diff --git a/build.gradle b/build.gradle index c5de9207..003762a3 100644 --- a/build.gradle +++ b/build.gradle @@ -13,23 +13,19 @@ buildscript { } dependencies { - classpath 'io.spring.gradle:spring-build-conventions:0.0.25.RELEASE' + classpath 'io.spring.gradle:spring-build-conventions:0.0.26.RELEASE' classpath "org.springframework.boot:spring-boot-gradle-plugin:$springBootVersion" - classpath 'io.spring.nohttp:nohttp-gradle:0.0.2.RELEASE' } } apply plugin: 'io.spring.convention.root' -apply plugin: 'io.spring.nohttp' - -repositories { - mavenCentral() -} group = 'org.springframework.session' description = 'Spring Session' subprojects { + apply plugin: 'io.spring.javaformat' + plugins.withType(JavaPlugin) { sourceCompatibility = JavaVersion.VERSION_1_8 diff --git a/etc/checkstyle/checkstyle.xml b/etc/checkstyle/checkstyle.xml index fba2b17f..ac5c5aeb 100644 --- a/etc/checkstyle/checkstyle.xml +++ b/etc/checkstyle/checkstyle.xml @@ -5,8 +5,10 @@ + + - - - - - - - - - - \ No newline at end of file diff --git a/etc/eclipse/eclipse-code-formatter.xml b/etc/eclipse/eclipse-code-formatter.xml deleted file mode 100644 index db0d768e..00000000 --- a/etc/eclipse/eclipse-code-formatter.xml +++ /dev/null @@ -1,295 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/etc/eclipse/org.eclipse.jdt.core.prefs b/etc/eclipse/org.eclipse.jdt.core.prefs deleted file mode 100644 index e44b6fc3..00000000 --- a/etc/eclipse/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,391 +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.codegen.inlineJsrBytecode=enabled -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.doc.comment.support=enabled -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.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=ignore -org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore -org.eclipse.jdt.core.compiler.problem.invalidJavadoc=warning -org.eclipse.jdt.core.compiler.problem.invalidJavadocTags=enabled -org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsDeprecatedRef=disabled -org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsNotVisibleRef=enabled -org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsVisibility=default -org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore -org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning -org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore -org.eclipse.jdt.core.compiler.problem.missingJavadocComments=ignore -org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsOverriding=disabled -org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsVisibility=public -org.eclipse.jdt.core.compiler.problem.missingJavadocTagDescription=all_standard_tags -org.eclipse.jdt.core.compiler.problem.missingJavadocTags=warning -org.eclipse.jdt.core.compiler.problem.missingJavadocTagsMethodTypeParameters=disabled -org.eclipse.jdt.core.compiler.problem.missingJavadocTagsOverriding=disabled -org.eclipse.jdt.core.compiler.problem.missingJavadocTagsVisibility=default -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.nullReference=ignore -org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning -org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore -org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore -org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore -org.eclipse.jdt.core.compiler.problem.rawTypeReference=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.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.undocumentedEmptyBlock=ignore -org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning -org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore -org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=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.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.unusedWarningToken=warning -org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.processAnnotations=disabled -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=false -org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true -org.eclipse.jdt.core.formatter.comment.indent_root_tags=false -org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=do not insert -org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=do not insert -org.eclipse.jdt.core.formatter.comment.line_length=90 -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=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=insert -org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=insert -org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=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=do not 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=90 -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=tab -org.eclipse.jdt.core.formatter.tabulation.size=4 -org.eclipse.jdt.core.formatter.use_on_off_tags=true -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 -org.eclipse.jdt.core.javaFormatter=org.springframework.ide.eclipse.jdt.formatter.javaformatter diff --git a/etc/eclipse/org.eclipse.jdt.ui.prefs b/etc/eclipse/org.eclipse.jdt.ui.prefs deleted file mode 100644 index 9952785e..00000000 --- a/etc/eclipse/org.eclipse.jdt.ui.prefs +++ /dev/null @@ -1,125 +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=true -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=true -cleanup.format_source_code_changes_only=false -cleanup.insert_inferred_type_arguments=false -cleanup.make_local_variable_final=false -cleanup.make_parameters_final=false -cleanup.make_private_fields_final=false -cleanup.make_type_abstract_if_missing_method=false -cleanup.make_variable_declarations_final=false -cleanup.never_use_blocks=false -cleanup.never_use_parentheses_in_expressions=true -cleanup.organize_imports=true -cleanup.qualify_static_field_accesses_with_declaring_class=false -cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true -cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true -cleanup.qualify_static_member_accesses_with_declaring_class=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=true -cleanup.remove_trailing_whitespaces_all=true -cleanup.remove_trailing_whitespaces_ignore_empty=false -cleanup.remove_unnecessary_casts=true -cleanup.remove_unnecessary_nls_tags=false -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=true -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=false -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=_Spring Boot Cleanup Conventions -cleanup_settings_version=2 -eclipse.preferences.version=1 -editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true -formatter_profile=Spring Session Java Conventions -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.springframework;\#; -org.eclipse.jdt.ui.javadoc=true -org.eclipse.jdt.ui.keywordthis=false -org.eclipse.jdt.ui.ondemandthreshold=9999 -org.eclipse.jdt.ui.overrideannotation=true -org.eclipse.jdt.ui.staticondemandthreshold=9999 -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=true -sp_cleanup.always_use_this_for_non_static_field_access=true -sp_cleanup.always_use_this_for_non_static_method_access=false -sp_cleanup.convert_to_enhanced_for_loop=false -sp_cleanup.correct_indentation=false -sp_cleanup.format_source_code=true -sp_cleanup.format_source_code_changes_only=false -sp_cleanup.make_local_variable_final=false -sp_cleanup.make_parameters_final=false -sp_cleanup.make_private_fields_final=false -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=false -sp_cleanup.on_save_use_additional_actions=true -sp_cleanup.organize_imports=true -sp_cleanup.qualify_static_field_accesses_with_declaring_class=false -sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_with_declaring_class=true -sp_cleanup.qualify_static_method_accesses_with_declaring_class=false -sp_cleanup.remove_private_constructors=true -sp_cleanup.remove_trailing_whitespaces=true -sp_cleanup.remove_trailing_whitespaces_all=true -sp_cleanup.remove_trailing_whitespaces_ignore_empty=false -sp_cleanup.remove_unnecessary_casts=true -sp_cleanup.remove_unnecessary_nls_tags=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_blocks=true -sp_cleanup.use_blocks_only_for_return_and_throw=false -sp_cleanup.use_parentheses_in_expressions=false -sp_cleanup.use_this_for_non_static_field_access=true -sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=false -sp_cleanup.use_this_for_non_static_method_access=false -sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true diff --git a/spring-session-core/src/main/java/org/springframework/session/FindByIndexNameSessionRepository.java b/spring-session-core/src/main/java/org/springframework/session/FindByIndexNameSessionRepository.java index ccab6386..4c917325 100644 --- a/spring-session-core/src/main/java/org/springframework/session/FindByIndexNameSessionRepository.java +++ b/spring-session-core/src/main/java/org/springframework/session/FindByIndexNameSessionRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,8 +27,7 @@ import java.util.Map; * @author Rob Winch * @author Vedran Pavic */ -public interface FindByIndexNameSessionRepository - extends SessionRepository { +public interface FindByIndexNameSessionRepository extends SessionRepository { /** * A session index that contains the current principal name (i.e. username). @@ -44,7 +43,6 @@ public interface FindByIndexNameSessionRepository /** * Find a {@link Map} of the session id to the {@link Session} of all sessions that * contain the specified index name index value. - * * @param indexName the name of the index (i.e. * {@link FindByIndexNameSessionRepository#PRINCIPAL_NAME_INDEX_NAME}) * @param indexValue the value of the index to search for. @@ -59,7 +57,6 @@ public interface FindByIndexNameSessionRepository * contain the index with the name * {@link FindByIndexNameSessionRepository#PRINCIPAL_NAME_INDEX_NAME} and the * specified principal name. - * * @param principalName the principal name * @return a {@code Map} (never {@code null}) of the session id to the {@code Session} * of all sessions that contain the specified principal name. If no results are found, diff --git a/spring-session-core/src/main/java/org/springframework/session/MapSession.java b/spring-session-core/src/main/java/org/springframework/session/MapSession.java index 443a3915..485883f1 100644 --- a/spring-session-core/src/main/java/org/springframework/session/MapSession.java +++ b/spring-session-core/src/main/java/org/springframework/session/MapSession.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,15 +47,20 @@ import java.util.UUID; * @since 1.0 */ public final class MapSession implements Session, Serializable { + /** * Default {@link #setMaxInactiveInterval(Duration)} (30 minutes). */ public static final int DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS = 1800; private String id; + private final String originalId; + private Map sessionAttrs = new HashMap<>(); + private Instant creationTime = Instant.now(); + private Instant lastAccessedTime = this.creationTime; /** @@ -70,12 +75,10 @@ public final class MapSession implements Session, Serializable { this(generateId()); } - /** * Creates a new instance with the specified id. This is preferred to the default * constructor when the id is known to prevent unnecessary consumption on entropy * which can be slow. - * * @param id the identifier to use */ public MapSession(String id) { @@ -85,7 +88,6 @@ public final class MapSession implements Session, Serializable { /** * Creates a new instance from the provided {@link Session}. - * * @param session the {@link Session} to initialize this {@link Session} with. Cannot * be null. */ @@ -95,8 +97,7 @@ public final class MapSession implements Session, Serializable { } this.id = session.getId(); this.originalId = this.id; - this.sessionAttrs = new HashMap<>( - session.getAttributeNames().size()); + this.sessionAttrs = new HashMap<>(session.getAttributeNames().size()); for (String attrName : session.getAttributeNames()) { Object attrValue = session.getAttribute(attrName); if (attrValue != null) { @@ -205,7 +206,6 @@ public final class MapSession implements Session, Serializable { * Sets the identifier for this {@link Session}. The id should be a secure random * generated value to prevent malicious users from guessing this value. The default is * a secure random generated identifier. - * * @param id the identifier for this session. */ public void setId(String id) { @@ -227,4 +227,5 @@ public final class MapSession implements Session, Serializable { } private static final long serialVersionUID = 7160779239673823561L; + } diff --git a/spring-session-core/src/main/java/org/springframework/session/MapSessionRepository.java b/spring-session-core/src/main/java/org/springframework/session/MapSessionRepository.java index b558047f..373c0182 100644 --- a/spring-session-core/src/main/java/org/springframework/session/MapSessionRepository.java +++ b/spring-session-core/src/main/java/org/springframework/session/MapSessionRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,7 +49,6 @@ public class MapSessionRepository implements SessionRepository { /** * Creates a new instance backed by the provided {@link java.util.Map}. This allows * injecting a distributed {@link java.util.Map}. - * * @param sessions the {@link java.util.Map} to use. Cannot be null. */ public MapSessionRepository(Map sessions) { @@ -99,8 +98,7 @@ public class MapSessionRepository implements SessionRepository { public MapSession createSession() { MapSession result = new MapSession(); if (this.defaultMaxInactiveInterval != null) { - result.setMaxInactiveInterval( - Duration.ofSeconds(this.defaultMaxInactiveInterval)); + result.setMaxInactiveInterval(Duration.ofSeconds(this.defaultMaxInactiveInterval)); } return result; } diff --git a/spring-session-core/src/main/java/org/springframework/session/ReactiveMapSessionRepository.java b/spring-session-core/src/main/java/org/springframework/session/ReactiveMapSessionRepository.java index 363a7401..ed3d843f 100644 --- a/spring-session-core/src/main/java/org/springframework/session/ReactiveMapSessionRepository.java +++ b/spring-session-core/src/main/java/org/springframework/session/ReactiveMapSessionRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,7 +51,6 @@ public class ReactiveMapSessionRepository implements ReactiveSessionRepository sessions) { @@ -101,8 +100,7 @@ public class ReactiveMapSessionRepository implements ReactiveSessionRepository { MapSession result = new MapSession(); if (this.defaultMaxInactiveInterval != null) { - result.setMaxInactiveInterval( - Duration.ofSeconds(this.defaultMaxInactiveInterval)); + result.setMaxInactiveInterval(Duration.ofSeconds(this.defaultMaxInactiveInterval)); } return Mono.just(result); }); diff --git a/spring-session-core/src/main/java/org/springframework/session/ReactiveSessionRepository.java b/spring-session-core/src/main/java/org/springframework/session/ReactiveSessionRepository.java index d167e493..2e41b9b2 100644 --- a/spring-session-core/src/main/java/org/springframework/session/ReactiveSessionRepository.java +++ b/spring-session-core/src/main/java/org/springframework/session/ReactiveSessionRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +36,6 @@ public interface ReactiveSessionRepository { * persisted. For example, the implementation returned might keep track of the changes * ensuring that only the delta needs to be persisted on a save. *

- * * @return a new {@link Session} that is capable of being persisted by this * {@link ReactiveSessionRepository} */ @@ -51,7 +50,6 @@ public interface ReactiveSessionRepository { * returning a {@link Session} that immediately persists any changes. In this case, * this method may not actually do anything. *

- * * @param session the {@link Session} to save * @return indicator of operation completion */ @@ -60,7 +58,6 @@ public interface ReactiveSessionRepository { /** * Gets the {@link Session} by the {@link Session#getId()} or null if no * {@link Session} is found. - * * @param id the {@link Session#getId()} to lookup * @return the {@link Session} by the {@link Session#getId()} or null if no * {@link Session} is found. diff --git a/spring-session-core/src/main/java/org/springframework/session/Session.java b/spring-session-core/src/main/java/org/springframework/session/Session.java index c34ec2eb..6be3445c 100644 --- a/spring-session-core/src/main/java/org/springframework/session/Session.java +++ b/spring-session-core/src/main/java/org/springframework/session/Session.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,13 +32,13 @@ public interface Session { /** * Gets a unique string that identifies the {@link Session}. - * * @return a unique string that identifies the {@link Session} */ String getId(); /** - * Changes the session id. After invoking the {@link #getId()} will return a new identifier. + * Changes the session id. After invoking the {@link #getId()} will return a new + * identifier. * @return the new session id which {@link #getId()} will now return */ String changeSessionId(); @@ -46,7 +46,6 @@ public interface Session { /** * Gets the Object associated with the specified name or null if no Object is * associated to that name. - * * @param the return type of the attribute * @param attributeName the name of the attribute to get * @return the Object associated with the specified name or null if no Object is @@ -65,8 +64,7 @@ public interface Session { default T getRequiredAttribute(String name) { T result = getAttribute(name); if (result == null) { - throw new IllegalArgumentException( - "Required attribute '" + name + "' is missing."); + throw new IllegalArgumentException("Required attribute '" + name + "' is missing."); } return result; } @@ -88,7 +86,6 @@ public interface Session { * Gets the attribute names that have a value associated with it. Each value can be * passed into {@link org.springframework.session.Session#getAttribute(String)} to * obtain the attribute value. - * * @return the attribute names that have a value associated with it. * @see #getAttribute(String) */ @@ -98,7 +95,6 @@ public interface Session { * Sets the attribute value for the provided attribute name. If the attributeValue is * null, it has the same result as removing the attribute with * {@link org.springframework.session.Session#removeAttribute(String)} . - * * @param attributeName the attribute name to set * @param attributeValue the value of the attribute to set. If null, the attribute * will be removed. @@ -113,21 +109,18 @@ public interface Session { /** * Gets the time when this session was created. - * * @return the time when this session was created. */ Instant getCreationTime(); /** * Sets the last accessed time. - * * @param lastAccessedTime the last accessed time */ void setLastAccessedTime(Instant lastAccessedTime); /** * Gets the last time this {@link Session} was accessed. - * * @return the last time the client sent a request associated with the session */ Instant getLastAccessedTime(); @@ -135,7 +128,6 @@ public interface Session { /** * Sets the maximum inactive interval between requests before this session will be * invalidated. A negative time indicates that the session will never timeout. - * * @param interval the amount of time that the {@link Session} should be kept alive * between client requests. */ @@ -144,7 +136,6 @@ public interface Session { /** * Gets the maximum inactive interval between requests before this session will be * invalidated. A negative time indicates that the session will never timeout. - * * @return the maximum inactive interval between requests before this session will be * invalidated. A negative time indicates that the session will never timeout. */ @@ -152,7 +143,6 @@ public interface Session { /** * Returns true if the session is expired. - * * @return true if the session is expired, else false. */ boolean isExpired(); diff --git a/spring-session-core/src/main/java/org/springframework/session/SessionRepository.java b/spring-session-core/src/main/java/org/springframework/session/SessionRepository.java index 13f34e33..7efe2f99 100644 --- a/spring-session-core/src/main/java/org/springframework/session/SessionRepository.java +++ b/spring-session-core/src/main/java/org/springframework/session/SessionRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,7 +34,6 @@ public interface SessionRepository { * persisted. For example, the implementation returned might keep track of the changes * ensuring that only the delta needs to be persisted on a save. *

- * * @return a new {@link Session} that is capable of being persisted by this * {@link SessionRepository} */ @@ -49,7 +48,6 @@ public interface SessionRepository { * returning a {@link Session} that immediately persists any changes. In this case, * this method may not actually do anything. *

- * * @param session the {@link Session} to save */ void save(S session); @@ -57,7 +55,6 @@ public interface SessionRepository { /** * Gets the {@link Session} by the {@link Session#getId()} or null if no * {@link Session} is found. - * * @param id the {@link org.springframework.session.Session#getId()} to lookup * @return the {@link Session} by the {@link Session#getId()} or null if no * {@link Session} is found. @@ -70,4 +67,5 @@ public interface SessionRepository { * @param id the {@link org.springframework.session.Session#getId()} to delete */ void deleteById(String id); + } diff --git a/spring-session-core/src/main/java/org/springframework/session/config/annotation/web/http/EnableSpringHttpSession.java b/spring-session-core/src/main/java/org/springframework/session/config/annotation/web/http/EnableSpringHttpSession.java index 50c2cc1a..daa43ebd 100644 --- a/spring-session-core/src/main/java/org/springframework/session/config/annotation/web/http/EnableSpringHttpSession.java +++ b/spring-session-core/src/main/java/org/springframework/session/config/annotation/web/http/EnableSpringHttpSession.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -76,4 +76,5 @@ import org.springframework.session.events.SessionDestroyedEvent; @Import(SpringHttpSessionConfiguration.class) @Configuration public @interface EnableSpringHttpSession { + } diff --git a/spring-session-core/src/main/java/org/springframework/session/config/annotation/web/http/SpringHttpSessionConfiguration.java b/spring-session-core/src/main/java/org/springframework/session/config/annotation/web/http/SpringHttpSessionConfiguration.java index 896e1882..014b0467 100644 --- a/spring-session-core/src/main/java/org/springframework/session/config/annotation/web/http/SpringHttpSessionConfiguration.java +++ b/spring-session-core/src/main/java/org/springframework/session/config/annotation/web/http/SpringHttpSessionConfiguration.java @@ -88,7 +88,6 @@ import org.springframework.util.ObjectUtils; * @author Rob Winch * @author Vedran Pavic * @since 1.1 - * * @see EnableSpringHttpSession */ @Configuration(proxyBeanMethods = false) @@ -110,8 +109,7 @@ public class SpringHttpSessionConfiguration implements ApplicationContextAware { @PostConstruct public void init() { - CookieSerializer cookieSerializer = (this.cookieSerializer != null) - ? this.cookieSerializer + CookieSerializer cookieSerializer = (this.cookieSerializer != null) ? this.cookieSerializer : createDefaultCookieSerializer(); this.defaultHttpSessionIdResolver.setCookieSerializer(cookieSerializer); } @@ -124,21 +122,16 @@ public class SpringHttpSessionConfiguration implements ApplicationContextAware { @Bean public SessionRepositoryFilter springSessionRepositoryFilter( SessionRepository sessionRepository) { - SessionRepositoryFilter sessionRepositoryFilter = new SessionRepositoryFilter<>( - sessionRepository); + SessionRepositoryFilter sessionRepositoryFilter = new SessionRepositoryFilter<>(sessionRepository); sessionRepositoryFilter.setHttpSessionIdResolver(this.httpSessionIdResolver); return sessionRepositoryFilter; } @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { - if (ClassUtils.isPresent( - "org.springframework.security.web.authentication.RememberMeServices", - null)) { + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + if (ClassUtils.isPresent("org.springframework.security.web.authentication.RememberMeServices", null)) { this.usesSpringSessionRememberMeServices = !ObjectUtils - .isEmpty(applicationContext - .getBeanNamesForType(SpringSessionRememberMeServices.class)); + .isEmpty(applicationContext.getBeanNamesForType(SpringSessionRememberMeServices.class)); } } @@ -170,8 +163,7 @@ public class SpringHttpSessionConfiguration implements ApplicationContextAware { sessionCookieConfig = this.servletContext.getSessionCookieConfig(); } catch (UnsupportedOperationException ex) { - this.logger - .warn("Unable to obtain SessionCookieConfig: " + ex.getMessage()); + this.logger.warn("Unable to obtain SessionCookieConfig: " + ex.getMessage()); } if (sessionCookieConfig != null) { if (sessionCookieConfig.getName() != null) { @@ -189,8 +181,7 @@ public class SpringHttpSessionConfiguration implements ApplicationContextAware { } } if (this.usesSpringSessionRememberMeServices) { - cookieSerializer.setRememberMeRequestAttribute( - SpringSessionRememberMeServices.REMEMBER_ME_LOGIN_ATTR); + cookieSerializer.setRememberMeRequestAttribute(SpringSessionRememberMeServices.REMEMBER_ME_LOGIN_ATTR); } return cookieSerializer; } diff --git a/spring-session-core/src/main/java/org/springframework/session/config/annotation/web/server/EnableSpringWebSession.java b/spring-session-core/src/main/java/org/springframework/session/config/annotation/web/server/EnableSpringWebSession.java index f0ad09de..6baede4b 100644 --- a/spring-session-core/src/main/java/org/springframework/session/config/annotation/web/server/EnableSpringWebSession.java +++ b/spring-session-core/src/main/java/org/springframework/session/config/annotation/web/server/EnableSpringWebSession.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,9 +23,10 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; /** - * Add this annotation to a {@code @Configuration} class to configure a {@code WebSessionManager} for a WebFlux - * application. This annotation assumes a {@code ReactiveSessionRepository} is defined somewhere in the application - * context. If not, it will fail with a clear error message. For example: + * Add this annotation to a {@code @Configuration} class to configure a + * {@code WebSessionManager} for a WebFlux application. This annotation assumes a + * {@code ReactiveSessionRepository} is defined somewhere in the application context. If + * not, it will fail with a clear error message. For example: * *
  * 
@@ -39,8 +40,7 @@ import org.springframework.context.annotation.Import;
  *     }
  *
  * }
- * 
- * 
+ * * * @author Greg Turnquist * @since 2.0 @@ -51,4 +51,5 @@ import org.springframework.context.annotation.Import; @Import(SpringWebSessionConfiguration.class) @Configuration public @interface EnableSpringWebSession { + } diff --git a/spring-session-core/src/main/java/org/springframework/session/config/annotation/web/server/SpringWebSessionConfiguration.java b/spring-session-core/src/main/java/org/springframework/session/config/annotation/web/server/SpringWebSessionConfiguration.java index 9a0b34bd..5a6dc3e0 100644 --- a/spring-session-core/src/main/java/org/springframework/session/config/annotation/web/server/SpringWebSessionConfiguration.java +++ b/spring-session-core/src/main/java/org/springframework/session/config/annotation/web/server/SpringWebSessionConfiguration.java @@ -27,12 +27,12 @@ import org.springframework.web.server.session.WebSessionIdResolver; import org.springframework.web.server.session.WebSessionManager; /** - * Wire up a {@link WebSessionManager} using a Reactive {@link ReactiveSessionRepository} from the application context. + * Wire up a {@link WebSessionManager} using a Reactive {@link ReactiveSessionRepository} + * from the application context. * * @author Greg Turnquist * @author Rob Winch * @since 2.0 - * * @see EnableSpringWebSession */ @Configuration(proxyBeanMethods = false) @@ -45,10 +45,11 @@ public class SpringWebSessionConfiguration { private WebSessionIdResolver webSessionIdResolver; /** - * Configure a {@link WebSessionManager} using a provided {@link ReactiveSessionRepository}. - * + * Configure a {@link WebSessionManager} using a provided + * {@link ReactiveSessionRepository}. * @param repository a bean that implements {@link ReactiveSessionRepository}. - * @return a configured {@link WebSessionManager} registered with a preconfigured name. + * @return a configured {@link WebSessionManager} registered with a preconfigured + * name. */ @Bean(WebHttpHandlerBuilder.WEB_SESSION_MANAGER_BEAN_NAME) public WebSessionManager webSessionManager(ReactiveSessionRepository repository) { @@ -62,4 +63,5 @@ public class SpringWebSessionConfiguration { return manager; } + } diff --git a/spring-session-core/src/main/java/org/springframework/session/events/AbstractSessionEvent.java b/spring-session-core/src/main/java/org/springframework/session/events/AbstractSessionEvent.java index 41f117e8..c6f135a4 100644 --- a/spring-session-core/src/main/java/org/springframework/session/events/AbstractSessionEvent.java +++ b/spring-session-core/src/main/java/org/springframework/session/events/AbstractSessionEvent.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,6 @@ public abstract class AbstractSessionEvent extends ApplicationEvent { * Gets the {@link Session} that was destroyed. For some {@link SessionRepository} * implementations it may not be possible to get the original session in which case * this may be null. - * * @param the type of Session * @return the expired {@link Session} or null if the data store does not support * obtaining it diff --git a/spring-session-core/src/main/java/org/springframework/session/security/SpringSessionBackedSessionInformation.java b/spring-session-core/src/main/java/org/springframework/session/security/SpringSessionBackedSessionInformation.java index eb3d563f..00373801 100644 --- a/spring-session-core/src/main/java/org/springframework/session/security/SpringSessionBackedSessionInformation.java +++ b/spring-session-core/src/main/java/org/springframework/session/security/SpringSessionBackedSessionInformation.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,23 +36,18 @@ import org.springframework.session.SessionRepository; * @author Vedran Pavic * @since 1.3 */ -class SpringSessionBackedSessionInformation - extends SessionInformation { +class SpringSessionBackedSessionInformation extends SessionInformation { - static final String EXPIRED_ATTR = SpringSessionBackedSessionInformation.class - .getName() + ".EXPIRED"; + static final String EXPIRED_ATTR = SpringSessionBackedSessionInformation.class.getName() + ".EXPIRED"; - private static final Log logger = LogFactory - .getLog(SpringSessionBackedSessionInformation.class); + private static final Log logger = LogFactory.getLog(SpringSessionBackedSessionInformation.class); private static final String SPRING_SECURITY_CONTEXT = "SPRING_SECURITY_CONTEXT"; private final SessionRepository sessionRepository; - SpringSessionBackedSessionInformation(S session, - SessionRepository sessionRepository) { - super(resolvePrincipal(session), session.getId(), - Date.from(session.getLastAccessedTime())); + SpringSessionBackedSessionInformation(S session, SessionRepository sessionRepository) { + super(resolvePrincipal(session), session.getId(), Date.from(session.getLastAccessedTime())); this.sessionRepository = sessionRepository; Boolean expired = session.getAttribute(EXPIRED_ATTR); if (Boolean.TRUE.equals(expired)) { @@ -62,20 +57,16 @@ class SpringSessionBackedSessionInformation /** * Tries to determine the principal's name from the given Session. - * * @param session the session * @return the principal's name, or empty String if it couldn't be determined */ private static String resolvePrincipal(Session session) { - String principalName = session - .getAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME); + String principalName = session.getAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME); if (principalName != null) { return principalName; } - SecurityContext securityContext = session - .getAttribute(SPRING_SECURITY_CONTEXT); - if (securityContext != null - && securityContext.getAuthentication() != null) { + SecurityContext securityContext = session.getAttribute(SPRING_SECURITY_CONTEXT); + if (securityContext != null && securityContext.getAuthentication() != null) { return securityContext.getAuthentication().getName(); } return ""; @@ -84,9 +75,8 @@ class SpringSessionBackedSessionInformation @Override public void expireNow() { if (logger.isDebugEnabled()) { - logger.debug("Expiring session " + getSessionId() + " for user '" - + getPrincipal() + "', presumably because maximum allowed concurrent " - + "sessions was exceeded"); + logger.debug("Expiring session " + getSessionId() + " for user '" + getPrincipal() + + "', presumably because maximum allowed concurrent " + "sessions was exceeded"); } super.expireNow(); S session = this.sessionRepository.findById(getSessionId()); @@ -95,8 +85,7 @@ class SpringSessionBackedSessionInformation this.sessionRepository.save(session); } else { - logger.info("Could not find Session with id " + getSessionId() - + " to mark as expired"); + logger.info("Could not find Session with id " + getSessionId() + " to mark as expired"); } } diff --git a/spring-session-core/src/main/java/org/springframework/session/security/SpringSessionBackedSessionRegistry.java b/spring-session-core/src/main/java/org/springframework/session/security/SpringSessionBackedSessionRegistry.java index e42525d0..f999cb6b 100644 --- a/spring-session-core/src/main/java/org/springframework/session/security/SpringSessionBackedSessionRegistry.java +++ b/spring-session-core/src/main/java/org/springframework/session/security/SpringSessionBackedSessionRegistry.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,13 +44,11 @@ import org.springframework.util.Assert; * @author Vedran Pavic * @since 1.3 */ -public class SpringSessionBackedSessionRegistry - implements SessionRegistry { +public class SpringSessionBackedSessionRegistry implements SessionRegistry { private final FindByIndexNameSessionRepository sessionRepository; - public SpringSessionBackedSessionRegistry( - FindByIndexNameSessionRepository sessionRepository) { + public SpringSessionBackedSessionRegistry(FindByIndexNameSessionRepository sessionRepository) { Assert.notNull(sessionRepository, "sessionRepository cannot be null"); this.sessionRepository = sessionRepository; } @@ -63,16 +61,13 @@ public class SpringSessionBackedSessionRegistry } @Override - public List getAllSessions(Object principal, - boolean includeExpiredSessions) { - Collection sessions = this.sessionRepository - .findByPrincipalName(name(principal)).values(); + public List getAllSessions(Object principal, boolean includeExpiredSessions) { + Collection sessions = this.sessionRepository.findByPrincipalName(name(principal)).values(); List infos = new ArrayList<>(); for (S session : sessions) { - if (includeExpiredSessions || !Boolean.TRUE.equals(session - .getAttribute(SpringSessionBackedSessionInformation.EXPIRED_ATTR))) { - infos.add(new SpringSessionBackedSessionInformation<>(session, - this.sessionRepository)); + if (includeExpiredSessions + || !Boolean.TRUE.equals(session.getAttribute(SpringSessionBackedSessionInformation.EXPIRED_ATTR))) { + infos.add(new SpringSessionBackedSessionInformation<>(session, this.sessionRepository)); } } return infos; @@ -82,8 +77,7 @@ public class SpringSessionBackedSessionRegistry public SessionInformation getSessionInformation(String sessionId) { S session = this.sessionRepository.findById(sessionId); if (session != null) { - return new SpringSessionBackedSessionInformation<>(session, - this.sessionRepository); + return new SpringSessionBackedSessionInformation<>(session, this.sessionRepository); } return null; } @@ -111,7 +105,6 @@ public class SpringSessionBackedSessionRegistry /** * Derives a String name for the given principal. - * * @param principal as provided by Spring Security * @return name of the principal, or its {@code toString()} representation if no name * could be derived diff --git a/spring-session-core/src/main/java/org/springframework/session/security/web/authentication/SpringSessionRememberMeServices.java b/spring-session-core/src/main/java/org/springframework/session/security/web/authentication/SpringSessionRememberMeServices.java index f14739e4..2afe12e2 100644 --- a/spring-session-core/src/main/java/org/springframework/session/security/web/authentication/SpringSessionRememberMeServices.java +++ b/spring-session-core/src/main/java/org/springframework/session/security/web/authentication/SpringSessionRememberMeServices.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,21 +36,19 @@ import org.springframework.util.Assert; * @author Vedran Pavic * @since 1.3.0 */ -public class SpringSessionRememberMeServices - implements RememberMeServices, LogoutHandler { +public class SpringSessionRememberMeServices implements RememberMeServices, LogoutHandler { /** * Remember-me login request attribute name. */ - public static final String REMEMBER_ME_LOGIN_ATTR = SpringSessionRememberMeServices.class - .getName() + "REMEMBER_ME_LOGIN_ATTR"; + public static final String REMEMBER_ME_LOGIN_ATTR = SpringSessionRememberMeServices.class.getName() + + "REMEMBER_ME_LOGIN_ATTR"; private static final String DEFAULT_REMEMBERME_PARAMETER = "remember-me"; private static final int THIRTY_DAYS_SECONDS = 2592000; - private static final Log logger = LogFactory - .getLog(SpringSessionRememberMeServices.class); + private static final Log logger = LogFactory.getLog(SpringSessionRememberMeServices.class); private String rememberMeParameterName = DEFAULT_REMEMBERME_PARAMETER; @@ -61,22 +59,19 @@ public class SpringSessionRememberMeServices private String sessionAttrToDeleteOnLoginFail = HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY; @Override - public final Authentication autoLogin(HttpServletRequest request, - HttpServletResponse response) { + public final Authentication autoLogin(HttpServletRequest request, HttpServletResponse response) { return null; } @Override - public final void loginFail(HttpServletRequest request, - HttpServletResponse response) { + public final void loginFail(HttpServletRequest request, HttpServletResponse response) { logout(request); } @Override - public final void loginSuccess(HttpServletRequest request, - HttpServletResponse response, Authentication successfulAuthentication) { - if (!this.alwaysRemember - && !rememberMeRequested(request, this.rememberMeParameterName)) { + public final void loginSuccess(HttpServletRequest request, HttpServletResponse response, + Authentication successfulAuthentication) { + if (!this.alwaysRemember && !rememberMeRequested(request, this.rememberMeParameterName)) { logger.debug("Remember-me login not requested."); return; } @@ -103,8 +98,7 @@ public class SpringSessionRememberMeServices } } if (logger.isDebugEnabled()) { - logger.debug("Did not send remember-me cookie (principal did not set " - + "parameter '" + parameter + "')"); + logger.debug("Did not send remember-me cookie (principal did not set " + "parameter '" + parameter + "')"); } return false; } @@ -116,8 +110,7 @@ public class SpringSessionRememberMeServices * @param rememberMeParameterName the request parameter */ public void setRememberMeParameterName(String rememberMeParameterName) { - Assert.hasText(rememberMeParameterName, - "rememberMeParameterName cannot be empty or null"); + Assert.hasText(rememberMeParameterName, "rememberMeParameterName cannot be empty or null"); this.rememberMeParameterName = rememberMeParameterName; } @@ -130,8 +123,7 @@ public class SpringSessionRememberMeServices } @Override - public void logout(HttpServletRequest request, HttpServletResponse response, - Authentication authentication) { + public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { logout(request); } @@ -142,4 +134,5 @@ public class SpringSessionRememberMeServices session.removeAttribute(this.sessionAttrToDeleteOnLoginFail); } } + } diff --git a/spring-session-core/src/main/java/org/springframework/session/web/context/AbstractHttpSessionApplicationInitializer.java b/spring-session-core/src/main/java/org/springframework/session/web/context/AbstractHttpSessionApplicationInitializer.java index 4206bb78..1d077d03 100644 --- a/spring-session-core/src/main/java/org/springframework/session/web/context/AbstractHttpSessionApplicationInitializer.java +++ b/spring-session-core/src/main/java/org/springframework/session/web/context/AbstractHttpSessionApplicationInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,8 +71,7 @@ import org.springframework.web.filter.DelegatingFilterProxy; * */ @Order(100) -public abstract class AbstractHttpSessionApplicationInitializer - implements WebApplicationInitializer { +public abstract class AbstractHttpSessionApplicationInitializer implements WebApplicationInitializer { private static final String SERVLET_CONTEXT_PREFIX = "org.springframework.web.servlet.FrameworkServlet.CONTEXT."; @@ -98,12 +97,10 @@ public abstract class AbstractHttpSessionApplicationInitializer /** * Creates a new instance that will instantiate the {@link ContextLoaderListener} with * the specified classes. - * * @param configurationClasses {@code @Configuration} classes that will be used to * configure the context */ - protected AbstractHttpSessionApplicationInitializer( - Class... configurationClasses) { + protected AbstractHttpSessionApplicationInitializer(Class... configurationClasses) { this.configurationClasses = configurationClasses; } @@ -125,8 +122,7 @@ public abstract class AbstractHttpSessionApplicationInitializer */ private void insertSessionRepositoryFilter(ServletContext servletContext) { String filterName = DEFAULT_FILTER_NAME; - DelegatingFilterProxy springSessionRepositoryFilter = new DelegatingFilterProxy( - filterName); + DelegatingFilterProxy springSessionRepositoryFilter = new DelegatingFilterProxy(filterName); String contextAttribute = getWebApplicationContextAttribute(); if (contextAttribute != null) { springSessionRepositoryFilter.setContextAttribute(contextAttribute); @@ -138,7 +134,6 @@ public abstract class AbstractHttpSessionApplicationInitializer * Inserts the provided {@link Filter}s before existing {@link Filter}s using default * generated names, {@link #getSessionDispatcherTypes()}, and * {@link #isAsyncSessionSupported()}. - * * @param servletContext the {@link ServletContext} to use * @param filters the {@link Filter}s to register */ @@ -150,7 +145,6 @@ public abstract class AbstractHttpSessionApplicationInitializer * Inserts the provided {@link Filter}s after existing {@link Filter}s using default * generated names, {@link #getSessionDispatcherTypes()}, and * {@link #isAsyncSessionSupported()}. - * * @param servletContext the {@link ServletContext} to use * @param filters the {@link Filter}s to register */ @@ -161,22 +155,18 @@ public abstract class AbstractHttpSessionApplicationInitializer /** * Registers the provided {@link Filter}s using default generated names, * {@link #getSessionDispatcherTypes()}, and {@link #isAsyncSessionSupported()}. - * * @param servletContext the {@link ServletContext} to use * @param insertBeforeOtherFilters if true, will insert the provided {@link Filter}s * before other {@link Filter}s. Otherwise, will insert the {@link Filter}s after * other {@link Filter}s. * @param filters the {@link Filter}s to register */ - private void registerFilters(ServletContext servletContext, - boolean insertBeforeOtherFilters, Filter... filters) { + private void registerFilters(ServletContext servletContext, boolean insertBeforeOtherFilters, Filter... filters) { Assert.notEmpty(filters, "filters cannot be null or empty"); for (Filter filter : filters) { if (filter == null) { - throw new IllegalArgumentException( - "filters cannot contain null values. Got " - + Arrays.asList(filters)); + throw new IllegalArgumentException("filters cannot contain null values. Got " + Arrays.asList(filters)); } String filterName = Conventions.getVariableName(filter); registerFilter(servletContext, insertBeforeOtherFilters, filterName, filter); @@ -186,25 +176,22 @@ public abstract class AbstractHttpSessionApplicationInitializer /** * Registers the provided filter using the {@link #isAsyncSessionSupported()} and * {@link #getSessionDispatcherTypes()}. - * * @param servletContext the servlet context * @param insertBeforeOtherFilters should this Filter be inserted before or after * other {@link Filter} * @param filterName the filter name * @param filter the filter */ - private void registerFilter(ServletContext servletContext, - boolean insertBeforeOtherFilters, String filterName, Filter filter) { + private void registerFilter(ServletContext servletContext, boolean insertBeforeOtherFilters, String filterName, + Filter filter) { Dynamic registration = servletContext.addFilter(filterName, filter); if (registration == null) { - throw new IllegalStateException( - "Duplicate Filter registration for '" + filterName - + "'. Check to ensure the Filter is only configured once."); + throw new IllegalStateException("Duplicate Filter registration for '" + filterName + + "'. Check to ensure the Filter is only configured once."); } registration.setAsyncSupported(isAsyncSessionSupported()); EnumSet dispatcherTypes = getSessionDispatcherTypes(); - registration.addMappingForUrlPatterns(dispatcherTypes, !insertBeforeOtherFilters, - "/*"); + registration.addMappingForUrlPatterns(dispatcherTypes, !insertBeforeOtherFilters, "/*"); } /** @@ -218,7 +205,6 @@ public abstract class AbstractHttpSessionApplicationInitializer * {@link ApplicationContext} is used to look up the springSessionRepositoryFilter * bean. *

- * * @return the {@link DelegatingFilterProxy#getContextAttribute()} or null if the * parent {@link ApplicationContext} should be used */ @@ -241,7 +227,6 @@ public abstract class AbstractHttpSessionApplicationInitializer * name, you can return "dispatcher" from this method to use the DispatcherServlet's * {@link WebApplicationContext}. *

- * * @return the {@code } of the DispatcherServlet to use its * {@link WebApplicationContext} or null (default) to use the parent * {@link ApplicationContext}. @@ -271,17 +256,16 @@ public abstract class AbstractHttpSessionApplicationInitializer * @return the {@link DispatcherType} for the filter */ protected EnumSet getSessionDispatcherTypes() { - return EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, - DispatcherType.ASYNC); + return EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.ASYNC); } /** * Determine if the springSessionRepositoryFilter should be marked as supporting * asynch. Default is true. - * * @return true if springSessionRepositoryFilter should be marked as supporting asynch */ protected boolean isAsyncSessionSupported() { return true; } + } diff --git a/spring-session-core/src/main/java/org/springframework/session/web/http/CookieHttpSessionIdResolver.java b/spring-session-core/src/main/java/org/springframework/session/web/http/CookieHttpSessionIdResolver.java index 658fc67e..16327d75 100644 --- a/spring-session-core/src/main/java/org/springframework/session/web/http/CookieHttpSessionIdResolver.java +++ b/spring-session-core/src/main/java/org/springframework/session/web/http/CookieHttpSessionIdResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,8 +63,8 @@ import org.springframework.session.web.http.CookieSerializer.CookieValue; */ public final class CookieHttpSessionIdResolver implements HttpSessionIdResolver { - private static final String WRITTEN_SESSION_ID_ATTR = CookieHttpSessionIdResolver.class - .getName().concat(".WRITTEN_SESSION_ID_ATTR"); + private static final String WRITTEN_SESSION_ID_ATTR = CookieHttpSessionIdResolver.class.getName() + .concat(".WRITTEN_SESSION_ID_ATTR"); private CookieSerializer cookieSerializer = new DefaultCookieSerializer(); @@ -74,14 +74,12 @@ public final class CookieHttpSessionIdResolver implements HttpSessionIdResolver } @Override - public void setSessionId(HttpServletRequest request, HttpServletResponse response, - String sessionId) { + public void setSessionId(HttpServletRequest request, HttpServletResponse response, String sessionId) { if (sessionId.equals(request.getAttribute(WRITTEN_SESSION_ID_ATTR))) { return; } request.setAttribute(WRITTEN_SESSION_ID_ATTR, sessionId); - this.cookieSerializer - .writeCookieValue(new CookieValue(request, response, sessionId)); + this.cookieSerializer.writeCookieValue(new CookieValue(request, response, sessionId)); } @Override @@ -91,7 +89,6 @@ public final class CookieHttpSessionIdResolver implements HttpSessionIdResolver /** * Sets the {@link CookieSerializer} to be used. - * * @param cookieSerializer the cookieSerializer to set. Cannot be null. */ public void setCookieSerializer(CookieSerializer cookieSerializer) { diff --git a/spring-session-core/src/main/java/org/springframework/session/web/http/CookieSerializer.java b/spring-session-core/src/main/java/org/springframework/session/web/http/CookieSerializer.java index b384d56b..5d8091a5 100644 --- a/spring-session-core/src/main/java/org/springframework/session/web/http/CookieSerializer.java +++ b/spring-session-core/src/main/java/org/springframework/session/web/http/CookieSerializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,7 +32,6 @@ public interface CookieSerializer { /** * Writes a given {@link CookieValue} to the provided {@link HttpServletResponse}. - * * @param cookieValue the {@link CookieValue} to write to * {@link CookieValue#getResponse()}. Cannot be null. */ @@ -43,7 +42,6 @@ public interface CookieSerializer { * List since there can be multiple {@link Cookie} in a single request with a matching * name. For example, one Cookie may have a path of / and another of /context, but the * path is not transmitted in the request. - * * @param request the {@link HttpServletRequest} to read the cookie from. Cannot be * null. * @return the values of all the matching cookies @@ -70,7 +68,6 @@ public interface CookieSerializer { /** * Creates a new instance. - * * @param request the {@link HttpServletRequest} to use. Useful for determining * the context in which the cookie is set. Cannot be null. * @param response the {@link HttpServletResponse} to use. @@ -78,8 +75,7 @@ public interface CookieSerializer { * modified by the {@link CookieSerializer} when writing to the actual cookie so * long as the original value is returned when the cookie is read. */ - public CookieValue(HttpServletRequest request, HttpServletResponse response, - String cookieValue) { + public CookieValue(HttpServletRequest request, HttpServletResponse response, String cookieValue) { this.request = request; this.response = response; this.cookieValue = cookieValue; @@ -108,7 +104,6 @@ public interface CookieSerializer { * The value to be written. This value may be modified by the * {@link CookieSerializer} before written to the cookie. However, the value must * be the same as the original when it is read back in. - * * @return the value to be written */ public String getCookieValue() { diff --git a/spring-session-core/src/main/java/org/springframework/session/web/http/DefaultCookieSerializer.java b/spring-session-core/src/main/java/org/springframework/session/web/http/DefaultCookieSerializer.java index bb6aab9d..9bc1a887 100644 --- a/spring-session-core/src/main/java/org/springframework/session/web/http/DefaultCookieSerializer.java +++ b/spring-session-core/src/main/java/org/springframework/session/web/http/DefaultCookieSerializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -97,15 +97,12 @@ public class DefaultCookieSerializer implements CookieSerializer { if (cookies != null) { for (Cookie cookie : cookies) { if (this.cookieName.equals(cookie.getName())) { - String sessionId = (this.useBase64Encoding - ? base64Decode(cookie.getValue()) - : cookie.getValue()); + String sessionId = (this.useBase64Encoding ? base64Decode(cookie.getValue()) : cookie.getValue()); if (sessionId == null) { continue; } if (this.jvmRoute != null && sessionId.endsWith(this.jvmRoute)) { - sessionId = sessionId.substring(0, - sessionId.length() - this.jvmRoute.length()); + sessionId = sessionId.substring(0, sessionId.length() - this.jvmRoute.length()); } matchingCookieValues.add(sessionId); } @@ -135,11 +132,9 @@ public class DefaultCookieSerializer implements CookieSerializer { int maxAge = getMaxAge(cookieValue); if (maxAge > -1) { sb.append("; Max-Age=").append(cookieValue.getCookieMaxAge()); - OffsetDateTime expires = (maxAge != 0) - ? OffsetDateTime.now().plusSeconds(maxAge) + OffsetDateTime expires = (maxAge != 0) ? OffsetDateTime.now().plusSeconds(maxAge) : Instant.EPOCH.atOffset(ZoneOffset.UTC); - sb.append("; Expires=") - .append(expires.format(DateTimeFormatter.RFC_1123_DATE_TIME)); + sb.append("; Expires=").append(expires.format(DateTimeFormatter.RFC_1123_DATE_TIME)); } String domain = getDomainName(request); if (domain != null && domain.length() > 0) { @@ -214,10 +209,8 @@ public class DefaultCookieSerializer implements CookieSerializer { char[] chars = value.toCharArray(); for (int i = start; i < end; i++) { char c = chars[i]; - if (c < 0x21 || c == 0x22 || c == 0x2c || c == 0x3b || c == 0x5c - || c == 0x7f) { - throw new IllegalArgumentException( - "Invalid character in cookie value: " + Integer.toString(c)); + if (c < 0x21 || c == 0x22 || c == 0x2c || c == 0x3b || c == 0x5c || c == 0x7f) { + throw new IllegalArgumentException("Invalid character in cookie value: " + Integer.toString(c)); } } } @@ -225,8 +218,8 @@ public class DefaultCookieSerializer implements CookieSerializer { private int getMaxAge(CookieValue cookieValue) { int maxAge = cookieValue.getCookieMaxAge(); if (maxAge < 0) { - if (this.rememberMeRequestAttribute != null && cookieValue.getRequest() - .getAttribute(this.rememberMeRequestAttribute) != null) { + if (this.rememberMeRequestAttribute != null + && cookieValue.getRequest().getAttribute(this.rememberMeRequestAttribute) != null) { // the cookie is only written at time of session creation, so we rely on // session expiration rather than cookie expiration if remember me is // enabled @@ -247,8 +240,7 @@ public class DefaultCookieSerializer implements CookieSerializer { while (i < chars.length) { prev = cur; cur = chars[i]; - if (!domainValid.get(cur) - || ((prev == '.' || prev == -1) && (cur == '.' || cur == '-')) + if (!domainValid.get(cur) || ((prev == '.' || prev == -1) && (cur == '.' || cur == '-')) || (prev == '-' && cur == '.')) { throw new IllegalArgumentException("Invalid cookie domain: " + domain); } @@ -270,7 +262,6 @@ public class DefaultCookieSerializer implements CookieSerializer { /** * Sets if a Cookie marked as secure should be used. The default is to use the value * of {@link HttpServletRequest#isSecure()}. - * * @param useSecureCookie determines if the cookie should be marked as secure. */ public void setUseSecureCookie(boolean useSecureCookie) { @@ -279,7 +270,6 @@ public class DefaultCookieSerializer implements CookieSerializer { /** * Sets if a Cookie marked as HTTP Only should be used. The default is true. - * * @param useHttpOnlyCookie determines if the cookie should be marked as HTTP Only. */ public void setUseHttpOnlyCookie(boolean useHttpOnlyCookie) { @@ -296,7 +286,6 @@ public class DefaultCookieSerializer implements CookieSerializer { /** * Sets the path of the Cookie. The default is to use the context path from the * {@link HttpServletRequest}. - * * @param cookiePath the path of the Cookie. If null, the default of the context path * will be used. */ @@ -314,7 +303,6 @@ public class DefaultCookieSerializer implements CookieSerializer { /** * Sets the maxAge property of the Cookie. The default is to delete the cookie when * the browser is closed. - * * @param cookieMaxAge the maxAge property of the Cookie */ public void setCookieMaxAge(int cookieMaxAge) { @@ -325,14 +313,12 @@ public class DefaultCookieSerializer implements CookieSerializer { * Sets an explicit Domain Name. This allow the domain of "example.com" to be used * when the request comes from www.example.com. This allows for sharing the cookie * across subdomains. The default is to use the current domain. - * * @param domainName the name of the domain to use. (i.e. "example.com") * @throws IllegalStateException if the domainNamePattern is also set */ public void setDomainName(String domainName) { if (this.domainNamePattern != null) { - throw new IllegalStateException( - "Cannot set both domainName and domainNamePattern"); + throw new IllegalStateException("Cannot set both domainName and domainNamePattern"); } this.domainName = domainName; } @@ -362,18 +348,15 @@ public class DefaultCookieSerializer implements CookieSerializer { *
  • localhost - null
  • *
  • 127.0.1.1 - null
  • * - * * @param domainNamePattern the case insensitive pattern to extract the domain name * with * @throws IllegalStateException if the domainName is also set */ public void setDomainNamePattern(String domainNamePattern) { if (this.domainName != null) { - throw new IllegalStateException( - "Cannot set both domainName and domainNamePattern"); + throw new IllegalStateException("Cannot set both domainName and domainNamePattern"); } - this.domainNamePattern = Pattern.compile(domainNamePattern, - Pattern.CASE_INSENSITIVE); + this.domainNamePattern = Pattern.compile(domainNamePattern, Pattern.CASE_INSENSITIVE); } /** @@ -390,7 +373,6 @@ public class DefaultCookieSerializer implements CookieSerializer { * To use set a custom route on each JVM instance and setup a frontend proxy to * forward all requests to the JVM based on the route. *

    - * * @param jvmRoute the JVM Route to use (i.e. "node01jvmA", "n01ja", etc) */ public void setJvmRoute(String jvmRoute) { @@ -401,7 +383,6 @@ public class DefaultCookieSerializer implements CookieSerializer { * Set if the Base64 encoding of cookie value should be used. This is valuable in * order to support RFC 6265 which * recommends using Base 64 encoding to the cookie value. - * * @param useBase64Encoding the flag to indicate whether to use Base64 encoding */ public void setUseBase64Encoding(boolean useBase64Encoding) { @@ -416,8 +397,7 @@ public class DefaultCookieSerializer implements CookieSerializer { */ public void setRememberMeRequestAttribute(String rememberMeRequestAttribute) { if (rememberMeRequestAttribute == null) { - throw new IllegalArgumentException( - "rememberMeRequestAttribute cannot be null"); + throw new IllegalArgumentException("rememberMeRequestAttribute cannot be null"); } this.rememberMeRequestAttribute = rememberMeRequestAttribute; } diff --git a/spring-session-core/src/main/java/org/springframework/session/web/http/HeaderHttpSessionIdResolver.java b/spring-session-core/src/main/java/org/springframework/session/web/http/HeaderHttpSessionIdResolver.java index e5aaacfc..c6d22c25 100644 --- a/spring-session-core/src/main/java/org/springframework/session/web/http/HeaderHttpSessionIdResolver.java +++ b/spring-session-core/src/main/java/org/springframework/session/web/http/HeaderHttpSessionIdResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -98,13 +98,11 @@ public class HeaderHttpSessionIdResolver implements HttpSessionIdResolver { @Override public List resolveSessionIds(HttpServletRequest request) { String headerValue = request.getHeader(this.headerName); - return (headerValue != null) ? Collections.singletonList(headerValue) - : Collections.emptyList(); + return (headerValue != null) ? Collections.singletonList(headerValue) : Collections.emptyList(); } @Override - public void setSessionId(HttpServletRequest request, HttpServletResponse response, - String sessionId) { + public void setSessionId(HttpServletRequest request, HttpServletResponse response, String sessionId) { response.setHeader(this.headerName, sessionId); } diff --git a/spring-session-core/src/main/java/org/springframework/session/web/http/HttpSessionAdapter.java b/spring-session-core/src/main/java/org/springframework/session/web/http/HttpSessionAdapter.java index a202277a..cc72fb67 100644 --- a/spring-session-core/src/main/java/org/springframework/session/web/http/HttpSessionAdapter.java +++ b/spring-session-core/src/main/java/org/springframework/session/web/http/HttpSessionAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -142,8 +142,8 @@ class HttpSessionAdapter implements HttpSession { if (value != oldValue) { if (oldValue instanceof HttpSessionBindingListener) { try { - ((HttpSessionBindingListener) oldValue).valueUnbound( - new HttpSessionBindingEvent(this, name, oldValue)); + ((HttpSessionBindingListener) oldValue) + .valueUnbound(new HttpSessionBindingEvent(this, name, oldValue)); } catch (Throwable th) { logger.error("Error invoking session binding event listener", th); @@ -151,8 +151,7 @@ class HttpSessionAdapter implements HttpSession { } if (value instanceof HttpSessionBindingListener) { try { - ((HttpSessionBindingListener) value) - .valueBound(new HttpSessionBindingEvent(this, name, value)); + ((HttpSessionBindingListener) value).valueBound(new HttpSessionBindingEvent(this, name, value)); } catch (Throwable th) { logger.error("Error invoking session binding event listener", th); @@ -173,8 +172,7 @@ class HttpSessionAdapter implements HttpSession { this.session.removeAttribute(name); if (oldValue instanceof HttpSessionBindingListener) { try { - ((HttpSessionBindingListener) oldValue) - .valueUnbound(new HttpSessionBindingEvent(this, name, oldValue)); + ((HttpSessionBindingListener) oldValue).valueUnbound(new HttpSessionBindingEvent(this, name, oldValue)); } catch (Throwable th) { logger.error("Error invoking session binding event listener", th); @@ -205,8 +203,7 @@ class HttpSessionAdapter implements HttpSession { private void checkState() { if (this.invalidated) { - throw new IllegalStateException( - "The HttpSession has already be invalidated."); + throw new IllegalStateException("The HttpSession has already be invalidated."); } } diff --git a/spring-session-core/src/main/java/org/springframework/session/web/http/HttpSessionIdResolver.java b/spring-session-core/src/main/java/org/springframework/session/web/http/HttpSessionIdResolver.java index e55a765b..42b660dd 100644 --- a/spring-session-core/src/main/java/org/springframework/session/web/http/HttpSessionIdResolver.java +++ b/spring-session-core/src/main/java/org/springframework/session/web/http/HttpSessionIdResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,8 +49,7 @@ public interface HttpSessionIdResolver { * @param response the current response * @param sessionId the session id */ - void setSessionId(HttpServletRequest request, HttpServletResponse response, - String sessionId); + void setSessionId(HttpServletRequest request, HttpServletResponse response, String sessionId); /** * Instruct the client to end the current session. This method is invoked when a diff --git a/spring-session-core/src/main/java/org/springframework/session/web/http/OnCommittedResponseWrapper.java b/spring-session-core/src/main/java/org/springframework/session/web/http/OnCommittedResponseWrapper.java index f08b012b..db372111 100644 --- a/spring-session-core/src/main/java/org/springframework/session/web/http/OnCommittedResponseWrapper.java +++ b/spring-session-core/src/main/java/org/springframework/session/web/http/OnCommittedResponseWrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,6 +36,7 @@ import org.apache.commons.logging.LogFactory; * @since 1.0 */ abstract class OnCommittedResponseWrapper extends HttpServletResponseWrapper { + private final Log logger = LogFactory.getLog(getClass()); private boolean disableOnCommitted; @@ -204,13 +205,11 @@ abstract class OnCommittedResponseWrapper extends HttpServletResponseWrapper { /** * Adds the contentLengthToWrite to the total contentWritten size and checks to see if * the response should be written. - * * @param contentLengthToWrite the size of the content that is about to be written. */ private void checkContentLength(long contentLengthToWrite) { this.contentWritten += contentLengthToWrite; - boolean isBodyFullyWritten = this.contentLength > 0 - && this.contentWritten >= this.contentLength; + boolean isBodyFullyWritten = this.contentLength > 0 && this.contentWritten >= this.contentLength; int bufferSize = getBufferSize(); boolean requiresFlush = bufferSize > 0 && this.contentWritten >= bufferSize; if (isBodyFullyWritten || requiresFlush) { @@ -234,9 +233,11 @@ abstract class OnCommittedResponseWrapper extends HttpServletResponseWrapper { * calling the prior to methods that commit the response. We delegate all methods to * the original {@link java.io.PrintWriter} to ensure that the behavior is as close to * the original {@link java.io.PrintWriter} as possible. See SEC-2039 + * * @author Rob Winch */ private class SaveContextPrintWriter extends PrintWriter { + private final PrintWriter delegate; SaveContextPrintWriter(PrintWriter delegate) { @@ -466,6 +467,7 @@ abstract class OnCommittedResponseWrapper extends HttpServletResponseWrapper { trackContentLength(c); return this.delegate.append(c); } + } /** @@ -477,6 +479,7 @@ abstract class OnCommittedResponseWrapper extends HttpServletResponseWrapper { * @author Rob Winch */ private class SaveContextServletOutputStream extends ServletOutputStream { + private final ServletOutputStream delegate; SaveContextServletOutputStream(ServletOutputStream delegate) { @@ -634,5 +637,7 @@ abstract class OnCommittedResponseWrapper extends HttpServletResponseWrapper { public void setWriteListener(WriteListener writeListener) { this.delegate.setWriteListener(writeListener); } + } + } diff --git a/spring-session-core/src/main/java/org/springframework/session/web/http/OncePerRequestFilter.java b/spring-session-core/src/main/java/org/springframework/session/web/http/OncePerRequestFilter.java index ff1c147d..8b0ff0f9 100644 --- a/spring-session-core/src/main/java/org/springframework/session/web/http/OncePerRequestFilter.java +++ b/spring-session-core/src/main/java/org/springframework/session/web/http/OncePerRequestFilter.java @@ -37,19 +37,18 @@ import javax.servlet.http.HttpServletResponse; * @since 1.0 */ abstract class OncePerRequestFilter implements Filter { + /** * Suffix that gets appended to the filter name for the "already filtered" request * attribute. */ public static final String ALREADY_FILTERED_SUFFIX = ".FILTERED"; - private String alreadyFilteredAttributeName = getClass().getName() - .concat(ALREADY_FILTERED_SUFFIX); + private String alreadyFilteredAttributeName = getClass().getName().concat(ALREADY_FILTERED_SUFFIX); /** - * This {@code doFilter} implementation stores a request attribute for - * "already filtered", proceeding without filtering again if the attribute is already - * there. + * This {@code doFilter} implementation stores a request attribute for "already + * filtered", proceeding without filtering again if the attribute is already there. * @param request the request * @param response the response * @param filterChain the filter chain @@ -57,21 +56,17 @@ abstract class OncePerRequestFilter implements Filter { * @throws IOException in case of I/O operation exception */ @Override - public final void doFilter(ServletRequest request, ServletResponse response, - FilterChain filterChain) throws ServletException, IOException { + public final void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) + throws ServletException, IOException { - if (!(request instanceof HttpServletRequest) - || !(response instanceof HttpServletResponse)) { - throw new ServletException( - "OncePerRequestFilter just supports HTTP requests"); + if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) { + throw new ServletException("OncePerRequestFilter just supports HTTP requests"); } HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; String alreadyFilteredAttributeName = this.alreadyFilteredAttributeName; - alreadyFilteredAttributeName = updateForErrorDispatch( - alreadyFilteredAttributeName, request); - boolean hasAlreadyFilteredAttribute = request - .getAttribute(alreadyFilteredAttributeName) != null; + alreadyFilteredAttributeName = updateForErrorDispatch(alreadyFilteredAttributeName, request); + boolean hasAlreadyFilteredAttribute = request.getAttribute(alreadyFilteredAttributeName) != null; if (hasAlreadyFilteredAttribute) { @@ -91,9 +86,9 @@ abstract class OncePerRequestFilter implements Filter { } } - private String updateForErrorDispatch(String alreadyFilteredAttributeName, - ServletRequest request) { - // Jetty does ERROR dispatch within sendError, so request attribute is still present + private String updateForErrorDispatch(String alreadyFilteredAttributeName, ServletRequest request) { + // Jetty does ERROR dispatch within sendError, so request attribute is still + // present // Use a separate attribute for ERROR dispatches if (DispatcherType.ERROR.equals(request.getDispatcherType()) && request.getAttribute(alreadyFilteredAttributeName) != null) { @@ -108,7 +103,6 @@ abstract class OncePerRequestFilter implements Filter { *

    * Provides HttpServletRequest and HttpServletResponse arguments instead of the * default ServletRequest and ServletResponse ones. - * * @param request the request * @param response the response * @param filterChain the FilterChain @@ -116,9 +110,8 @@ abstract class OncePerRequestFilter implements Filter { * @throws IOException thrown when an I/O exception of some sort has occurred * @see Filter#doFilter */ - protected abstract void doFilterInternal(HttpServletRequest request, - HttpServletResponse response, FilterChain filterChain) - throws ServletException, IOException; + protected abstract void doFilterInternal(HttpServletRequest request, HttpServletResponse response, + FilterChain filterChain) throws ServletException, IOException; @Override public void init(FilterConfig config) { @@ -127,4 +120,5 @@ abstract class OncePerRequestFilter implements Filter { @Override public void destroy() { } + } diff --git a/spring-session-core/src/main/java/org/springframework/session/web/http/SessionEventHttpSessionListenerAdapter.java b/spring-session-core/src/main/java/org/springframework/session/web/http/SessionEventHttpSessionListenerAdapter.java index 01a37bcd..df271a68 100644 --- a/spring-session-core/src/main/java/org/springframework/session/web/http/SessionEventHttpSessionListenerAdapter.java +++ b/spring-session-core/src/main/java/org/springframework/session/web/http/SessionEventHttpSessionListenerAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,6 +40,7 @@ import org.springframework.web.context.ServletContextAware; */ public class SessionEventHttpSessionListenerAdapter implements ApplicationListener, ServletContextAware { + private final List listeners; private ServletContext context; @@ -75,8 +76,7 @@ public class SessionEventHttpSessionListenerAdapter private HttpSessionEvent createHttpSessionEvent(AbstractSessionEvent event) { Session session = event.getSession(); - HttpSession httpSession = new HttpSessionAdapter<>(session, - this.context); + HttpSession httpSession = new HttpSessionAdapter<>(session, this.context); return new HttpSessionEvent(httpSession); } @@ -91,4 +91,5 @@ public class SessionEventHttpSessionListenerAdapter public void setServletContext(ServletContext servletContext) { this.context = servletContext; } + } diff --git a/spring-session-core/src/main/java/org/springframework/session/web/http/SessionRepositoryFilter.java b/spring-session-core/src/main/java/org/springframework/session/web/http/SessionRepositoryFilter.java index f2983afb..d0350399 100644 --- a/spring-session-core/src/main/java/org/springframework/session/web/http/SessionRepositoryFilter.java +++ b/spring-session-core/src/main/java/org/springframework/session/web/http/SessionRepositoryFilter.java @@ -79,25 +79,21 @@ import org.springframework.session.SessionRepository; @Order(SessionRepositoryFilter.DEFAULT_ORDER) public class SessionRepositoryFilter extends OncePerRequestFilter { - private static final String SESSION_LOGGER_NAME = SessionRepositoryFilter.class - .getName().concat(".SESSION_LOGGER"); + private static final String SESSION_LOGGER_NAME = SessionRepositoryFilter.class.getName().concat(".SESSION_LOGGER"); private static final Log SESSION_LOGGER = LogFactory.getLog(SESSION_LOGGER_NAME); /** * The session repository request attribute name. */ - public static final String SESSION_REPOSITORY_ATTR = SessionRepository.class - .getName(); + public static final String SESSION_REPOSITORY_ATTR = SessionRepository.class.getName(); /** * Invalid session id (not backed by the session repository) request attribute name. */ - public static final String INVALID_SESSION_ID_ATTR = SESSION_REPOSITORY_ATTR - + ".invalidSessionId"; + public static final String INVALID_SESSION_ID_ATTR = SESSION_REPOSITORY_ATTR + ".invalidSessionId"; - private static final String CURRENT_SESSION_ATTR = SESSION_REPOSITORY_ATTR - + ".CURRENT_SESSION"; + private static final String CURRENT_SESSION_ATTR = SESSION_REPOSITORY_ATTR + ".CURRENT_SESSION"; /** * The default filter order. @@ -110,7 +106,6 @@ public class SessionRepositoryFilter extends OncePerRequestFi /** * Creates a new instance. - * * @param sessionRepository the SessionRepository to use. Cannot be null. */ public SessionRepositoryFilter(SessionRepository sessionRepository) { @@ -123,7 +118,6 @@ public class SessionRepositoryFilter extends OncePerRequestFi /** * Sets the {@link HttpSessionIdResolver} to be used. The default is a * {@link CookieHttpSessionIdResolver}. - * * @param httpSessionIdResolver the {@link HttpSessionIdResolver} to use. Cannot be * null. */ @@ -135,15 +129,13 @@ public class SessionRepositoryFilter extends OncePerRequestFi } @Override - protected void doFilterInternal(HttpServletRequest request, - HttpServletResponse response, FilterChain filterChain) + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { request.setAttribute(SESSION_REPOSITORY_ATTR, this.sessionRepository); - SessionRepositoryRequestWrapper wrappedRequest = new SessionRepositoryRequestWrapper( - request, response); - SessionRepositoryResponseWrapper wrappedResponse = new SessionRepositoryResponseWrapper( - wrappedRequest, response); + SessionRepositoryRequestWrapper wrappedRequest = new SessionRepositoryRequestWrapper(request, response); + SessionRepositoryResponseWrapper wrappedResponse = new SessionRepositoryResponseWrapper(wrappedRequest, + response); try { filterChain.doFilter(wrappedRequest, wrappedResponse); @@ -159,8 +151,7 @@ public class SessionRepositoryFilter extends OncePerRequestFi * @author Rob Winch * @since 1.0 */ - private final class SessionRepositoryResponseWrapper - extends OnCommittedResponseWrapper { + private final class SessionRepositoryResponseWrapper extends OnCommittedResponseWrapper { private final SessionRepositoryRequestWrapper request; @@ -169,8 +160,7 @@ public class SessionRepositoryFilter extends OncePerRequestFi * @param request the request to be wrapped * @param response the response to be wrapped */ - SessionRepositoryResponseWrapper(SessionRepositoryRequestWrapper request, - HttpServletResponse response) { + SessionRepositoryResponseWrapper(SessionRepositoryRequestWrapper request, HttpServletResponse response) { super(response); if (request == null) { throw new IllegalArgumentException("request cannot be null"); @@ -182,6 +172,7 @@ public class SessionRepositoryFilter extends OncePerRequestFi protected void onResponseCommitted() { this.request.commitSession(); } + } /** @@ -192,8 +183,7 @@ public class SessionRepositoryFilter extends OncePerRequestFi * @author Rob Winch * @since 1.0 */ - private final class SessionRepositoryRequestWrapper - extends HttpServletRequestWrapper { + private final class SessionRepositoryRequestWrapper extends HttpServletRequestWrapper { private final HttpServletResponse response; @@ -207,8 +197,7 @@ public class SessionRepositoryFilter extends OncePerRequestFi private boolean requestedSessionInvalidated; - private SessionRepositoryRequestWrapper(HttpServletRequest request, - HttpServletResponse response) { + private SessionRepositoryRequestWrapper(HttpServletRequest request, HttpServletResponse response) { super(request); this.response = response; } @@ -221,8 +210,7 @@ public class SessionRepositoryFilter extends OncePerRequestFi HttpSessionWrapper wrappedSession = getCurrentSession(); if (wrappedSession == null) { if (isInvalidateClientSession()) { - SessionRepositoryFilter.this.httpSessionIdResolver.expireSession(this, - this.response); + SessionRepositoryFilter.this.httpSessionIdResolver.expireSession(this, this.response); } } else { @@ -230,10 +218,8 @@ public class SessionRepositoryFilter extends OncePerRequestFi clearRequestedSessionCache(); SessionRepositoryFilter.this.sessionRepository.save(session); String sessionId = session.getId(); - if (!isRequestedSessionIdValid() - || !sessionId.equals(getRequestedSessionId())) { - SessionRepositoryFilter.this.httpSessionIdResolver.setSessionId(this, - this.response, sessionId); + if (!isRequestedSessionIdValid() || !sessionId.equals(getRequestedSessionId())) { + SessionRepositoryFilter.this.httpSessionIdResolver.setSessionId(this, this.response, sessionId); } } } @@ -321,8 +307,7 @@ public class SessionRepositoryFilter extends OncePerRequestFi SESSION_LOGGER.debug( "A new session was created. To help you troubleshoot where the session was created we provided a StackTrace (this is not an error). You can prevent this from appearing by disabling DEBUG logging for " + SESSION_LOGGER_NAME, - new RuntimeException( - "For debugging purposes only (not an error)")); + new RuntimeException("For debugging purposes only (not an error)")); } S session = SessionRepositoryFilter.this.sessionRepository.createSession(); session.setLastAccessedTime(Instant.now()); @@ -352,14 +337,12 @@ public class SessionRepositoryFilter extends OncePerRequestFi private S getRequestedSession() { if (!this.requestedSessionCached) { - List sessionIds = SessionRepositoryFilter.this.httpSessionIdResolver - .resolveSessionIds(this); + List sessionIds = SessionRepositoryFilter.this.httpSessionIdResolver.resolveSessionIds(this); for (String sessionId : sessionIds) { if (this.requestedSessionId == null) { this.requestedSessionId = sessionId; } - S session = SessionRepositoryFilter.this.sessionRepository - .findById(sessionId); + S session = SessionRepositoryFilter.this.sessionRepository.findById(sessionId); if (session != null) { this.requestedSession = session; this.requestedSessionId = sessionId; @@ -397,6 +380,7 @@ public class SessionRepositoryFilter extends OncePerRequestFi clearRequestedSessionCache(); SessionRepositoryFilter.this.sessionRepository.deleteById(getId()); } + } /** @@ -404,8 +388,7 @@ public class SessionRepositoryFilter extends OncePerRequestFi * * @since 1.3.4 */ - private final class SessionCommittingRequestDispatcher - implements RequestDispatcher { + private final class SessionCommittingRequestDispatcher implements RequestDispatcher { private final RequestDispatcher delegate; @@ -414,14 +397,12 @@ public class SessionRepositoryFilter extends OncePerRequestFi } @Override - public void forward(ServletRequest request, ServletResponse response) - throws ServletException, IOException { + public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException { this.delegate.forward(request, response); } @Override - public void include(ServletRequest request, ServletResponse response) - throws ServletException, IOException { + public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException { SessionRepositoryRequestWrapper.this.commitSession(); this.delegate.include(request, response); } diff --git a/spring-session-core/src/main/java/org/springframework/session/web/server/session/SpringSessionWebSessionStore.java b/spring-session-core/src/main/java/org/springframework/session/web/server/session/SpringSessionWebSessionStore.java index d33efb7d..97e0d910 100644 --- a/spring-session-core/src/main/java/org/springframework/session/web/server/session/SpringSessionWebSessionStore.java +++ b/spring-session-core/src/main/java/org/springframework/session/web/server/session/SpringSessionWebSessionStore.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,12 +61,14 @@ public class SpringSessionWebSessionStore implements WebSessi } /** - * Configure the {@link Clock} to use to set lastAccessTime on every created - * session and to calculate if it is expired. - *

    This may be useful to align to different timezone or to set the clock - * back in a test, e.g. {@code Clock.offset(clock, Duration.ofMinutes(-31))} - * in order to simulate session expiration. - *

    By default this is {@code Clock.system(ZoneId.of("GMT"))}. + * Configure the {@link Clock} to use to set lastAccessTime on every created session + * and to calculate if it is expired. + *

    + * This may be useful to align to different timezone or to set the clock back in a + * test, e.g. {@code Clock.offset(clock, Duration.ofMinutes(-31))} in order to + * simulate session expiration. + *

    + * By default this is {@code Clock.system(ZoneId.of("GMT"))}. * @param clock the clock to use */ public void setClock(Clock clock) { @@ -90,8 +92,7 @@ public class SpringSessionWebSessionStore implements WebSessi @Override public Mono retrieveSession(String sessionId) { return this.sessions.findById(sessionId) - .doOnNext((session) -> session.setLastAccessedTime(this.clock.instant())) - .map(this::existingSession); + .doOnNext((session) -> session.setLastAccessedTime(this.clock.instant())).map(this::existingSession); } @Override @@ -133,8 +134,7 @@ public class SpringSessionWebSessionStore implements WebSessi @Override public Mono changeSessionId() { return Mono.defer(() -> { - this.session - .changeSessionId(); + this.session.changeSessionId(); return save(); }); } @@ -152,8 +152,7 @@ public class SpringSessionWebSessionStore implements WebSessi @Override public boolean isStarted() { State value = this.state.get(); - return (State.STARTED.equals(value) - || (State.NEW.equals(value) && !getAttributes().isEmpty())); + return (State.STARTED.equals(value) || (State.NEW.equals(value) && !getAttributes().isEmpty())); } @Override @@ -198,10 +197,13 @@ public class SpringSessionWebSessionStore implements WebSessi public void setMaxIdleTime(Duration maxIdleTime) { this.session.setMaxInactiveInterval(maxIdleTime); } + } private enum State { + NEW, STARTED, EXPIRED + } private static class SpringSessionMap implements Map { @@ -226,8 +228,7 @@ public class SpringSessionWebSessionStore implements WebSessi @Override public boolean containsKey(Object key) { - return key instanceof String - && this.session.getAttributeNames().contains(key); + return key instanceof String && this.session.getAttributeNames().contains(key); } @Override @@ -346,5 +347,7 @@ public class SpringSessionWebSessionStore implements WebSessi } } + } + } diff --git a/spring-session-core/src/main/java/org/springframework/session/web/socket/config/annotation/AbstractSessionWebSocketMessageBrokerConfigurer.java b/spring-session-core/src/main/java/org/springframework/session/web/socket/config/annotation/AbstractSessionWebSocketMessageBrokerConfigurer.java index 596a249d..484cb00e 100644 --- a/spring-session-core/src/main/java/org/springframework/session/web/socket/config/annotation/AbstractSessionWebSocketMessageBrokerConfigurer.java +++ b/spring-session-core/src/main/java/org/springframework/session/web/socket/config/annotation/AbstractSessionWebSocketMessageBrokerConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -93,8 +93,7 @@ public abstract class AbstractSessionWebSocketMessageBrokerConfigurer * - * * @author Rob Winch * @author Mark Anderson * @since 1.0 */ -public final class WebSocketRegistryListener - implements ApplicationListener { +public final class WebSocketRegistryListener implements ApplicationListener { private static final Log logger = LogFactory.getLog(WebSocketRegistryListener.class); - static final CloseStatus SESSION_EXPIRED_STATUS = new CloseStatus( - CloseStatus.POLICY_VIOLATION.getCode(), + static final CloseStatus SESSION_EXPIRED_STATUS = new CloseStatus(CloseStatus.POLICY_VIOLATION.getCode(), "This connection was established under an authenticated HTTP Session that has expired"); private final ConcurrentHashMap> httpSessionIdToWsSessions = new ConcurrentHashMap<>(); @@ -72,8 +69,7 @@ public final class WebSocketRegistryListener Map sessionAttributes = SimpMessageHeaderAccessor .getSessionAttributes(e.getMessage().getHeaders()); String httpSessionId = (sessionAttributes != null) - ? SessionRepositoryMessageInterceptor.getSessionId(sessionAttributes) - : null; + ? SessionRepositoryMessageInterceptor.getSessionId(sessionAttributes) : null; afterConnectionClosed(httpSessionId, e.getSessionId()); } } @@ -98,8 +94,7 @@ public final class WebSocketRegistryListener return; } - Map sessions = this.httpSessionIdToWsSessions - .get(httpSessionId); + Map sessions = this.httpSessionIdToWsSessions.get(httpSessionId); if (sessions != null) { boolean result = sessions.remove(wsSessionId) != null; if (logger.isDebugEnabled()) { @@ -108,16 +103,15 @@ public final class WebSocketRegistryListener if (sessions.isEmpty()) { this.httpSessionIdToWsSessions.remove(httpSessionId); if (logger.isDebugEnabled()) { - logger.debug("Removed the corresponding HTTP Session for " - + wsSessionId + " since it contained no WebSocket mappings"); + logger.debug("Removed the corresponding HTTP Session for " + wsSessionId + + " since it contained no WebSocket mappings"); } } } } private void registerWsSession(String httpSessionId, WebSocketSession wsSession) { - Map sessions = this.httpSessionIdToWsSessions - .get(httpSessionId); + Map sessions = this.httpSessionIdToWsSessions.get(httpSessionId); if (sessions == null) { sessions = new ConcurrentHashMap<>(); this.httpSessionIdToWsSessions.putIfAbsent(httpSessionId, sessions); @@ -127,25 +121,22 @@ public final class WebSocketRegistryListener } private void closeWsSessions(String httpSessionId) { - Map sessionsToClose = this.httpSessionIdToWsSessions - .remove(httpSessionId); + Map sessionsToClose = this.httpSessionIdToWsSessions.remove(httpSessionId); if (sessionsToClose == null) { return; } if (logger.isDebugEnabled()) { - logger.debug( - "Closing WebSocket connections associated to expired HTTP Session " - + httpSessionId); + logger.debug("Closing WebSocket connections associated to expired HTTP Session " + httpSessionId); } for (WebSocketSession toClose : sessionsToClose.values()) { try { toClose.close(SESSION_EXPIRED_STATUS); } catch (IOException ex) { - logger.debug( - "Failed to close WebSocketSession (this is nothing to worry about but for debugging only)", + logger.debug("Failed to close WebSocketSession (this is nothing to worry about but for debugging only)", ex); } } } + } diff --git a/spring-session-core/src/main/java/org/springframework/session/web/socket/server/SessionRepositoryMessageInterceptor.java b/spring-session-core/src/main/java/org/springframework/session/web/socket/server/SessionRepositoryMessageInterceptor.java index 8327d8f0..4f0f665d 100644 --- a/spring-session-core/src/main/java/org/springframework/session/web/socket/server/SessionRepositoryMessageInterceptor.java +++ b/spring-session-core/src/main/java/org/springframework/session/web/socket/server/SessionRepositoryMessageInterceptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -72,15 +72,13 @@ public final class SessionRepositoryMessageInterceptor /** * Creates a new instance. - * * @param sessionRepository the {@link SessionRepository} to use. Cannot be null. */ public SessionRepositoryMessageInterceptor(SessionRepository sessionRepository) { Assert.notNull(sessionRepository, "sessionRepository cannot be null"); this.sessionRepository = sessionRepository; - this.matchingMessageTypes = EnumSet.of(SimpMessageType.CONNECT, - SimpMessageType.MESSAGE, SimpMessageType.SUBSCRIBE, - SimpMessageType.UNSUBSCRIBE); + this.matchingMessageTypes = EnumSet.of(SimpMessageType.CONNECT, SimpMessageType.MESSAGE, + SimpMessageType.SUBSCRIBE, SimpMessageType.UNSUBSCRIBE); } /** @@ -94,14 +92,12 @@ public final class SessionRepositoryMessageInterceptor * The default is: SimpMessageType.CONNECT, SimpMessageType.MESSAGE, * SimpMessageType.SUBSCRIBE, SimpMessageType.UNSUBSCRIBE. *

    - * * @param matchingMessageTypes the {@link SimpMessageType} to match on in * {@link #preSend(Message, MessageChannel)}, else the {@link Message} is continued * without accessing or updating the {@link Session} */ public void setMatchingMessageTypes(Set matchingMessageTypes) { - Assert.notEmpty(matchingMessageTypes, - "matchingMessageTypes cannot be null or empty"); + Assert.notEmpty(matchingMessageTypes, "matchingMessageTypes cannot be null or empty"); this.matchingMessageTypes = matchingMessageTypes; } @@ -110,16 +106,12 @@ public final class SessionRepositoryMessageInterceptor if (message == null) { return message; } - SimpMessageType messageType = SimpMessageHeaderAccessor - .getMessageType(message.getHeaders()); + SimpMessageType messageType = SimpMessageHeaderAccessor.getMessageType(message.getHeaders()); if (!this.matchingMessageTypes.contains(messageType)) { return message; } - Map sessionHeaders = SimpMessageHeaderAccessor - .getSessionAttributes(message.getHeaders()); - String sessionId = (sessionHeaders != null) - ? (String) sessionHeaders.get(SPRING_SESSION_ID_ATTR_NAME) - : null; + Map sessionHeaders = SimpMessageHeaderAccessor.getSessionAttributes(message.getHeaders()); + String sessionId = (sessionHeaders != null) ? (String) sessionHeaders.get(SPRING_SESSION_ID_ATTR_NAME) : null; if (sessionId != null) { S session = this.sessionRepository.findById(sessionId); if (session != null) { @@ -132,8 +124,8 @@ public final class SessionRepositoryMessageInterceptor } @Override - public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, - WebSocketHandler wsHandler, Map attributes) throws Exception { + public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, + Map attributes) throws Exception { if (request instanceof ServletServerHttpRequest) { ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request; HttpSession session = servletRequest.getServletRequest().getSession(false); @@ -145,8 +137,8 @@ public final class SessionRepositoryMessageInterceptor } @Override - public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, - WebSocketHandler wsHandler, Exception exception) { + public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, + Exception exception) { } public static String getSessionId(Map attributes) { @@ -156,4 +148,5 @@ public final class SessionRepositoryMessageInterceptor public static void setSessionId(Map attributes, String sessionId) { attributes.put(SPRING_SESSION_ID_ATTR_NAME, sessionId); } + } diff --git a/spring-session-core/src/test/java/org/springframework/session/MapSessionRepositoryTests.java b/spring-session-core/src/test/java/org/springframework/session/MapSessionRepositoryTests.java index 2a1cc612..ede43f20 100644 --- a/spring-session-core/src/test/java/org/springframework/session/MapSessionRepositoryTests.java +++ b/spring-session-core/src/test/java/org/springframework/session/MapSessionRepositoryTests.java @@ -29,20 +29,20 @@ import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link MapSessionRepository}. */ -public class MapSessionRepositoryTests { +class MapSessionRepositoryTests { private MapSessionRepository repository; private MapSession session; @BeforeEach - public void setup() { + void setup() { this.repository = new MapSessionRepository(new ConcurrentHashMap<>()); this.session = new MapSession(); } @Test - public void getSessionExpired() { + void getSessionExpired() { this.session.setMaxInactiveInterval(Duration.ofSeconds(1)); this.session.setLastAccessedTime(Instant.now().minus(5, ChronoUnit.MINUTES)); this.repository.save(this.session); @@ -51,29 +51,25 @@ public class MapSessionRepositoryTests { } @Test - public void createSessionDefaultExpiration() { + void createSessionDefaultExpiration() { Session session = this.repository.createSession(); assertThat(session).isInstanceOf(MapSession.class); - assertThat(session.getMaxInactiveInterval()) - .isEqualTo(new MapSession().getMaxInactiveInterval()); + assertThat(session.getMaxInactiveInterval()).isEqualTo(new MapSession().getMaxInactiveInterval()); } @Test - public void createSessionCustomDefaultExpiration() { - final Duration expectedMaxInterval = new MapSession().getMaxInactiveInterval() - .plusSeconds(10); - this.repository.setDefaultMaxInactiveInterval( - (int) expectedMaxInterval.getSeconds()); + void createSessionCustomDefaultExpiration() { + final Duration expectedMaxInterval = new MapSession().getMaxInactiveInterval().plusSeconds(10); + this.repository.setDefaultMaxInactiveInterval((int) expectedMaxInterval.getSeconds()); Session session = this.repository.createSession(); - assertThat(session.getMaxInactiveInterval()) - .isEqualTo(expectedMaxInterval); + assertThat(session.getMaxInactiveInterval()).isEqualTo(expectedMaxInterval); } @Test - public void changeSessionIdWhenNotYetSaved() { + void changeSessionIdWhenNotYetSaved() { MapSession createSession = this.repository.createSession(); String originalId = createSession.getId(); @@ -86,7 +82,7 @@ public class MapSessionRepositoryTests { } @Test - public void changeSessionIdWhenSaved() { + void changeSessionIdWhenSaved() { MapSession createSession = this.repository.createSession(); this.repository.save(createSession); @@ -101,7 +97,7 @@ public class MapSessionRepositoryTests { } @Test // gh-1120 - public void getAttributeNamesAndRemove() { + void getAttributeNamesAndRemove() { MapSession session = this.repository.createSession(); session.setAttribute("attribute1", "value1"); session.setAttribute("attribute2", "value2"); diff --git a/spring-session-core/src/test/java/org/springframework/session/MapSessionTests.java b/spring-session-core/src/test/java/org/springframework/session/MapSessionTests.java index 52fd97ee..36221f5e 100644 --- a/spring-session-core/src/test/java/org/springframework/session/MapSessionTests.java +++ b/spring-session-core/src/test/java/org/springframework/session/MapSessionTests.java @@ -26,38 +26,37 @@ import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -public class MapSessionTests { +class MapSessionTests { private MapSession session; @BeforeEach - public void setup() { + void setup() { this.session = new MapSession(); this.session.setLastAccessedTime(Instant.ofEpochMilli(1413258262962L)); } @Test - public void constructorNullSession() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new MapSession((Session) null)) + void constructorNullSession() { + assertThatIllegalArgumentException().isThrownBy(() -> new MapSession((Session) null)) .withMessage("session cannot be null"); } @Test - public void getAttributeWhenNullThenNull() { + void getAttributeWhenNullThenNull() { String result = this.session.getAttribute("attrName"); assertThat(result).isNull(); } @Test - public void getAttributeOrDefaultWhenNullThenDefaultValue() { + void getAttributeOrDefaultWhenNullThenDefaultValue() { String defaultValue = "default"; String result = this.session.getAttributeOrDefault("attrName", defaultValue); assertThat(result).isEqualTo(defaultValue); } @Test - public void getAttributeOrDefaultWhenNotNullThenDefaultValue() { + void getAttributeOrDefaultWhenNotNullThenDefaultValue() { String defaultValue = "default"; String attrValue = "value"; String attrName = "attrName"; @@ -69,14 +68,13 @@ public class MapSessionTests { } @Test - public void getRequiredAttributeWhenNullThenException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.session.getRequiredAttribute("attrName")) + void getRequiredAttributeWhenNullThenException() { + assertThatIllegalArgumentException().isThrownBy(() -> this.session.getRequiredAttribute("attrName")) .withMessage("Required attribute 'attrName' is missing."); } @Test - public void getRequiredAttributeWhenNotNullThenReturns() { + void getRequiredAttributeWhenNotNullThenReturns() { String attrValue = "value"; String attrName = "attrName"; this.session.setAttribute(attrName, attrValue); @@ -90,7 +88,7 @@ public class MapSessionTests { * Ensure conforms to the javadoc of {@link Session} */ @Test - public void setAttributeNullObjectRemoves() { + void setAttributeNullObjectRemoves() { String attr = "attr"; this.session.setAttribute(attr, new Object()); this.session.setAttribute(attr, null); @@ -98,43 +96,43 @@ public class MapSessionTests { } @Test - public void equalsNonSessionFalse() { + void equalsNonSessionFalse() { assertThat(this.session.equals(new Object())).isFalse(); } @Test - public void equalsCustomSession() { + void equalsCustomSession() { CustomSession other = new CustomSession(); this.session.setId(other.getId()); assertThat(this.session.equals(other)).isTrue(); } @Test - public void hashCodeEqualsIdHashCode() { + void hashCodeEqualsIdHashCode() { this.session.setId("constantId"); assertThat(this.session.hashCode()).isEqualTo(this.session.getId().hashCode()); } @Test - public void isExpiredExact() { + void isExpiredExact() { Instant now = Instant.ofEpochMilli(1413260062962L); assertThat(this.session.isExpired(now)).isTrue(); } @Test - public void isExpiredOneMsTooSoon() { + void isExpiredOneMsTooSoon() { Instant now = Instant.ofEpochMilli(1413260062961L); assertThat(this.session.isExpired(now)).isFalse(); } @Test - public void isExpiredOneMsAfter() { + void isExpiredOneMsAfter() { Instant now = Instant.ofEpochMilli(1413260062963L); assertThat(this.session.isExpired(now)).isTrue(); } @Test // gh-1120 - public void getAttributeNamesAndRemove() { + void getAttributeNamesAndRemove() { this.session.setAttribute("attribute1", "value1"); this.session.setAttribute("attribute2", "value2"); @@ -206,6 +204,7 @@ public class MapSessionTests { public boolean isExpired() { return false; } + } } diff --git a/spring-session-core/src/test/java/org/springframework/session/ReactiveMapSessionRepositoryTests.java b/spring-session-core/src/test/java/org/springframework/session/ReactiveMapSessionRepositoryTests.java index c2362a82..23044fe2 100644 --- a/spring-session-core/src/test/java/org/springframework/session/ReactiveMapSessionRepositoryTests.java +++ b/spring-session-core/src/test/java/org/springframework/session/ReactiveMapSessionRepositoryTests.java @@ -35,20 +35,20 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException * @author Rob Winch * @since 2.0 */ -public class ReactiveMapSessionRepositoryTests { +class ReactiveMapSessionRepositoryTests { private ReactiveMapSessionRepository repository; private MapSession session; @BeforeEach - public void setup() { + void setup() { this.repository = new ReactiveMapSessionRepository(new HashMap<>()); this.session = new MapSession("session-id"); } @Test - public void constructorMapThenFound() { + void constructorMapThenFound() { Map sessions = new HashMap<>(); sessions.put(this.session.getId(), this.session); this.repository = new ReactiveMapSessionRepository(sessions); @@ -59,21 +59,20 @@ public class ReactiveMapSessionRepositoryTests { } @Test - public void constructorMapWhenNullThenThrowsIllegalArgumentException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new ReactiveMapSessionRepository(null)) + void constructorMapWhenNullThenThrowsIllegalArgumentException() { + assertThatIllegalArgumentException().isThrownBy(() -> new ReactiveMapSessionRepository(null)) .withMessage("sessions cannot be null"); } @Test - public void saveWhenNoSubscribersThenNotFound() { + void saveWhenNoSubscribersThenNotFound() { this.repository.save(this.session); assertThat(this.repository.findById(this.session.getId()).block()).isNull(); } @Test - public void saveWhenSubscriberThenFound() { + void saveWhenSubscriberThenFound() { this.repository.save(this.session).block(); Session findByIdSession = this.repository.findById(this.session.getId()).block(); @@ -82,7 +81,7 @@ public class ReactiveMapSessionRepositoryTests { } @Test - public void findByIdWhenExpiredRemovesFromSessionMap() { + void findByIdWhenExpiredRemovesFromSessionMap() { this.session.setMaxInactiveInterval(Duration.ofMinutes(1)); this.session.setLastAccessedTime(Instant.now().minus(5, ChronoUnit.MINUTES)); @@ -95,20 +94,17 @@ public class ReactiveMapSessionRepositoryTests { } @Test - public void createSessionWhenDefaultMaxInactiveIntervalThenDefaultMaxInactiveInterval() { + void createSessionWhenDefaultMaxInactiveIntervalThenDefaultMaxInactiveInterval() { Session session = this.repository.createSession().block(); assertThat(session).isInstanceOf(MapSession.class); - assertThat(session.getMaxInactiveInterval()) - .isEqualTo(new MapSession().getMaxInactiveInterval()); + assertThat(session.getMaxInactiveInterval()).isEqualTo(new MapSession().getMaxInactiveInterval()); } @Test - public void createSessionWhenCustomMaxInactiveIntervalThenCustomMaxInactiveInterval() { - final Duration expectedMaxInterval = new MapSession().getMaxInactiveInterval() - .plusSeconds(10); - this.repository - .setDefaultMaxInactiveInterval((int) expectedMaxInterval.getSeconds()); + void createSessionWhenCustomMaxInactiveIntervalThenCustomMaxInactiveInterval() { + final Duration expectedMaxInterval = new MapSession().getMaxInactiveInterval().plusSeconds(10); + this.repository.setDefaultMaxInactiveInterval((int) expectedMaxInterval.getSeconds()); Session session = this.repository.createSession().block(); @@ -116,7 +112,7 @@ public class ReactiveMapSessionRepositoryTests { } @Test - public void changeSessionIdWhenNotYetSaved() { + void changeSessionIdWhenNotYetSaved() { MapSession createSession = this.repository.createSession().block(); String originalId = createSession.getId(); @@ -129,7 +125,7 @@ public class ReactiveMapSessionRepositoryTests { } @Test - public void changeSessionIdWhenSaved() { + void changeSessionIdWhenSaved() { MapSession createSession = this.repository.createSession().block(); this.repository.save(createSession).block(); @@ -144,7 +140,7 @@ public class ReactiveMapSessionRepositoryTests { } @Test // gh-1120 - public void getAttributeNamesAndRemove() { + void getAttributeNamesAndRemove() { MapSession session = this.repository.createSession().block(); session.setAttribute("attribute1", "value1"); session.setAttribute("attribute2", "value2"); diff --git a/spring-session-core/src/test/java/org/springframework/session/config/annotation/web/http/EnableSpringHttpSessionCustomCookieSerializerTests.java b/spring-session-core/src/test/java/org/springframework/session/config/annotation/web/http/EnableSpringHttpSessionCustomCookieSerializerTests.java index 13e9cb24..81e0efac 100644 --- a/spring-session-core/src/test/java/org/springframework/session/config/annotation/web/http/EnableSpringHttpSessionCustomCookieSerializerTests.java +++ b/spring-session-core/src/test/java/org/springframework/session/config/annotation/web/http/EnableSpringHttpSessionCustomCookieSerializerTests.java @@ -61,7 +61,7 @@ import static org.mockito.Mockito.verify; @ExtendWith(SpringExtension.class) @ContextConfiguration @WebAppConfiguration -public class EnableSpringHttpSessionCustomCookieSerializerTests { +class EnableSpringHttpSessionCustomCookieSerializerTests { @Autowired private MockHttpServletRequest request; @@ -81,7 +81,7 @@ public class EnableSpringHttpSessionCustomCookieSerializerTests { private CookieSerializer cookieSerializer; @BeforeEach - public void setup() { + void setup() { this.chain = new MockFilterChain(); reset(this.sessionRepository); @@ -89,12 +89,11 @@ public class EnableSpringHttpSessionCustomCookieSerializerTests { } @Test - public void usesReadSessionIds() throws Exception { + void usesReadSessionIds() throws Exception { String sessionId = "sessionId"; given(this.cookieSerializer.readCookieValues(any(HttpServletRequest.class))) .willReturn(Collections.singletonList(sessionId)); - given(this.sessionRepository.findById(anyString())) - .willReturn(new MapSession(sessionId)); + given(this.sessionRepository.findById(anyString())).willReturn(new MapSession(sessionId)); this.sessionRepositoryFilter.doFilter(this.request, this.response, this.chain); @@ -102,19 +101,18 @@ public class EnableSpringHttpSessionCustomCookieSerializerTests { } @Test - public void usesWrite() throws Exception { + void usesWrite() throws Exception { given(this.sessionRepository.createSession()).willReturn(new MapSession()); - this.sessionRepositoryFilter.doFilter(this.request, this.response, - new MockFilterChain() { + this.sessionRepositoryFilter.doFilter(this.request, this.response, new MockFilterChain() { - @Override - public void doFilter(ServletRequest request, ServletResponse response) - throws IOException, ServletException { - ((HttpServletRequest) request).getSession(); - super.doFilter(request, response); - } - }); + @Override + public void doFilter(ServletRequest request, ServletResponse response) + throws IOException, ServletException { + ((HttpServletRequest) request).getSession(); + super.doFilter(request, response); + } + }); verify(this.cookieSerializer).writeCookieValue(any(CookieValue.class)); } diff --git a/spring-session-core/src/test/java/org/springframework/session/config/annotation/web/http/SpringHttpSessionConfigurationTests.java b/spring-session-core/src/test/java/org/springframework/session/config/annotation/web/http/SpringHttpSessionConfigurationTests.java index 074daf72..a41a7d24 100644 --- a/spring-session-core/src/test/java/org/springframework/session/config/annotation/web/http/SpringHttpSessionConfigurationTests.java +++ b/spring-session-core/src/test/java/org/springframework/session/config/annotation/web/http/SpringHttpSessionConfigurationTests.java @@ -45,12 +45,12 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * * @author Vedran Pavic */ -public class SpringHttpSessionConfigurationTests { +class SpringHttpSessionConfigurationTests { private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); @AfterEach - public void closeContext() { + void closeContext() { if (this.context != null) { this.context.close(); } @@ -62,28 +62,26 @@ public class SpringHttpSessionConfigurationTests { } @Test - public void noSessionRepositoryConfiguration() { + void noSessionRepositoryConfiguration() { assertThatExceptionOfType(UnsatisfiedDependencyException.class) .isThrownBy(() -> registerAndRefresh(EmptyConfiguration.class)) .withMessageContaining("org.springframework.session.SessionRepository"); } @Test - public void defaultConfiguration() { + void defaultConfiguration() { registerAndRefresh(DefaultConfiguration.class); - assertThat(this.context.getBean(SessionEventHttpSessionListenerAdapter.class)) - .isNotNull(); + assertThat(this.context.getBean(SessionEventHttpSessionListenerAdapter.class)).isNotNull(); assertThat(this.context.getBean(SessionRepositoryFilter.class)).isNotNull(); assertThat(this.context.getBean(SessionRepository.class)).isNotNull(); } @Test - public void sessionCookieConfigConfiguration() { + void sessionCookieConfigConfiguration() { registerAndRefresh(SessionCookieConfigConfiguration.class); - SessionRepositoryFilter sessionRepositoryFilter = this.context - .getBean(SessionRepositoryFilter.class); + SessionRepositoryFilter sessionRepositoryFilter = this.context.getBean(SessionRepositoryFilter.class); assertThat(sessionRepositoryFilter).isNotNull(); CookieHttpSessionIdResolver httpSessionIdResolver = (CookieHttpSessionIdResolver) ReflectionTestUtils .getField(sessionRepositoryFilter, "httpSessionIdResolver"); @@ -91,22 +89,17 @@ public class SpringHttpSessionConfigurationTests { DefaultCookieSerializer cookieSerializer = (DefaultCookieSerializer) ReflectionTestUtils .getField(httpSessionIdResolver, "cookieSerializer"); assertThat(cookieSerializer).isNotNull(); - assertThat(ReflectionTestUtils.getField(cookieSerializer, "cookieName")) - .isEqualTo("test-name"); - assertThat(ReflectionTestUtils.getField(cookieSerializer, "cookiePath")) - .isEqualTo("test-path"); - assertThat(ReflectionTestUtils.getField(cookieSerializer, "cookieMaxAge")) - .isEqualTo(600); - assertThat(ReflectionTestUtils.getField(cookieSerializer, "domainName")) - .isEqualTo("test-domain"); + assertThat(ReflectionTestUtils.getField(cookieSerializer, "cookieName")).isEqualTo("test-name"); + assertThat(ReflectionTestUtils.getField(cookieSerializer, "cookiePath")).isEqualTo("test-path"); + assertThat(ReflectionTestUtils.getField(cookieSerializer, "cookieMaxAge")).isEqualTo(600); + assertThat(ReflectionTestUtils.getField(cookieSerializer, "domainName")).isEqualTo("test-domain"); } @Test - public void rememberMeServicesConfiguration() { + void rememberMeServicesConfiguration() { registerAndRefresh(RememberMeServicesConfiguration.class); - SessionRepositoryFilter sessionRepositoryFilter = this.context - .getBean(SessionRepositoryFilter.class); + SessionRepositoryFilter sessionRepositoryFilter = this.context.getBean(SessionRepositoryFilter.class); assertThat(sessionRepositoryFilter).isNotNull(); CookieHttpSessionIdResolver httpSessionIdResolver = (CookieHttpSessionIdResolver) ReflectionTestUtils .getField(sessionRepositoryFilter, "httpSessionIdResolver"); @@ -114,14 +107,14 @@ public class SpringHttpSessionConfigurationTests { DefaultCookieSerializer cookieSerializer = (DefaultCookieSerializer) ReflectionTestUtils .getField(httpSessionIdResolver, "cookieSerializer"); assertThat(cookieSerializer).isNotNull(); - assertThat(ReflectionTestUtils.getField(cookieSerializer, - "rememberMeRequestAttribute")).isEqualTo( - SpringSessionRememberMeServices.REMEMBER_ME_LOGIN_ATTR); + assertThat(ReflectionTestUtils.getField(cookieSerializer, "rememberMeRequestAttribute")) + .isEqualTo(SpringSessionRememberMeServices.REMEMBER_ME_LOGIN_ATTR); } @Configuration @EnableSpringHttpSession static class EmptyConfiguration { + } static class BaseConfiguration { @@ -136,6 +129,7 @@ public class SpringHttpSessionConfigurationTests { @Configuration @EnableSpringHttpSession static class DefaultConfiguration extends BaseConfiguration { + } @Configuration diff --git a/spring-session-core/src/test/java/org/springframework/session/config/annotation/web/server/SpringWebSessionConfigurationTests.java b/spring-session-core/src/test/java/org/springframework/session/config/annotation/web/server/SpringWebSessionConfigurationTests.java index f2245f71..6d9a8e71 100644 --- a/spring-session-core/src/test/java/org/springframework/session/config/annotation/web/server/SpringWebSessionConfigurationTests.java +++ b/spring-session-core/src/test/java/org/springframework/session/config/annotation/web/server/SpringWebSessionConfigurationTests.java @@ -41,18 +41,19 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * * @author Greg Turnquist */ -public class SpringWebSessionConfigurationTests { +class SpringWebSessionConfigurationTests { + private AnnotationConfigApplicationContext context; @AfterEach - public void cleanup() { + void cleanup() { if (this.context != null) { this.context.close(); } } @Test - public void enableSpringWebSessionConfiguresThings() { + void enableSpringWebSessionConfiguresThings() { this.context = new AnnotationConfigApplicationContext(); this.context.register(GoodConfig.class); @@ -69,19 +70,18 @@ public class SpringWebSessionConfigurationTests { } @Test - public void missingReactiveSessionRepositoryBreaksAppContext() { + void missingReactiveSessionRepositoryBreaksAppContext() { this.context = new AnnotationConfigApplicationContext(); this.context.register(BadConfig.class); - assertThatExceptionOfType(UnsatisfiedDependencyException.class) - .isThrownBy(this.context::refresh) - .withMessageContaining("Error creating bean with name 'webSessionManager'") - .withMessageContaining("No qualifying bean of type '" + ReactiveSessionRepository.class.getCanonicalName()); + assertThatExceptionOfType(UnsatisfiedDependencyException.class).isThrownBy(this.context::refresh) + .withMessageContaining("Error creating bean with name 'webSessionManager'").withMessageContaining( + "No qualifying bean of type '" + ReactiveSessionRepository.class.getCanonicalName()); } @Test - public void defaultSessionIdResolverShouldBeCookieBased() { + void defaultSessionIdResolverShouldBeCookieBased() { this.context = new AnnotationConfigApplicationContext(); this.context.register(GoodConfig.class); @@ -92,7 +92,7 @@ public class SpringWebSessionConfigurationTests { } @Test - public void providedSessionIdResolverShouldBePickedUpAutomatically() { + void providedSessionIdResolverShouldBePickedUpAutomatically() { this.context = new AnnotationConfigApplicationContext(); this.context.register(OverrideSessionIdResolver.class); @@ -109,12 +109,14 @@ public class SpringWebSessionConfigurationTests { static class GoodConfig { /** - * Use Reactor-friendly, {@link java.util.Map}-backed {@link ReactiveSessionRepository} for test purposes. + * Use Reactor-friendly, {@link java.util.Map}-backed + * {@link ReactiveSessionRepository} for test purposes. */ @Bean ReactiveSessionRepository reactiveSessionRepository() { return new ReactiveMapSessionRepository(new HashMap<>()); } + } /** @@ -137,6 +139,7 @@ public class SpringWebSessionConfigurationTests { WebSessionIdResolver alternateWebSessionIdResolver() { return new HeaderWebSessionIdResolver(); } + } } diff --git a/spring-session-core/src/test/java/org/springframework/session/security/SpringSessionBackedSessionRegistryTest.java b/spring-session-core/src/test/java/org/springframework/session/security/SpringSessionBackedSessionRegistryTest.java index 0fcb6960..255e03a4 100644 --- a/spring-session-core/src/test/java/org/springframework/session/security/SpringSessionBackedSessionRegistryTest.java +++ b/spring-session-core/src/test/java/org/springframework/session/security/SpringSessionBackedSessionRegistryTest.java @@ -46,7 +46,7 @@ import static org.mockito.BDDMockito.when; /** * Tests for {@link SpringSessionBackedSessionRegistry}. */ -public class SpringSessionBackedSessionRegistryTest { +class SpringSessionBackedSessionRegistryTest { private static final String SESSION_ID = "sessionId"; @@ -54,8 +54,7 @@ public class SpringSessionBackedSessionRegistryTest { private static final String USER_NAME = "userName"; - private static final User PRINCIPAL = new User(USER_NAME, "password", - Collections.emptyList()); + private static final User PRINCIPAL = new User(USER_NAME, "password", Collections.emptyList()); private static final Instant NOW = Instant.now(); @@ -71,74 +70,63 @@ public class SpringSessionBackedSessionRegistryTest { } @Test - public void sessionInformationForExistingSession() { + void sessionInformationForExistingSession() { Session session = createSession(SESSION_ID, USER_NAME, NOW); when(this.sessionRepository.findById(SESSION_ID)).thenReturn(session); - SessionInformation sessionInfo = this.sessionRegistry - .getSessionInformation(SESSION_ID); + SessionInformation sessionInfo = this.sessionRegistry.getSessionInformation(SESSION_ID); assertThat(sessionInfo.getSessionId()).isEqualTo(SESSION_ID); - assertThat( - sessionInfo.getLastRequest().toInstant().truncatedTo(ChronoUnit.MILLIS)) - .isEqualTo(NOW.truncatedTo(ChronoUnit.MILLIS)); + assertThat(sessionInfo.getLastRequest().toInstant().truncatedTo(ChronoUnit.MILLIS)) + .isEqualTo(NOW.truncatedTo(ChronoUnit.MILLIS)); assertThat(sessionInfo.getPrincipal()).isEqualTo(USER_NAME); assertThat(sessionInfo.isExpired()).isFalse(); } @Test - public void sessionInformationForExpiredSession() { + void sessionInformationForExpiredSession() { Session session = createSession(SESSION_ID, USER_NAME, NOW); - session.setAttribute(SpringSessionBackedSessionInformation.EXPIRED_ATTR, - Boolean.TRUE); + session.setAttribute(SpringSessionBackedSessionInformation.EXPIRED_ATTR, Boolean.TRUE); when(this.sessionRepository.findById(SESSION_ID)).thenReturn(session); - SessionInformation sessionInfo = this.sessionRegistry - .getSessionInformation(SESSION_ID); + SessionInformation sessionInfo = this.sessionRegistry.getSessionInformation(SESSION_ID); assertThat(sessionInfo.getSessionId()).isEqualTo(SESSION_ID); - assertThat( - sessionInfo.getLastRequest().toInstant().truncatedTo(ChronoUnit.MILLIS)) + assertThat(sessionInfo.getLastRequest().toInstant().truncatedTo(ChronoUnit.MILLIS)) .isEqualTo(NOW.truncatedTo(ChronoUnit.MILLIS)); assertThat(sessionInfo.getPrincipal()).isEqualTo(USER_NAME); assertThat(sessionInfo.isExpired()).isTrue(); } @Test - public void noSessionInformationForMissingSession() { - assertThat(this.sessionRegistry.getSessionInformation("nonExistingSessionId")) - .isNull(); + void noSessionInformationForMissingSession() { + assertThat(this.sessionRegistry.getSessionInformation("nonExistingSessionId")).isNull(); } @Test - public void getAllSessions() { + void getAllSessions() { setUpSessions(); - List allSessionInfos = this.sessionRegistry - .getAllSessions(PRINCIPAL, true); + List allSessionInfos = this.sessionRegistry.getAllSessions(PRINCIPAL, true); - assertThat(allSessionInfos).extracting("sessionId").containsExactly(SESSION_ID, - SESSION_ID2); + assertThat(allSessionInfos).extracting("sessionId").containsExactly(SESSION_ID, SESSION_ID2); } @Test - public void getNonExpiredSessions() { + void getNonExpiredSessions() { setUpSessions(); - List nonExpiredSessionInfos = this.sessionRegistry - .getAllSessions(PRINCIPAL, false); + List nonExpiredSessionInfos = this.sessionRegistry.getAllSessions(PRINCIPAL, false); - assertThat(nonExpiredSessionInfos).extracting("sessionId") - .containsExactly(SESSION_ID2); + assertThat(nonExpiredSessionInfos).extracting("sessionId").containsExactly(SESSION_ID2); } @Test - public void expireNow() { + void expireNow() { Session session = createSession(SESSION_ID, USER_NAME, NOW); when(this.sessionRepository.findById(SESSION_ID)).thenReturn(session); - SessionInformation sessionInfo = this.sessionRegistry - .getSessionInformation(SESSION_ID); + SessionInformation sessionInfo = this.sessionRegistry.getSessionInformation(SESSION_ID); assertThat(sessionInfo.isExpired()).isFalse(); sessionInfo.expireNow(); @@ -146,13 +134,11 @@ public class SpringSessionBackedSessionRegistryTest { assertThat(sessionInfo.isExpired()).isTrue(); ArgumentCaptor captor = ArgumentCaptor.forClass(Session.class); verify(this.sessionRepository).save(captor.capture()); - assertThat(captor.getValue().getAttribute( - SpringSessionBackedSessionInformation.EXPIRED_ATTR)) - .isEqualTo(Boolean.TRUE); + assertThat(captor.getValue().getAttribute(SpringSessionBackedSessionInformation.EXPIRED_ATTR)) + .isEqualTo(Boolean.TRUE); } - private Session createSession(String sessionId, String userName, - Instant lastAccessed) { + private Session createSession(String sessionId, String userName, Instant lastAccessed) { MapSession session = new MapSession(sessionId); session.setLastAccessedTime(lastAccessed); Authentication authentication = mock(Authentication.class); @@ -165,14 +151,12 @@ public class SpringSessionBackedSessionRegistryTest { private void setUpSessions() { Session session1 = createSession(SESSION_ID, USER_NAME, NOW); - session1.setAttribute(SpringSessionBackedSessionInformation.EXPIRED_ATTR, - Boolean.TRUE); + session1.setAttribute(SpringSessionBackedSessionInformation.EXPIRED_ATTR, Boolean.TRUE); Session session2 = createSession(SESSION_ID2, USER_NAME, NOW); Map sessions = new LinkedHashMap<>(); sessions.put(session1.getId(), session1); sessions.put(session2.getId(), session2); - when(this.sessionRepository.findByPrincipalName(USER_NAME)) - .thenReturn(sessions); + when(this.sessionRepository.findByPrincipalName(USER_NAME)).thenReturn(sessions); } } diff --git a/spring-session-core/src/test/java/org/springframework/session/security/web/authentication/SpringSessionRememberMeServicesTests.java b/spring-session-core/src/test/java/org/springframework/session/security/web/authentication/SpringSessionRememberMeServicesTests.java index 3b6671e9..b6326b98 100644 --- a/spring-session-core/src/test/java/org/springframework/session/security/web/authentication/SpringSessionRememberMeServicesTests.java +++ b/spring-session-core/src/test/java/org/springframework/session/security/web/authentication/SpringSessionRememberMeServicesTests.java @@ -40,60 +40,50 @@ import static org.mockito.Mockito.verifyZeroInteractions; * * @author Vedran Pavic */ -public class SpringSessionRememberMeServicesTests { +class SpringSessionRememberMeServicesTests { private SpringSessionRememberMeServices rememberMeServices; @Test - public void create() { + void create() { this.rememberMeServices = new SpringSessionRememberMeServices(); - assertThat(ReflectionTestUtils.getField(this.rememberMeServices, - "rememberMeParameterName")).isEqualTo("remember-me"); - assertThat( - ReflectionTestUtils.getField(this.rememberMeServices, "alwaysRemember")) - .isEqualTo(false); - assertThat( - ReflectionTestUtils.getField(this.rememberMeServices, "validitySeconds")) - .isEqualTo(2592000); + assertThat(ReflectionTestUtils.getField(this.rememberMeServices, "rememberMeParameterName")) + .isEqualTo("remember-me"); + assertThat(ReflectionTestUtils.getField(this.rememberMeServices, "alwaysRemember")).isEqualTo(false); + assertThat(ReflectionTestUtils.getField(this.rememberMeServices, "validitySeconds")).isEqualTo(2592000); } @Test - public void createWithCustomParameter() { + void createWithCustomParameter() { this.rememberMeServices = new SpringSessionRememberMeServices(); this.rememberMeServices.setRememberMeParameterName("test-param"); - assertThat(ReflectionTestUtils.getField(this.rememberMeServices, - "rememberMeParameterName")).isEqualTo("test-param"); + assertThat(ReflectionTestUtils.getField(this.rememberMeServices, "rememberMeParameterName")) + .isEqualTo("test-param"); } @Test - public void createWithNullParameter() { + void createWithNullParameter() { this.rememberMeServices = new SpringSessionRememberMeServices(); - assertThatIllegalArgumentException() - .isThrownBy( - () -> this.rememberMeServices.setRememberMeParameterName(null)) + assertThatIllegalArgumentException().isThrownBy(() -> this.rememberMeServices.setRememberMeParameterName(null)) .withMessage("rememberMeParameterName cannot be empty or null"); } @Test - public void createWithAlwaysRemember() { + void createWithAlwaysRemember() { this.rememberMeServices = new SpringSessionRememberMeServices(); this.rememberMeServices.setAlwaysRemember(true); - assertThat( - ReflectionTestUtils.getField(this.rememberMeServices, "alwaysRemember")) - .isEqualTo(true); + assertThat(ReflectionTestUtils.getField(this.rememberMeServices, "alwaysRemember")).isEqualTo(true); } @Test - public void createWithCustomValidity() { + void createWithCustomValidity() { this.rememberMeServices = new SpringSessionRememberMeServices(); this.rememberMeServices.setValiditySeconds(100000); - assertThat( - ReflectionTestUtils.getField(this.rememberMeServices, "validitySeconds")) - .isEqualTo(100000); + assertThat(ReflectionTestUtils.getField(this.rememberMeServices, "validitySeconds")).isEqualTo(100000); } @Test - public void autoLogin() { + void autoLogin() { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); this.rememberMeServices = new SpringSessionRememberMeServices(); @@ -103,7 +93,7 @@ public class SpringSessionRememberMeServicesTests { // gh-752 @Test - public void loginFailRemoveSecurityContext() { + void loginFailRemoveSecurityContext() { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); HttpSession session = mock(HttpSession.class); @@ -111,13 +101,12 @@ public class SpringSessionRememberMeServicesTests { this.rememberMeServices = new SpringSessionRememberMeServices(); this.rememberMeServices.loginFail(request, response); verify(request, times(1)).getSession(eq(false)); - verify(session, times(1)).removeAttribute( - HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY); + verify(session, times(1)).removeAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY); verifyZeroInteractions(request, response, session); } @Test - public void loginSuccess() { + void loginSuccess() { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); Authentication authentication = mock(Authentication.class); @@ -128,14 +117,13 @@ public class SpringSessionRememberMeServicesTests { this.rememberMeServices.loginSuccess(request, response, authentication); verify(request, times(1)).getParameter(eq("remember-me")); verify(request, times(1)).getSession(); - verify(request, times(1)).setAttribute( - eq(SpringSessionRememberMeServices.REMEMBER_ME_LOGIN_ATTR), eq(true)); + verify(request, times(1)).setAttribute(eq(SpringSessionRememberMeServices.REMEMBER_ME_LOGIN_ATTR), eq(true)); verify(session, times(1)).setMaxInactiveInterval(eq(2592000)); verifyZeroInteractions(request, response, session, authentication); } @Test - public void loginSuccessWithCustomParameter() { + void loginSuccessWithCustomParameter() { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); Authentication authentication = mock(Authentication.class); @@ -147,14 +135,13 @@ public class SpringSessionRememberMeServicesTests { this.rememberMeServices.loginSuccess(request, response, authentication); verify(request, times(1)).getParameter(eq("test-param")); verify(request, times(1)).getSession(); - verify(request, times(1)).setAttribute( - eq(SpringSessionRememberMeServices.REMEMBER_ME_LOGIN_ATTR), eq(true)); + verify(request, times(1)).setAttribute(eq(SpringSessionRememberMeServices.REMEMBER_ME_LOGIN_ATTR), eq(true)); verify(session, times(1)).setMaxInactiveInterval(eq(2592000)); verifyZeroInteractions(request, response, session, authentication); } @Test - public void loginSuccessWithAlwaysRemember() { + void loginSuccessWithAlwaysRemember() { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); Authentication authentication = mock(Authentication.class); @@ -164,14 +151,13 @@ public class SpringSessionRememberMeServicesTests { this.rememberMeServices.setAlwaysRemember(true); this.rememberMeServices.loginSuccess(request, response, authentication); verify(request, times(1)).getSession(); - verify(request, times(1)).setAttribute( - eq(SpringSessionRememberMeServices.REMEMBER_ME_LOGIN_ATTR), eq(true)); + verify(request, times(1)).setAttribute(eq(SpringSessionRememberMeServices.REMEMBER_ME_LOGIN_ATTR), eq(true)); verify(session, times(1)).setMaxInactiveInterval(eq(2592000)); verifyZeroInteractions(request, response, session, authentication); } @Test - public void loginSuccessWithCustomValidity() { + void loginSuccessWithCustomValidity() { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); Authentication authentication = mock(Authentication.class); @@ -183,8 +169,7 @@ public class SpringSessionRememberMeServicesTests { this.rememberMeServices.loginSuccess(request, response, authentication); verify(request, times(1)).getParameter(eq("remember-me")); verify(request, times(1)).getSession(); - verify(request, times(1)).setAttribute( - eq(SpringSessionRememberMeServices.REMEMBER_ME_LOGIN_ATTR), eq(true)); + verify(request, times(1)).setAttribute(eq(SpringSessionRememberMeServices.REMEMBER_ME_LOGIN_ATTR), eq(true)); verify(session, times(1)).setMaxInactiveInterval(eq(100000)); verifyZeroInteractions(request, response, session, authentication); } diff --git a/spring-session-core/src/test/java/org/springframework/session/web/http/CookieHttpSessionIdResolverTests.java b/spring-session-core/src/test/java/org/springframework/session/web/http/CookieHttpSessionIdResolverTests.java index c10e00a5..d502121f 100644 --- a/spring-session-core/src/test/java/org/springframework/session/web/http/CookieHttpSessionIdResolverTests.java +++ b/spring-session-core/src/test/java/org/springframework/session/web/http/CookieHttpSessionIdResolverTests.java @@ -34,17 +34,20 @@ import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link CookieHttpSessionIdResolver}. */ -public class CookieHttpSessionIdResolverTests { +class CookieHttpSessionIdResolverTests { private MockHttpServletRequest request; + private MockHttpServletResponse response; private CookieHttpSessionIdResolver strategy; + private String cookieName; + private Session session; @BeforeEach - public void setup() throws Exception { + void setup() throws Exception { this.cookieName = "SESSION"; this.session = new MapSession(); this.request = new MockHttpServletRequest(); @@ -53,19 +56,19 @@ public class CookieHttpSessionIdResolverTests { } @Test - public void getRequestedSessionIdNull() throws Exception { + void getRequestedSessionIdNull() throws Exception { assertThat(this.strategy.resolveSessionIds(this.request)).isEmpty(); } @Test - public void getRequestedSessionIdNotNull() throws Exception { + void getRequestedSessionIdNotNull() throws Exception { setSessionCookie(this.session.getId()); assertThat(this.strategy.resolveSessionIds(this.request)) .isEqualTo(Collections.singletonList(this.session.getId())); } @Test - public void getRequestedSessionIdNotNullCustomCookieName() throws Exception { + void getRequestedSessionIdNotNullCustomCookieName() throws Exception { setCookieName("CUSTOM"); setSessionCookie(this.session.getId()); assertThat(this.strategy.resolveSessionIds(this.request)) @@ -73,13 +76,13 @@ public class CookieHttpSessionIdResolverTests { } @Test - public void onNewSession() throws Exception { + void onNewSession() throws Exception { this.strategy.setSessionId(this.request, this.response, this.session.getId()); assertThat(getSessionId()).isEqualTo(this.session.getId()); } @Test - public void onNewSessionTwiceSameId() throws Exception { + void onNewSessionTwiceSameId() throws Exception { this.strategy.setSessionId(this.request, this.response, this.session.getId()); this.strategy.setSessionId(this.request, this.response, this.session.getId()); @@ -87,7 +90,7 @@ public class CookieHttpSessionIdResolverTests { } @Test - public void onNewSessionTwiceNewId() throws Exception { + void onNewSessionTwiceNewId() throws Exception { Session newSession = new MapSession(); this.strategy.setSessionId(this.request, this.response, this.session.getId()); @@ -101,49 +104,47 @@ public class CookieHttpSessionIdResolverTests { } @Test - public void onNewSessionCookiePath() throws Exception { + void onNewSessionCookiePath() throws Exception { this.request.setContextPath("/somethingunique"); this.strategy.setSessionId(this.request, this.response, this.session.getId()); Cookie sessionCookie = this.response.getCookie(this.cookieName); - assertThat(sessionCookie.getPath()) - .isEqualTo(this.request.getContextPath() + "/"); + assertThat(sessionCookie.getPath()).isEqualTo(this.request.getContextPath() + "/"); } @Test - public void onNewSessionCustomCookieName() throws Exception { + void onNewSessionCustomCookieName() throws Exception { setCookieName("CUSTOM"); this.strategy.setSessionId(this.request, this.response, this.session.getId()); assertThat(getSessionId()).isEqualTo(this.session.getId()); } @Test - public void onDeleteSession() throws Exception { + void onDeleteSession() throws Exception { this.strategy.expireSession(this.request, this.response); assertThat(getSessionId()).isEmpty(); } @Test - public void onDeleteSessionCookiePath() throws Exception { + void onDeleteSessionCookiePath() throws Exception { this.request.setContextPath("/somethingunique"); this.strategy.expireSession(this.request, this.response); Cookie sessionCookie = this.response.getCookie(this.cookieName); - assertThat(sessionCookie.getPath()) - .isEqualTo(this.request.getContextPath() + "/"); + assertThat(sessionCookie.getPath()).isEqualTo(this.request.getContextPath() + "/"); } @Test - public void onDeleteSessionCustomCookieName() throws Exception { + void onDeleteSessionCustomCookieName() throws Exception { setCookieName("CUSTOM"); this.strategy.expireSession(this.request, this.response); assertThat(getSessionId()).isEmpty(); } @Test - public void createSessionCookieValue() { - assertThat(createSessionCookieValue(17)).isEqualToIgnoringCase( - "0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 a 10 b 11 c 12 d 13 e 14 f 15 10 16"); + void createSessionCookieValue() { + assertThat(createSessionCookieValue(17)) + .isEqualToIgnoringCase("0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 a 10 b 11 c 12 d 13 e 14 f 15 10 16"); } private String createSessionCookieValue(long size) { diff --git a/spring-session-core/src/test/java/org/springframework/session/web/http/DefaultCookieSerializerTests.java b/spring-session-core/src/test/java/org/springframework/session/web/http/DefaultCookieSerializerTests.java index 246edaa6..c8a5d115 100644 --- a/spring-session-core/src/test/java/org/springframework/session/web/http/DefaultCookieSerializerTests.java +++ b/spring-session-core/src/test/java/org/springframework/session/web/http/DefaultCookieSerializerTests.java @@ -42,7 +42,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; * @author Vedran Pavic * @author Eddú Meléndez */ -public class DefaultCookieSerializerTests { +class DefaultCookieSerializerTests { private String cookieName; @@ -55,7 +55,7 @@ public class DefaultCookieSerializerTests { private String sessionId; @BeforeEach - public void setup() { + void setup() { this.cookieName = "SESSION"; this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); @@ -66,23 +66,21 @@ public class DefaultCookieSerializerTests { // --- readCookieValues --- @Test - public void readCookieValuesNull() { + void readCookieValuesNull() { assertThat(this.serializer.readCookieValues(this.request)).isEmpty(); } @ParameterizedTest @ValueSource(strings = { "true", "false" }) - public void readCookieValuesSingle(boolean useBase64Encoding) { + void readCookieValuesSingle(boolean useBase64Encoding) { this.serializer.setUseBase64Encoding(useBase64Encoding); - this.request.setCookies( - createCookie(this.cookieName, this.sessionId, useBase64Encoding)); + this.request.setCookies(createCookie(this.cookieName, this.sessionId, useBase64Encoding)); - assertThat(this.serializer.readCookieValues(this.request)) - .containsOnly(this.sessionId); + assertThat(this.serializer.readCookieValues(this.request)).containsOnly(this.sessionId); } @Test - public void readCookieSerializerUseBase64EncodingTrueValuesNotBase64() { + void readCookieSerializerUseBase64EncodingTrueValuesNotBase64() { this.sessionId = "&^%$*"; this.serializer.setUseBase64Encoding(true); this.request.setCookies(new Cookie(this.cookieName, this.sessionId)); @@ -92,48 +90,41 @@ public class DefaultCookieSerializerTests { @ParameterizedTest @ValueSource(strings = { "true", "false" }) - public void readCookieValuesSingleAndInvalidName(boolean useBase64Encoding) { + void readCookieValuesSingleAndInvalidName(boolean useBase64Encoding) { this.serializer.setUseBase64Encoding(useBase64Encoding); - this.request.setCookies( - createCookie(this.cookieName, this.sessionId, useBase64Encoding), - createCookie(this.cookieName + "INVALID", this.sessionId + "INVALID", - useBase64Encoding)); + this.request.setCookies(createCookie(this.cookieName, this.sessionId, useBase64Encoding), + createCookie(this.cookieName + "INVALID", this.sessionId + "INVALID", useBase64Encoding)); - assertThat(this.serializer.readCookieValues(this.request)) - .containsOnly(this.sessionId); + assertThat(this.serializer.readCookieValues(this.request)).containsOnly(this.sessionId); } @ParameterizedTest @ValueSource(strings = { "true", "false" }) - public void readCookieValuesMulti(boolean useBase64Encoding) { + void readCookieValuesMulti(boolean useBase64Encoding) { this.serializer.setUseBase64Encoding(useBase64Encoding); String secondSession = "secondSessionId"; - this.request.setCookies( - createCookie(this.cookieName, this.sessionId, useBase64Encoding), + this.request.setCookies(createCookie(this.cookieName, this.sessionId, useBase64Encoding), createCookie(this.cookieName, secondSession, useBase64Encoding)); - assertThat(this.serializer.readCookieValues(this.request)) - .containsExactly(this.sessionId, secondSession); + assertThat(this.serializer.readCookieValues(this.request)).containsExactly(this.sessionId, secondSession); } @ParameterizedTest @ValueSource(strings = { "true", "false" }) - public void readCookieValuesMultiCustomSessionCookieName(boolean useBase64Encoding) { + void readCookieValuesMultiCustomSessionCookieName(boolean useBase64Encoding) { this.serializer.setUseBase64Encoding(useBase64Encoding); setCookieName("JSESSIONID"); String secondSession = "secondSessionId"; - this.request.setCookies( - createCookie(this.cookieName, this.sessionId, useBase64Encoding), + this.request.setCookies(createCookie(this.cookieName, this.sessionId, useBase64Encoding), createCookie(this.cookieName, secondSession, useBase64Encoding)); - assertThat(this.serializer.readCookieValues(this.request)) - .containsExactly(this.sessionId, secondSession); + assertThat(this.serializer.readCookieValues(this.request)).containsExactly(this.sessionId, secondSession); } // gh-392 @ParameterizedTest @ValueSource(strings = { "true", "false" }) - public void readCookieValuesNullCookieValue(boolean useBase64Encoding) { + void readCookieValuesNullCookieValue(boolean useBase64Encoding) { this.serializer.setUseBase64Encoding(useBase64Encoding); this.request.setCookies(createCookie(this.cookieName, null, useBase64Encoding)); @@ -142,7 +133,7 @@ public class DefaultCookieSerializerTests { @ParameterizedTest @ValueSource(strings = { "true", "false" }) - public void readCookieValuesNullCookieValueAndJvmRoute(boolean useBase64Encoding) { + void readCookieValuesNullCookieValueAndJvmRoute(boolean useBase64Encoding) { this.serializer.setJvmRoute("123"); this.request.setCookies(createCookie(this.cookieName, null, useBase64Encoding)); @@ -151,21 +142,20 @@ public class DefaultCookieSerializerTests { @ParameterizedTest @ValueSource(strings = { "true", "false" }) - public void readCookieValuesNullCookieValueAndNotNullCookie(boolean useBase64Encoding) { + void readCookieValuesNullCookieValueAndNotNullCookie(boolean useBase64Encoding) { this.serializer.setUseBase64Encoding(useBase64Encoding); this.serializer.setJvmRoute("123"); this.request.setCookies(createCookie(this.cookieName, null, useBase64Encoding), createCookie(this.cookieName, this.sessionId, useBase64Encoding)); - assertThat(this.serializer.readCookieValues(this.request)) - .containsOnly(this.sessionId); + assertThat(this.serializer.readCookieValues(this.request)).containsOnly(this.sessionId); } // --- writeCookie --- @ParameterizedTest @ValueSource(strings = { "true", "false" }) - public void writeCookie(boolean useBase64Encoding) { + void writeCookie(boolean useBase64Encoding) { this.serializer.setUseBase64Encoding(useBase64Encoding); this.serializer.writeCookieValue(cookieValue(this.sessionId)); @@ -175,14 +165,14 @@ public class DefaultCookieSerializerTests { // --- httpOnly --- @Test - public void writeCookieHttpOnlyDefault() { + void writeCookieHttpOnlyDefault() { this.serializer.writeCookieValue(cookieValue(this.sessionId)); assertThat(getCookie().isHttpOnly()).isTrue(); } @Test - public void writeCookieHttpOnlySetTrue() { + void writeCookieHttpOnlySetTrue() { this.serializer.setUseHttpOnlyCookie(true); this.serializer.writeCookieValue(cookieValue(this.sessionId)); @@ -191,7 +181,7 @@ public class DefaultCookieSerializerTests { } @Test - public void writeCookieHttpOnlySetFalse() { + void writeCookieHttpOnlySetFalse() { this.serializer.setUseHttpOnlyCookie(false); this.serializer.writeCookieValue(cookieValue(this.sessionId)); @@ -202,14 +192,14 @@ public class DefaultCookieSerializerTests { // --- domainName --- @Test - public void writeCookieDomainNameDefault() { + void writeCookieDomainNameDefault() { this.serializer.writeCookieValue(cookieValue(this.sessionId)); assertThat(getCookie().getDomain()).isNull(); } @Test - public void writeCookieDomainNameCustom() { + void writeCookieDomainNameCustom() { String domainName = "example.com"; this.serializer.setDomainName(domainName); @@ -219,17 +209,16 @@ public class DefaultCookieSerializerTests { } @Test - public void setDomainNameAndDomainNamePatternThrows() { + void setDomainNameAndDomainNamePatternThrows() { this.serializer.setDomainName("example.com"); - assertThatIllegalStateException() - .isThrownBy(() -> this.serializer.setDomainNamePattern(".*")) + assertThatIllegalStateException().isThrownBy(() -> this.serializer.setDomainNamePattern(".*")) .withMessage("Cannot set both domainName and domainNamePattern"); } // --- domainNamePattern --- @Test - public void writeCookieDomainNamePattern() { + void writeCookieDomainNamePattern() { String domainNamePattern = "^.+?\\.(\\w+\\.[a-z]+)$"; this.serializer.setDomainNamePattern(domainNamePattern); @@ -253,24 +242,23 @@ public class DefaultCookieSerializerTests { } @Test - public void setDomainNamePatternAndDomainNameThrows() { + void setDomainNamePatternAndDomainNameThrows() { this.serializer.setDomainNamePattern(".*"); - assertThatIllegalStateException() - .isThrownBy(() -> this.serializer.setDomainName("example.com")) + assertThatIllegalStateException().isThrownBy(() -> this.serializer.setDomainName("example.com")) .withMessage("Cannot set both domainName and domainNamePattern"); } // --- cookieName --- @Test - public void writeCookieCookieNameDefault() { + void writeCookieCookieNameDefault() { this.serializer.writeCookieValue(cookieValue(this.sessionId)); assertThat(getCookie().getName()).isEqualTo("SESSION"); } @Test - public void writeCookieCookieNameCustom() { + void writeCookieCookieNameCustom() { String cookieName = "JSESSIONID"; setCookieName(cookieName); @@ -280,16 +268,15 @@ public class DefaultCookieSerializerTests { } @Test - public void setCookieNameNullThrows() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.serializer.setCookieName(null)) + void setCookieNameNullThrows() { + assertThatIllegalArgumentException().isThrownBy(() -> this.serializer.setCookieName(null)) .withMessage("cookieName cannot be null"); } // --- cookiePath --- @Test - public void writeCookieCookiePathDefaultEmptyContextPathUsed() { + void writeCookieCookiePathDefaultEmptyContextPathUsed() { this.request.setContextPath(""); this.serializer.writeCookieValue(cookieValue(this.sessionId)); @@ -298,7 +285,7 @@ public class DefaultCookieSerializerTests { } @Test - public void writeCookieCookiePathDefaultContextPathUsed() { + void writeCookieCookiePathDefaultContextPathUsed() { this.request.setContextPath("/context"); this.serializer.writeCookieValue(cookieValue(this.sessionId)); @@ -307,7 +294,7 @@ public class DefaultCookieSerializerTests { } @Test - public void writeCookieCookiePathExplicitNullCookiePathContextPathUsed() { + void writeCookieCookiePathExplicitNullCookiePathContextPathUsed() { this.request.setContextPath("/context"); this.serializer.setCookiePath(null); @@ -317,7 +304,7 @@ public class DefaultCookieSerializerTests { } @Test - public void writeCookieCookiePathExplicitCookiePath() { + void writeCookieCookiePathExplicitCookiePath() { this.request.setContextPath("/context"); this.serializer.setCookiePath("/"); @@ -329,14 +316,14 @@ public class DefaultCookieSerializerTests { // --- cookieMaxAge --- @Test - public void writeCookieCookieMaxAgeDefault() { + void writeCookieCookieMaxAgeDefault() { this.serializer.writeCookieValue(cookieValue(this.sessionId)); assertThat(getCookie().getMaxAge()).isEqualTo(-1); } @Test - public void writeCookieCookieMaxAgeExplicit() { + void writeCookieCookieMaxAgeExplicit() { this.serializer.setCookieMaxAge(100); this.serializer.writeCookieValue(cookieValue(this.sessionId)); @@ -345,7 +332,7 @@ public class DefaultCookieSerializerTests { } @Test - public void writeCookieCookieMaxAgeExplicitEmptyCookie() { + void writeCookieCookieMaxAgeExplicitEmptyCookie() { this.serializer.setCookieMaxAge(100); this.serializer.writeCookieValue(cookieValue("")); @@ -354,7 +341,7 @@ public class DefaultCookieSerializerTests { } @Test - public void writeCookieCookieMaxAgeExplicitCookieValue() { + void writeCookieCookieMaxAgeExplicitCookieValue() { CookieValue cookieValue = cookieValue(this.sessionId); cookieValue.setCookieMaxAge(100); @@ -366,14 +353,14 @@ public class DefaultCookieSerializerTests { // --- secure --- @Test - public void writeCookieDefaultInsecureRequest() { + void writeCookieDefaultInsecureRequest() { this.serializer.writeCookieValue(cookieValue(this.sessionId)); assertThat(getCookie().getSecure()).isFalse(); } @Test - public void writeCookieSecureSecureRequest() { + void writeCookieSecureSecureRequest() { this.request.setSecure(true); this.serializer.setUseSecureCookie(true); @@ -383,7 +370,7 @@ public class DefaultCookieSerializerTests { } @Test - public void writeCookieSecureInsecureRequest() { + void writeCookieSecureInsecureRequest() { this.serializer.setUseSecureCookie(true); this.serializer.writeCookieValue(cookieValue(this.sessionId)); @@ -392,7 +379,7 @@ public class DefaultCookieSerializerTests { } @Test - public void writeCookieInsecureSecureRequest() { + void writeCookieInsecureSecureRequest() { this.request.setSecure(true); this.serializer.setUseSecureCookie(false); @@ -402,7 +389,7 @@ public class DefaultCookieSerializerTests { } @Test - public void writeCookieInecureInsecureRequest() { + void writeCookieInecureInsecureRequest() { this.serializer.setUseSecureCookie(false); this.serializer.writeCookieValue(cookieValue(this.sessionId)); @@ -414,51 +401,45 @@ public class DefaultCookieSerializerTests { @ParameterizedTest @ValueSource(strings = { "true", "false" }) - public void writeCookieJvmRoute(boolean useBase64Encoding) { + void writeCookieJvmRoute(boolean useBase64Encoding) { this.serializer.setUseBase64Encoding(useBase64Encoding); String jvmRoute = "route"; this.serializer.setJvmRoute(jvmRoute); this.serializer.writeCookieValue(cookieValue(this.sessionId)); - assertThat(getCookieValue(useBase64Encoding)) - .isEqualTo(this.sessionId + "." + jvmRoute); + assertThat(getCookieValue(useBase64Encoding)).isEqualTo(this.sessionId + "." + jvmRoute); } @ParameterizedTest @ValueSource(strings = { "true", "false" }) - public void readCookieJvmRoute(boolean useBase64Encoding) { + void readCookieJvmRoute(boolean useBase64Encoding) { this.serializer.setUseBase64Encoding(useBase64Encoding); String jvmRoute = "route"; this.serializer.setJvmRoute(jvmRoute); - this.request.setCookies(createCookie(this.cookieName, - this.sessionId + "." + jvmRoute, useBase64Encoding)); + this.request.setCookies(createCookie(this.cookieName, this.sessionId + "." + jvmRoute, useBase64Encoding)); - assertThat(this.serializer.readCookieValues(this.request)) - .containsOnly(this.sessionId); + assertThat(this.serializer.readCookieValues(this.request)).containsOnly(this.sessionId); } @ParameterizedTest @ValueSource(strings = { "true", "false" }) - public void readCookieJvmRouteRouteMissing(boolean useBase64Encoding) { + void readCookieJvmRouteRouteMissing(boolean useBase64Encoding) { this.serializer.setUseBase64Encoding(useBase64Encoding); String jvmRoute = "route"; this.serializer.setJvmRoute(jvmRoute); - this.request.setCookies( - createCookie(this.cookieName, this.sessionId, useBase64Encoding)); + this.request.setCookies(createCookie(this.cookieName, this.sessionId, useBase64Encoding)); - assertThat(this.serializer.readCookieValues(this.request)) - .containsOnly(this.sessionId); + assertThat(this.serializer.readCookieValues(this.request)).containsOnly(this.sessionId); } @ParameterizedTest @ValueSource(strings = { "true", "false" }) - public void readCookieJvmRouteOnlyRoute(boolean useBase64Encoding) { + void readCookieJvmRouteOnlyRoute(boolean useBase64Encoding) { this.serializer.setUseBase64Encoding(useBase64Encoding); String jvmRoute = "route"; this.serializer.setJvmRoute(jvmRoute); - this.request.setCookies( - createCookie(this.cookieName, "." + jvmRoute, useBase64Encoding)); + this.request.setCookies(createCookie(this.cookieName, "." + jvmRoute, useBase64Encoding)); assertThat(this.serializer.readCookieValues(this.request)).containsOnly(""); } @@ -466,7 +447,7 @@ public class DefaultCookieSerializerTests { // --- rememberMe --- @Test - public void writeCookieRememberMeCookieMaxAgeDefault() { + void writeCookieRememberMeCookieMaxAgeDefault() { this.request.setAttribute("rememberMe", true); this.serializer.setRememberMeRequestAttribute("rememberMe"); this.serializer.writeCookieValue(cookieValue(this.sessionId)); @@ -475,7 +456,7 @@ public class DefaultCookieSerializerTests { } @Test - public void writeCookieRememberMeCookieMaxAgeOverride() { + void writeCookieRememberMeCookieMaxAgeOverride() { this.request.setAttribute("rememberMe", true); this.serializer.setRememberMeRequestAttribute("rememberMe"); CookieValue cookieValue = cookieValue(this.sessionId); @@ -488,14 +469,14 @@ public class DefaultCookieSerializerTests { // --- sameSite --- @Test - public void writeCookieDefaultSameSiteLax() { + void writeCookieDefaultSameSiteLax() { this.serializer.writeCookieValue(cookieValue(this.sessionId)); assertThat(getCookie().getSameSite()).isEqualTo("Lax"); } @Test - public void writeCookieSetSameSiteLax() { + void writeCookieSetSameSiteLax() { this.serializer.setSameSite("Lax"); this.serializer.writeCookieValue(cookieValue(this.sessionId)); @@ -503,7 +484,7 @@ public class DefaultCookieSerializerTests { } @Test - public void writeCookieSetSameSiteStrict() { + void writeCookieSetSameSiteStrict() { this.serializer.setSameSite("Strict"); this.serializer.writeCookieValue(cookieValue(this.sessionId)); @@ -511,7 +492,7 @@ public class DefaultCookieSerializerTests { } @Test - public void writeCookieSetSameSiteNull() { + void writeCookieSetSameSiteNull() { this.serializer.setSameSite(null); this.serializer.writeCookieValue(cookieValue(this.sessionId)); diff --git a/spring-session-core/src/test/java/org/springframework/session/web/http/HeaderHttpSessionIdResolverTests.java b/spring-session-core/src/test/java/org/springframework/session/web/http/HeaderHttpSessionIdResolverTests.java index 4c911359..81b6671c 100644 --- a/spring-session-core/src/test/java/org/springframework/session/web/http/HeaderHttpSessionIdResolverTests.java +++ b/spring-session-core/src/test/java/org/springframework/session/web/http/HeaderHttpSessionIdResolverTests.java @@ -32,7 +32,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException /** * Tests for {@link HeaderHttpSessionIdResolver}. */ -public class HeaderHttpSessionIdResolverTests { +class HeaderHttpSessionIdResolverTests { private static final String HEADER_X_AUTH_TOKEN = "X-Auth-Token"; @@ -43,71 +43,64 @@ public class HeaderHttpSessionIdResolverTests { private HeaderHttpSessionIdResolver resolver; @BeforeEach - public void setup() { + void setup() { this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); this.resolver = HeaderHttpSessionIdResolver.xAuthToken(); } @Test - public void createResolverWithXAuthTokenHeader() { + void createResolverWithXAuthTokenHeader() { HeaderHttpSessionIdResolver resolver = HeaderHttpSessionIdResolver.xAuthToken(); - assertThat(ReflectionTestUtils.getField(resolver, "headerName")) - .isEqualTo("X-Auth-Token"); + assertThat(ReflectionTestUtils.getField(resolver, "headerName")).isEqualTo("X-Auth-Token"); } @Test - public void createResolverWithAuthenticationInfoHeader() { - HeaderHttpSessionIdResolver resolver = HeaderHttpSessionIdResolver - .authenticationInfo(); - assertThat(ReflectionTestUtils.getField(resolver, "headerName")) - .isEqualTo("Authentication-Info"); + void createResolverWithAuthenticationInfoHeader() { + HeaderHttpSessionIdResolver resolver = HeaderHttpSessionIdResolver.authenticationInfo(); + assertThat(ReflectionTestUtils.getField(resolver, "headerName")).isEqualTo("Authentication-Info"); } @Test - public void createResolverWithCustomHeaderName() { - HeaderHttpSessionIdResolver resolver = new HeaderHttpSessionIdResolver( - "Custom-Header"); - assertThat(ReflectionTestUtils.getField(resolver, "headerName")) - .isEqualTo("Custom-Header"); + void createResolverWithCustomHeaderName() { + HeaderHttpSessionIdResolver resolver = new HeaderHttpSessionIdResolver("Custom-Header"); + assertThat(ReflectionTestUtils.getField(resolver, "headerName")).isEqualTo("Custom-Header"); } @Test - public void createResolverWithNullHeaderName() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new HeaderHttpSessionIdResolver(null)) + void createResolverWithNullHeaderName() { + assertThatIllegalArgumentException().isThrownBy(() -> new HeaderHttpSessionIdResolver(null)) .withMessage("headerName cannot be null"); } @Test - public void getRequestedSessionIdNull() { + void getRequestedSessionIdNull() { assertThat(this.resolver.resolveSessionIds(this.request)).isEmpty(); } @Test - public void getRequestedSessionIdNotNull() { + void getRequestedSessionIdNotNull() { String sessionId = UUID.randomUUID().toString(); setSessionId(sessionId); - assertThat(this.resolver.resolveSessionIds(this.request)) - .isEqualTo(Collections.singletonList(sessionId)); + assertThat(this.resolver.resolveSessionIds(this.request)).isEqualTo(Collections.singletonList(sessionId)); } @Test - public void onNewSession() { + void onNewSession() { String sessionId = UUID.randomUUID().toString(); this.resolver.setSessionId(this.request, this.response, sessionId); assertThat(getSessionId()).isEqualTo(sessionId); } @Test - public void onDeleteSession() { + void onDeleteSession() { this.resolver.expireSession(this.request, this.response); assertThat(getSessionId()).isEmpty(); } // the header is set as apposed to added @Test - public void onNewSessionMulti() { + void onNewSessionMulti() { String sessionId = UUID.randomUUID().toString(); this.resolver.setSessionId(this.request, this.response, sessionId); this.resolver.setSessionId(this.request, this.response, sessionId); @@ -117,7 +110,7 @@ public class HeaderHttpSessionIdResolverTests { // the header is set as apposed to added @Test - public void onDeleteSessionMulti() { + void onDeleteSessionMulti() { this.resolver.expireSession(this.request, this.response); this.resolver.expireSession(this.request, this.response); assertThat(this.response.getHeaders(HEADER_X_AUTH_TOKEN).size()).isEqualTo(1); diff --git a/spring-session-core/src/test/java/org/springframework/session/web/http/OnCommittedResponseWrapperTests.java b/spring-session-core/src/test/java/org/springframework/session/web/http/OnCommittedResponseWrapperTests.java index 74ffe250..760ca5d7 100644 --- a/spring-session-core/src/test/java/org/springframework/session/web/http/OnCommittedResponseWrapperTests.java +++ b/spring-session-core/src/test/java/org/springframework/session/web/http/OnCommittedResponseWrapperTests.java @@ -32,22 +32,25 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; -public class OnCommittedResponseWrapperTests { +class OnCommittedResponseWrapperTests { + private static final String NL = "\r\n"; @Mock HttpServletResponse delegate; + @Mock PrintWriter writer; + @Mock ServletOutputStream out; - OnCommittedResponseWrapper response; + private OnCommittedResponseWrapper response; - boolean committed; + private boolean committed; @BeforeEach - public void setup() throws Exception { + void setup() throws Exception { MockitoAnnotations.initMocks(this); this.response = new OnCommittedResponseWrapper(this.delegate) { @Override @@ -62,14 +65,14 @@ public class OnCommittedResponseWrapperTests { // --- printwriter @Test - public void printWriterHashCode() throws Exception { + void printWriterHashCode() throws Exception { int expected = this.writer.hashCode(); assertThat(this.response.getWriter().hashCode()).isEqualTo(expected); } @Test - public void printWriterCheckError() throws Exception { + void printWriterCheckError() throws Exception { boolean expected = true; given(this.writer.checkError()).willReturn(expected); @@ -77,7 +80,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void printWriterWriteInt() throws Exception { + void printWriterWriteInt() throws Exception { int expected = 1; this.response.getWriter().write(expected); @@ -86,7 +89,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void printWriterWriteCharIntInt() throws Exception { + void printWriterWriteCharIntInt() throws Exception { char[] buff = new char[0]; int off = 2; int len = 3; @@ -97,7 +100,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void printWriterWriteChar() throws Exception { + void printWriterWriteChar() throws Exception { char[] buff = new char[0]; this.response.getWriter().write(buff); @@ -106,7 +109,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void printWriterWriteStringIntInt() throws Exception { + void printWriterWriteStringIntInt() throws Exception { String s = ""; int off = 2; int len = 3; @@ -117,7 +120,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void printWriterWriteString() throws Exception { + void printWriterWriteString() throws Exception { String s = ""; this.response.getWriter().write(s); @@ -126,7 +129,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void printWriterPrintBoolean() throws Exception { + void printWriterPrintBoolean() throws Exception { boolean b = true; this.response.getWriter().print(b); @@ -135,7 +138,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void printWriterPrintChar() throws Exception { + void printWriterPrintChar() throws Exception { char c = 1; this.response.getWriter().print(c); @@ -144,7 +147,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void printWriterPrintInt() throws Exception { + void printWriterPrintInt() throws Exception { int i = 1; this.response.getWriter().print(i); @@ -153,7 +156,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void printWriterPrintLong() throws Exception { + void printWriterPrintLong() throws Exception { long l = 1; this.response.getWriter().print(l); @@ -162,7 +165,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void printWriterPrintFloat() throws Exception { + void printWriterPrintFloat() throws Exception { float f = 1; this.response.getWriter().print(f); @@ -171,7 +174,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void printWriterPrintDouble() throws Exception { + void printWriterPrintDouble() throws Exception { double x = 1; this.response.getWriter().print(x); @@ -180,7 +183,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void printWriterPrintCharArray() throws Exception { + void printWriterPrintCharArray() throws Exception { char[] x = new char[0]; this.response.getWriter().print(x); @@ -189,7 +192,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void printWriterPrintString() throws Exception { + void printWriterPrintString() throws Exception { String x = "1"; this.response.getWriter().print(x); @@ -198,7 +201,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void printWriterPrintObject() throws Exception { + void printWriterPrintObject() throws Exception { Object x = "1"; this.response.getWriter().print(x); @@ -207,14 +210,14 @@ public class OnCommittedResponseWrapperTests { } @Test - public void printWriterPrintln() throws Exception { + void printWriterPrintln() throws Exception { this.response.getWriter().println(); verify(this.writer).println(); } @Test - public void printWriterPrintlnBoolean() throws Exception { + void printWriterPrintlnBoolean() throws Exception { boolean b = true; this.response.getWriter().println(b); @@ -223,7 +226,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void printWriterPrintlnChar() throws Exception { + void printWriterPrintlnChar() throws Exception { char c = 1; this.response.getWriter().println(c); @@ -232,7 +235,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void printWriterPrintlnInt() throws Exception { + void printWriterPrintlnInt() throws Exception { int i = 1; this.response.getWriter().println(i); @@ -241,7 +244,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void printWriterPrintlnLong() throws Exception { + void printWriterPrintlnLong() throws Exception { long l = 1; this.response.getWriter().println(l); @@ -250,7 +253,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void printWriterPrintlnFloat() throws Exception { + void printWriterPrintlnFloat() throws Exception { float f = 1; this.response.getWriter().println(f); @@ -259,7 +262,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void printWriterPrintlnDouble() throws Exception { + void printWriterPrintlnDouble() throws Exception { double x = 1; this.response.getWriter().println(x); @@ -268,7 +271,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void printWriterPrintlnCharArray() throws Exception { + void printWriterPrintlnCharArray() throws Exception { char[] x = new char[0]; this.response.getWriter().println(x); @@ -277,7 +280,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void printWriterPrintlnString() throws Exception { + void printWriterPrintlnString() throws Exception { String x = "1"; this.response.getWriter().println(x); @@ -286,7 +289,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void printWriterPrintlnObject() throws Exception { + void printWriterPrintlnObject() throws Exception { Object x = "1"; this.response.getWriter().println(x); @@ -295,7 +298,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void printWriterPrintfStringObjectVargs() throws Exception { + void printWriterPrintfStringObjectVargs() throws Exception { String format = "format"; Object[] args = new Object[] { "1" }; @@ -305,7 +308,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void printWriterPrintfLocaleStringObjectVargs() throws Exception { + void printWriterPrintfLocaleStringObjectVargs() throws Exception { Locale l = Locale.US; String format = "format"; Object[] args = new Object[] { "1" }; @@ -316,7 +319,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void printWriterFormatStringObjectVargs() throws Exception { + void printWriterFormatStringObjectVargs() throws Exception { String format = "format"; Object[] args = new Object[] { "1" }; @@ -326,7 +329,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void printWriterFormatLocaleStringObjectVargs() throws Exception { + void printWriterFormatLocaleStringObjectVargs() throws Exception { Locale l = Locale.US; String format = "format"; Object[] args = new Object[] { "1" }; @@ -337,7 +340,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void printWriterAppendCharSequence() throws Exception { + void printWriterAppendCharSequence() throws Exception { String x = "a"; this.response.getWriter().append(x); @@ -346,7 +349,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void printWriterAppendCharSequenceIntInt() throws Exception { + void printWriterAppendCharSequenceIntInt() throws Exception { String x = "abcdef"; int start = 1; int end = 3; @@ -357,7 +360,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void printWriterAppendChar() throws Exception { + void printWriterAppendChar() throws Exception { char x = 1; this.response.getWriter().append(x); @@ -368,14 +371,14 @@ public class OnCommittedResponseWrapperTests { // servletoutputstream @Test - public void outputStreamHashCode() throws Exception { + void outputStreamHashCode() throws Exception { int expected = this.out.hashCode(); assertThat(this.response.getOutputStream().hashCode()).isEqualTo(expected); } @Test - public void outputStreamWriteInt() throws Exception { + void outputStreamWriteInt() throws Exception { int expected = 1; this.response.getOutputStream().write(expected); @@ -384,7 +387,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void outputStreamWriteByte() throws Exception { + void outputStreamWriteByte() throws Exception { byte[] expected = new byte[0]; this.response.getOutputStream().write(expected); @@ -393,7 +396,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void outputStreamWriteByteIntInt() throws Exception { + void outputStreamWriteByteIntInt() throws Exception { int start = 1; int end = 2; byte[] expected = new byte[0]; @@ -404,7 +407,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void outputStreamPrintBoolean() throws Exception { + void outputStreamPrintBoolean() throws Exception { boolean b = true; this.response.getOutputStream().print(b); @@ -413,7 +416,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void outputStreamPrintChar() throws Exception { + void outputStreamPrintChar() throws Exception { char c = 1; this.response.getOutputStream().print(c); @@ -422,7 +425,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void outputStreamPrintInt() throws Exception { + void outputStreamPrintInt() throws Exception { int i = 1; this.response.getOutputStream().print(i); @@ -431,7 +434,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void outputStreamPrintLong() throws Exception { + void outputStreamPrintLong() throws Exception { long l = 1; this.response.getOutputStream().print(l); @@ -440,7 +443,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void outputStreamPrintFloat() throws Exception { + void outputStreamPrintFloat() throws Exception { float f = 1; this.response.getOutputStream().print(f); @@ -449,7 +452,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void outputStreamPrintDouble() throws Exception { + void outputStreamPrintDouble() throws Exception { double x = 1; this.response.getOutputStream().print(x); @@ -458,7 +461,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void outputStreamPrintString() throws Exception { + void outputStreamPrintString() throws Exception { String x = "1"; this.response.getOutputStream().print(x); @@ -467,14 +470,14 @@ public class OnCommittedResponseWrapperTests { } @Test - public void outputStreamPrintln() throws Exception { + void outputStreamPrintln() throws Exception { this.response.getOutputStream().println(); verify(this.out).println(); } @Test - public void outputStreamPrintlnBoolean() throws Exception { + void outputStreamPrintlnBoolean() throws Exception { boolean b = true; this.response.getOutputStream().println(b); @@ -483,7 +486,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void outputStreamPrintlnChar() throws Exception { + void outputStreamPrintlnChar() throws Exception { char c = 1; this.response.getOutputStream().println(c); @@ -492,7 +495,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void outputStreamPrintlnInt() throws Exception { + void outputStreamPrintlnInt() throws Exception { int i = 1; this.response.getOutputStream().println(i); @@ -501,7 +504,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void outputStreamPrintlnLong() throws Exception { + void outputStreamPrintlnLong() throws Exception { long l = 1; this.response.getOutputStream().println(l); @@ -510,7 +513,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void outputStreamPrintlnFloat() throws Exception { + void outputStreamPrintlnFloat() throws Exception { float f = 1; this.response.getOutputStream().println(f); @@ -519,7 +522,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void outputStreamPrintlnDouble() throws Exception { + void outputStreamPrintlnDouble() throws Exception { double x = 1; this.response.getOutputStream().println(x); @@ -528,7 +531,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void outputStreamPrintlnString() throws Exception { + void outputStreamPrintlnString() throws Exception { String x = "1"; this.response.getOutputStream().println(x); @@ -540,7 +543,7 @@ public class OnCommittedResponseWrapperTests { // has been greater than zero and has been written to the response. @Test - public void contentLengthPrintWriterWriteIntCommits() throws Exception { + void contentLengthPrintWriterWriteIntCommits() throws Exception { int expected = 1; this.response.setContentLength(String.valueOf(expected).length()); @@ -550,7 +553,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthPrintWriterWriteIntMultiDigitCommits() throws Exception { + void contentLengthPrintWriterWriteIntMultiDigitCommits() throws Exception { int expected = 10000; this.response.setContentLength(String.valueOf(expected).length()); @@ -560,8 +563,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthPlus1PrintWriterWriteIntMultiDigitCommits() - throws Exception { + void contentLengthPlus1PrintWriterWriteIntMultiDigitCommits() throws Exception { int expected = 10000; this.response.setContentLength(String.valueOf(expected).length() + 1); @@ -575,7 +577,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthPrintWriterWriteCharIntIntCommits() throws Exception { + void contentLengthPrintWriterWriteCharIntIntCommits() throws Exception { char[] buff = new char[0]; int off = 2; int len = 3; @@ -587,7 +589,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthPrintWriterWriteCharCommits() throws Exception { + void contentLengthPrintWriterWriteCharCommits() throws Exception { char[] buff = new char[4]; this.response.setContentLength(buff.length); @@ -597,7 +599,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthPrintWriterWriteStringIntIntCommits() throws Exception { + void contentLengthPrintWriterWriteStringIntIntCommits() throws Exception { String s = ""; int off = 2; int len = 3; @@ -609,7 +611,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthPrintWriterWriteStringCommits() throws IOException { + void contentLengthPrintWriterWriteStringCommits() throws IOException { String body = "something"; this.response.setContentLength(body.length()); @@ -619,7 +621,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void printWriterWriteStringContentLengthCommits() throws IOException { + void printWriterWriteStringContentLengthCommits() throws IOException { String body = "something"; this.response.getWriter().write(body); @@ -629,7 +631,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void printWriterWriteStringDoesNotCommit() throws IOException { + void printWriterWriteStringDoesNotCommit() throws IOException { String body = "something"; this.response.getWriter().write(body); @@ -638,7 +640,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthPrintWriterPrintBooleanCommits() throws Exception { + void contentLengthPrintWriterPrintBooleanCommits() throws Exception { boolean b = true; this.response.setContentLength(1); @@ -648,7 +650,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthPrintWriterPrintCharCommits() throws Exception { + void contentLengthPrintWriterPrintCharCommits() throws Exception { char c = 1; this.response.setContentLength(1); @@ -658,7 +660,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthPrintWriterPrintIntCommits() throws Exception { + void contentLengthPrintWriterPrintIntCommits() throws Exception { int i = 1234; this.response.setContentLength(String.valueOf(i).length()); @@ -668,7 +670,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthPrintWriterPrintLongCommits() throws Exception { + void contentLengthPrintWriterPrintLongCommits() throws Exception { long l = 12345; this.response.setContentLength(String.valueOf(l).length()); @@ -678,7 +680,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthPrintWriterPrintFloatCommits() throws Exception { + void contentLengthPrintWriterPrintFloatCommits() throws Exception { float f = 12345; this.response.setContentLength(String.valueOf(f).length()); @@ -688,7 +690,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthPrintWriterPrintDoubleCommits() throws Exception { + void contentLengthPrintWriterPrintDoubleCommits() throws Exception { double x = 1.2345; this.response.setContentLength(String.valueOf(x).length()); @@ -698,7 +700,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthPrintWriterPrintCharArrayCommits() throws Exception { + void contentLengthPrintWriterPrintCharArrayCommits() throws Exception { char[] x = new char[10]; this.response.setContentLength(x.length); @@ -708,7 +710,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthPrintWriterPrintStringCommits() throws Exception { + void contentLengthPrintWriterPrintStringCommits() throws Exception { String x = "12345"; this.response.setContentLength(x.length()); @@ -718,7 +720,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthPrintWriterPrintObjectCommits() throws Exception { + void contentLengthPrintWriterPrintObjectCommits() throws Exception { Object x = "12345"; this.response.setContentLength(String.valueOf(x).length()); @@ -728,7 +730,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthPrintWriterPrintlnCommits() throws Exception { + void contentLengthPrintWriterPrintlnCommits() throws Exception { this.response.setContentLength(NL.length()); this.response.getWriter().println(); @@ -737,7 +739,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthPrintWriterPrintlnBooleanCommits() throws Exception { + void contentLengthPrintWriterPrintlnBooleanCommits() throws Exception { boolean b = true; this.response.setContentLength(1); @@ -747,7 +749,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthPrintWriterPrintlnCharCommits() throws Exception { + void contentLengthPrintWriterPrintlnCharCommits() throws Exception { char c = 1; this.response.setContentLength(1); @@ -757,7 +759,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthPrintWriterPrintlnIntCommits() throws Exception { + void contentLengthPrintWriterPrintlnIntCommits() throws Exception { int i = 12345; this.response.setContentLength(String.valueOf(i).length()); @@ -767,7 +769,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthPrintWriterPrintlnLongCommits() throws Exception { + void contentLengthPrintWriterPrintlnLongCommits() throws Exception { long l = 12345678; this.response.setContentLength(String.valueOf(l).length()); @@ -777,7 +779,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthPrintWriterPrintlnFloatCommits() throws Exception { + void contentLengthPrintWriterPrintlnFloatCommits() throws Exception { float f = 1234; this.response.setContentLength(String.valueOf(f).length()); @@ -787,7 +789,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthPrintWriterPrintlnDoubleCommits() throws Exception { + void contentLengthPrintWriterPrintlnDoubleCommits() throws Exception { double x = 1; this.response.setContentLength(String.valueOf(x).length()); @@ -797,7 +799,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthPrintWriterPrintlnCharArrayCommits() throws Exception { + void contentLengthPrintWriterPrintlnCharArrayCommits() throws Exception { char[] x = new char[20]; this.response.setContentLength(x.length); @@ -807,7 +809,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthPrintWriterPrintlnStringCommits() throws Exception { + void contentLengthPrintWriterPrintlnStringCommits() throws Exception { String x = "1"; this.response.setContentLength(String.valueOf(x).length()); @@ -817,7 +819,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthPrintWriterPrintlnObjectCommits() throws Exception { + void contentLengthPrintWriterPrintlnObjectCommits() throws Exception { Object x = "1"; this.response.setContentLength(String.valueOf(x).length()); @@ -827,7 +829,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthPrintWriterAppendCharSequenceCommits() throws Exception { + void contentLengthPrintWriterAppendCharSequenceCommits() throws Exception { String x = "a"; this.response.setContentLength(String.valueOf(x).length()); @@ -837,8 +839,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthPrintWriterAppendCharSequenceIntIntCommits() - throws Exception { + void contentLengthPrintWriterAppendCharSequenceIntIntCommits() throws Exception { String x = "abcdef"; int start = 1; int end = 3; @@ -850,7 +851,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthPrintWriterAppendCharCommits() throws Exception { + void contentLengthPrintWriterAppendCharCommits() throws Exception { char x = 1; this.response.setContentLength(1); @@ -860,7 +861,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthOutputStreamWriteIntCommits() throws Exception { + void contentLengthOutputStreamWriteIntCommits() throws Exception { int expected = 1; this.response.setContentLength(String.valueOf(expected).length()); @@ -870,7 +871,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthOutputStreamWriteIntMultiDigitCommits() throws Exception { + void contentLengthOutputStreamWriteIntMultiDigitCommits() throws Exception { int expected = 10000; this.response.setContentLength(String.valueOf(expected).length()); @@ -880,8 +881,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthPlus1OutputStreamWriteIntMultiDigitCommits() - throws Exception { + void contentLengthPlus1OutputStreamWriteIntMultiDigitCommits() throws Exception { int expected = 10000; this.response.setContentLength(String.valueOf(expected).length() + 1); @@ -896,11 +896,10 @@ public class OnCommittedResponseWrapperTests { // gh-171 @Test - public void contentLengthPlus1OutputStreamWriteByteArrayMultiDigitCommits() - throws Exception { + void contentLengthPlus1OutputStreamWriteByteArrayMultiDigitCommits() throws Exception { String expected = "{\n" + " \"parameterName\" : \"_csrf\",\n" - + " \"token\" : \"06300b65-c4aa-4c8f-8cda-39ee17f545a0\",\n" - + " \"headerName\" : \"X-CSRF-TOKEN\"\n" + "}"; + + " \"token\" : \"06300b65-c4aa-4c8f-8cda-39ee17f545a0\",\n" + " \"headerName\" : \"X-CSRF-TOKEN\"\n" + + "}"; this.response.setContentLength(expected.length() + 1); this.response.getOutputStream().write(expected.getBytes()); @@ -913,7 +912,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthOutputStreamPrintBooleanCommits() throws Exception { + void contentLengthOutputStreamPrintBooleanCommits() throws Exception { boolean b = true; this.response.setContentLength(1); @@ -923,7 +922,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthOutputStreamPrintCharCommits() throws Exception { + void contentLengthOutputStreamPrintCharCommits() throws Exception { char c = 1; this.response.setContentLength(1); @@ -933,7 +932,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthOutputStreamPrintIntCommits() throws Exception { + void contentLengthOutputStreamPrintIntCommits() throws Exception { int i = 1234; this.response.setContentLength(String.valueOf(i).length()); @@ -943,7 +942,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthOutputStreamPrintLongCommits() throws Exception { + void contentLengthOutputStreamPrintLongCommits() throws Exception { long l = 12345; this.response.setContentLength(String.valueOf(l).length()); @@ -953,7 +952,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthOutputStreamPrintFloatCommits() throws Exception { + void contentLengthOutputStreamPrintFloatCommits() throws Exception { float f = 12345; this.response.setContentLength(String.valueOf(f).length()); @@ -963,7 +962,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthOutputStreamPrintDoubleCommits() throws Exception { + void contentLengthOutputStreamPrintDoubleCommits() throws Exception { double x = 1.2345; this.response.setContentLength(String.valueOf(x).length()); @@ -973,7 +972,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthOutputStreamPrintStringCommits() throws Exception { + void contentLengthOutputStreamPrintStringCommits() throws Exception { String x = "12345"; this.response.setContentLength(x.length()); @@ -983,7 +982,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthOutputStreamPrintlnCommits() throws Exception { + void contentLengthOutputStreamPrintlnCommits() throws Exception { this.response.setContentLength(NL.length()); this.response.getOutputStream().println(); @@ -992,7 +991,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthOutputStreamPrintlnBooleanCommits() throws Exception { + void contentLengthOutputStreamPrintlnBooleanCommits() throws Exception { boolean b = true; this.response.setContentLength(1); @@ -1002,7 +1001,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthOutputStreamPrintlnCharCommits() throws Exception { + void contentLengthOutputStreamPrintlnCharCommits() throws Exception { char c = 1; this.response.setContentLength(1); @@ -1012,7 +1011,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthOutputStreamPrintlnIntCommits() throws Exception { + void contentLengthOutputStreamPrintlnIntCommits() throws Exception { int i = 12345; this.response.setContentLength(String.valueOf(i).length()); @@ -1022,7 +1021,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthOutputStreamPrintlnLongCommits() throws Exception { + void contentLengthOutputStreamPrintlnLongCommits() throws Exception { long l = 12345678; this.response.setContentLength(String.valueOf(l).length()); @@ -1032,7 +1031,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthOutputStreamPrintlnFloatCommits() throws Exception { + void contentLengthOutputStreamPrintlnFloatCommits() throws Exception { float f = 1234; this.response.setContentLength(String.valueOf(f).length()); @@ -1042,7 +1041,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthOutputStreamPrintlnDoubleCommits() throws Exception { + void contentLengthOutputStreamPrintlnDoubleCommits() throws Exception { double x = 1; this.response.setContentLength(String.valueOf(x).length()); @@ -1052,7 +1051,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthOutputStreamPrintlnStringCommits() throws Exception { + void contentLengthOutputStreamPrintlnStringCommits() throws Exception { String x = "1"; this.response.setContentLength(String.valueOf(x).length()); @@ -1062,7 +1061,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthDoesNotCommit() throws IOException { + void contentLengthDoesNotCommit() throws IOException { String body = "something"; this.response.setContentLength(body.length()); @@ -1071,7 +1070,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void contentLengthOutputStreamWriteStringCommits() throws IOException { + void contentLengthOutputStreamWriteStringCommits() throws IOException { String body = "something"; this.response.setContentLength(body.length()); @@ -1081,10 +1080,9 @@ public class OnCommittedResponseWrapperTests { } @Test - public void addHeaderContentLengthPrintWriterWriteStringCommits() throws Exception { + void addHeaderContentLengthPrintWriterWriteStringCommits() throws Exception { int expected = 1234; - this.response.addHeader("Content-Length", - String.valueOf(String.valueOf(expected).length())); + this.response.addHeader("Content-Length", String.valueOf(String.valueOf(expected).length())); this.response.getWriter().write(expected); @@ -1092,7 +1090,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void bufferSizePrintWriterWriteCommits() throws Exception { + void bufferSizePrintWriterWriteCommits() throws Exception { String expected = "1234567890"; given(this.response.getBufferSize()).willReturn(expected.length()); @@ -1102,7 +1100,7 @@ public class OnCommittedResponseWrapperTests { } @Test - public void bufferSizeCommitsOnce() throws Exception { + void bufferSizeCommitsOnce() throws Exception { String expected = "1234567890"; given(this.response.getBufferSize()).willReturn(expected.length()); @@ -1116,4 +1114,5 @@ public class OnCommittedResponseWrapperTests { assertThat(this.committed).isFalse(); } + } diff --git a/spring-session-core/src/test/java/org/springframework/session/web/http/OncePerRequestFilterTests.java b/spring-session-core/src/test/java/org/springframework/session/web/http/OncePerRequestFilterTests.java index 791cd10d..c486eea2 100644 --- a/spring-session-core/src/test/java/org/springframework/session/web/http/OncePerRequestFilterTests.java +++ b/spring-session-core/src/test/java/org/springframework/session/web/http/OncePerRequestFilterTests.java @@ -35,18 +35,23 @@ import org.springframework.mock.web.MockHttpServletResponse; import static org.assertj.core.api.Assertions.assertThat; -public class OncePerRequestFilterTests { +class OncePerRequestFilterTests { + private MockHttpServletRequest request; + private MockHttpServletResponse response; + private MockFilterChain chain; + private OncePerRequestFilter filter; + private HttpServlet servlet; private List invocations; @BeforeEach @SuppressWarnings("serial") - public void setup() { + void setup() { this.servlet = new HttpServlet() { }; this.request = new MockHttpServletRequest(); @@ -55,9 +60,8 @@ public class OncePerRequestFilterTests { this.invocations = new ArrayList<>(); this.filter = new OncePerRequestFilter() { @Override - protected void doFilterInternal(HttpServletRequest request, - HttpServletResponse response, FilterChain filterChain) - throws ServletException, IOException { + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, + FilterChain filterChain) throws ServletException, IOException { OncePerRequestFilterTests.this.invocations.add(this); filterChain.doFilter(request, response); } @@ -65,34 +69,32 @@ public class OncePerRequestFilterTests { } @Test - public void doFilterOnce() throws ServletException, IOException { + void doFilterOnce() throws ServletException, IOException { this.filter.doFilter(this.request, this.response, this.chain); assertThat(this.invocations).containsOnly(this.filter); } @Test - public void doFilterMultiOnlyIvokesOnce() throws ServletException, IOException { - this.filter.doFilter(this.request, this.response, - new MockFilterChain(this.servlet, this.filter)); + void doFilterMultiOnlyIvokesOnce() throws ServletException, IOException { + this.filter.doFilter(this.request, this.response, new MockFilterChain(this.servlet, this.filter)); assertThat(this.invocations).containsOnly(this.filter); } @Test - public void doFilterOtherSubclassInvoked() throws ServletException, IOException { + void doFilterOtherSubclassInvoked() throws ServletException, IOException { OncePerRequestFilter filter2 = new OncePerRequestFilter() { @Override - protected void doFilterInternal(HttpServletRequest request, - HttpServletResponse response, FilterChain filterChain) - throws ServletException, IOException { + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, + FilterChain filterChain) throws ServletException, IOException { OncePerRequestFilterTests.this.invocations.add(this); filterChain.doFilter(request, response); } }; - this.filter.doFilter(this.request, this.response, - new MockFilterChain(this.servlet, filter2)); + this.filter.doFilter(this.request, this.response, new MockFilterChain(this.servlet, filter2)); assertThat(this.invocations).containsOnly(this.filter, filter2); } + } diff --git a/spring-session-core/src/test/java/org/springframework/session/web/http/SessionEventHttpSessionListenerAdapterTests.java b/spring-session-core/src/test/java/org/springframework/session/web/http/SessionEventHttpSessionListenerAdapterTests.java index 39b648c3..7a2be0ca 100644 --- a/spring-session-core/src/test/java/org/springframework/session/web/http/SessionEventHttpSessionListenerAdapterTests.java +++ b/spring-session-core/src/test/java/org/springframework/session/web/http/SessionEventHttpSessionListenerAdapterTests.java @@ -47,7 +47,7 @@ import static org.mockito.Mockito.verifyZeroInteractions; * @author Rob Winch * @since 1.1 */ -public class SessionEventHttpSessionListenerAdapterTests { +class SessionEventHttpSessionListenerAdapterTests { @Mock private HttpSessionListener listener1; @@ -68,10 +68,9 @@ public class SessionEventHttpSessionListenerAdapterTests { private SessionEventHttpSessionListenerAdapter listener; @BeforeEach - public void setup() { + void setup() { MockitoAnnotations.initMocks(this); - this.listener = new SessionEventHttpSessionListenerAdapter( - Arrays.asList(this.listener1, this.listener2)); + this.listener = new SessionEventHttpSessionListenerAdapter(Arrays.asList(this.listener1, this.listener2)); this.listener.setServletContext(new MockServletContext()); Session session = new MapSession(); @@ -83,7 +82,7 @@ public class SessionEventHttpSessionListenerAdapterTests { // make configuration easier (i.e. autowire all HttpSessionListeners and might get // none) @Test - public void constructorEmptyWorks() { + void constructorEmptyWorks() { new SessionEventHttpSessionListenerAdapter(Collections.emptyList()); } @@ -92,9 +91,8 @@ public class SessionEventHttpSessionListenerAdapterTests { * listeners */ @Test - public void onApplicationEventEmptyListenersDoesNotUseEvent() { - this.listener = new SessionEventHttpSessionListenerAdapter( - Collections.emptyList()); + void onApplicationEventEmptyListenersDoesNotUseEvent() { + this.listener = new SessionEventHttpSessionListenerAdapter(Collections.emptyList()); this.destroyed = mock(SessionDestroyedEvent.class); this.listener.onApplicationEvent(this.destroyed); @@ -103,25 +101,23 @@ public class SessionEventHttpSessionListenerAdapterTests { } @Test - public void onApplicationEventDestroyed() { + void onApplicationEventDestroyed() { this.listener.onApplicationEvent(this.destroyed); verify(this.listener1).sessionDestroyed(this.sessionEvent.capture()); verify(this.listener2).sessionDestroyed(this.sessionEvent.capture()); - assertThat(this.sessionEvent.getValue().getSession().getId()) - .isEqualTo(this.destroyed.getSessionId()); + assertThat(this.sessionEvent.getValue().getSession().getId()).isEqualTo(this.destroyed.getSessionId()); } @Test - public void onApplicationEventCreated() { + void onApplicationEventCreated() { this.listener.onApplicationEvent(this.created); verify(this.listener1).sessionCreated(this.sessionEvent.capture()); verify(this.listener2).sessionCreated(this.sessionEvent.capture()); - assertThat(this.sessionEvent.getValue().getSession().getId()) - .isEqualTo(this.created.getSessionId()); + assertThat(this.sessionEvent.getValue().getSession().getId()).isEqualTo(this.created.getSessionId()); } } diff --git a/spring-session-core/src/test/java/org/springframework/session/web/http/SessionRepositoryFilterTests.java b/spring-session-core/src/test/java/org/springframework/session/web/http/SessionRepositoryFilterTests.java index f891f886..7237bf26 100644 --- a/spring-session-core/src/test/java/org/springframework/session/web/http/SessionRepositoryFilterTests.java +++ b/spring-session-core/src/test/java/org/springframework/session/web/http/SessionRepositoryFilterTests.java @@ -78,7 +78,7 @@ import static org.mockito.Mockito.verifyZeroInteractions; * Tests for {@link SessionRepositoryFilter}. */ @SuppressWarnings("deprecation") -public class SessionRepositoryFilterTests { +class SessionRepositoryFilterTests { @Mock private HttpSessionIdResolver strategy; @@ -96,7 +96,7 @@ public class SessionRepositoryFilterTests { private MockFilterChain chain; @BeforeEach - public void setup() throws Exception { + void setup() throws Exception { MockitoAnnotations.initMocks(this); this.sessions = new HashMap<>(); this.sessionRepository = new MapSessionRepository(this.sessions); @@ -105,7 +105,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterCreateDate() throws Exception { + void doFilterCreateDate() throws Exception { final String CREATE_ATTR = "create"; doFilter(new DoInFilter() { @Override @@ -113,8 +113,7 @@ public class SessionRepositoryFilterTests { long creationTime = wrappedRequest.getSession().getCreationTime(); long now = System.currentTimeMillis(); assertThat(now - creationTime).isGreaterThanOrEqualTo(0).isLessThan(5000); - SessionRepositoryFilterTests.this.request.setAttribute(CREATE_ATTR, - creationTime); + SessionRepositoryFilterTests.this.request.setAttribute(CREATE_ATTR, creationTime); } }); @@ -133,7 +132,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterCreateSetsLastAccessedTime() throws Exception { + void doFilterCreateSetsLastAccessedTime() throws Exception { MapSession session = new MapSession(); session.setLastAccessedTime(Instant.EPOCH); this.sessionRepository = spy(this.sessionRepository); @@ -147,23 +146,20 @@ public class SessionRepositoryFilterTests { long now = System.currentTimeMillis(); long fiveSecondsAgo = now - TimeUnit.SECONDS.toMillis(5); assertThat(session.getLastAccessedTime()).isLessThanOrEqualTo(now); - assertThat(session.getLastAccessedTime()) - .isGreaterThanOrEqualTo(fiveSecondsAgo); + assertThat(session.getLastAccessedTime()).isGreaterThanOrEqualTo(fiveSecondsAgo); } }); } @Test - public void doFilterLastAccessedTime() throws Exception { + void doFilterLastAccessedTime() throws Exception { final String ACCESS_ATTR = "create"; doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { long lastAccessed = wrappedRequest.getSession().getLastAccessedTime(); - assertThat(lastAccessed).isCloseTo( - wrappedRequest.getSession().getCreationTime(), Offset.offset(5L)); - SessionRepositoryFilterTests.this.request.setAttribute(ACCESS_ATTR, - lastAccessed); + assertThat(lastAccessed).isCloseTo(wrappedRequest.getSession().getCreationTime(), Offset.offset(5L)); + SessionRepositoryFilterTests.this.request.setAttribute(ACCESS_ATTR, lastAccessed); } }); @@ -175,14 +171,13 @@ public class SessionRepositoryFilterTests { public void doFilter(HttpServletRequest wrappedRequest) { long lastAccessed = wrappedRequest.getSession().getLastAccessedTime(); - assertThat(lastAccessed) - .isGreaterThan(wrappedRequest.getSession().getCreationTime()); + assertThat(lastAccessed).isGreaterThan(wrappedRequest.getSession().getCreationTime()); } }); } @Test - public void doFilterId() throws Exception { + void doFilterId() throws Exception { final String ID_ATTR = "create"; doFilter(new DoInFilter() { @Override @@ -207,7 +202,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterIdChanges() throws Exception { + void doFilterIdChanges() throws Exception { final String ID_ATTR = "create"; doFilter(new DoInFilter() { @Override @@ -229,7 +224,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterServletContext() throws Exception { + void doFilterServletContext() throws Exception { doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { @@ -240,7 +235,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterMaxInactiveIntervalDefault() throws Exception { + void doFilterMaxInactiveIntervalDefault() throws Exception { doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { @@ -253,14 +248,13 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterMaxInactiveIntervalOverride() throws Exception { + void doFilterMaxInactiveIntervalOverride() throws Exception { final int interval = 600; doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { wrappedRequest.getSession().setMaxInactiveInterval(interval); - assertThat(wrappedRequest.getSession().getMaxInactiveInterval()) - .isEqualTo(interval); + assertThat(wrappedRequest.getSession().getMaxInactiveInterval()).isEqualTo(interval); } }); @@ -269,25 +263,21 @@ public class SessionRepositoryFilterTests { doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { - assertThat(wrappedRequest.getSession().getMaxInactiveInterval()) - .isEqualTo(interval); + assertThat(wrappedRequest.getSession().getMaxInactiveInterval()).isEqualTo(interval); } }); } @Test - public void doFilterAttribute() throws Exception { + void doFilterAttribute() throws Exception { final String ATTR = "ATTR"; final String VALUE = "VALUE"; doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { wrappedRequest.getSession().setAttribute(ATTR, VALUE); - assertThat(wrappedRequest.getSession().getAttribute(ATTR)) - .isEqualTo(VALUE); - assertThat( - Collections.list(wrappedRequest.getSession().getAttributeNames())) - .containsOnly(ATTR); + assertThat(wrappedRequest.getSession().getAttribute(ATTR)).isEqualTo(VALUE); + assertThat(Collections.list(wrappedRequest.getSession().getAttributeNames())).containsOnly(ATTR); } }); @@ -296,11 +286,8 @@ public class SessionRepositoryFilterTests { doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { - assertThat(wrappedRequest.getSession().getAttribute(ATTR)) - .isEqualTo(VALUE); - assertThat( - Collections.list(wrappedRequest.getSession().getAttributeNames())) - .containsOnly(ATTR); + assertThat(wrappedRequest.getSession().getAttribute(ATTR)).isEqualTo(VALUE); + assertThat(Collections.list(wrappedRequest.getSession().getAttributeNames())).containsOnly(ATTR); } }); @@ -309,8 +296,7 @@ public class SessionRepositoryFilterTests { doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { - assertThat(wrappedRequest.getSession().getAttribute(ATTR)) - .isEqualTo(VALUE); + assertThat(wrappedRequest.getSession().getAttribute(ATTR)).isEqualTo(VALUE); wrappedRequest.getSession().removeAttribute(ATTR); @@ -329,7 +315,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterValue() throws Exception { + void doFilterValue() throws Exception { final String ATTR = "ATTR"; final String VALUE = "VALUE"; doFilter(new DoInFilter() { @@ -337,8 +323,7 @@ public class SessionRepositoryFilterTests { public void doFilter(HttpServletRequest wrappedRequest) { wrappedRequest.getSession().putValue(ATTR, VALUE); assertThat(wrappedRequest.getSession().getValue(ATTR)).isEqualTo(VALUE); - assertThat(Arrays.asList(wrappedRequest.getSession().getValueNames())) - .containsOnly(ATTR); + assertThat(Arrays.asList(wrappedRequest.getSession().getValueNames())).containsOnly(ATTR); } }); @@ -348,8 +333,7 @@ public class SessionRepositoryFilterTests { @Override public void doFilter(HttpServletRequest wrappedRequest) { assertThat(wrappedRequest.getSession().getValue(ATTR)).isEqualTo(VALUE); - assertThat(Arrays.asList(wrappedRequest.getSession().getValueNames())) - .containsOnly(ATTR); + assertThat(Arrays.asList(wrappedRequest.getSession().getValueNames())).containsOnly(ATTR); } }); @@ -377,7 +361,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterIsNewTrue() throws Exception { + void doFilterIsNewTrue() throws Exception { doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { @@ -388,7 +372,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterIsNewFalse() throws Exception { + void doFilterIsNewFalse() throws Exception { doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { @@ -410,7 +394,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterSetsCookieIfChanged() throws Exception { + void doFilterSetsCookieIfChanged() throws Exception { this.sessionRepository = new MapSessionRepository(new ConcurrentHashMap<>()) { @Override public MapSession findById(String id) { @@ -440,7 +424,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterGetSessionNew() throws Exception { + void doFilterGetSessionNew() throws Exception { doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { @@ -452,7 +436,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterGetSessionTrueNew() throws Exception { + void doFilterGetSessionTrueNew() throws Exception { doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { @@ -464,7 +448,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterGetSessionFalseNew() throws Exception { + void doFilterGetSessionFalseNew() throws Exception { doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { @@ -476,7 +460,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterIsRequestedValidSessionTrue() throws Exception { + void doFilterIsRequestedValidSessionTrue() throws Exception { doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { @@ -497,7 +481,7 @@ public class SessionRepositoryFilterTests { // gh-152 @Test - public void doFilterChangeSessionId() throws Exception { + void doFilterChangeSessionId() throws Exception { final String ATTR = "ATTRIBUTE"; final String VALUE = "VALUE"; @@ -518,8 +502,7 @@ public class SessionRepositoryFilterTests { HttpSession originalSession = wrappedRequest.getSession(); assertThat(originalSession.getId()).isEqualTo(originalSessionId); - String changeSessionId = ReflectionTestUtils.invokeMethod(wrappedRequest, - "changeSessionId"); + String changeSessionId = ReflectionTestUtils.invokeMethod(wrappedRequest, "changeSessionId"); assertThat(changeSessionId).isNotEqualTo(originalSessionId); // gh-227 assertThat(originalSession.getId()).isEqualTo(changeSessionId); @@ -537,14 +520,13 @@ public class SessionRepositoryFilterTests { doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { - assertThat(wrappedRequest.getSession().getAttribute(ATTR)) - .isEqualTo(VALUE); + assertThat(wrappedRequest.getSession().getAttribute(ATTR)).isEqualTo(VALUE); } }); } @Test - public void doFilterChangeSessionIdNoSession() throws Exception { + void doFilterChangeSessionIdNoSession() throws Exception { // change the session id doFilter(new DoInFilter() { @Override @@ -561,7 +543,7 @@ public class SessionRepositoryFilterTests { // gh-142, gh-153 @Test - public void doFilterIsRequestedValidSessionFalseInvalidId() throws Exception { + void doFilterIsRequestedValidSessionFalseInvalidId() throws Exception { setSessionCookie("invalid"); this.request.setRequestedSessionIdValid(true); @@ -574,7 +556,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterIsRequestedValidSessionFalse() throws Exception { + void doFilterIsRequestedValidSessionFalse() throws Exception { this.request.setRequestedSessionIdValid(true); doFilter(new DoInFilter() { @@ -586,7 +568,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterGetSessionGetSessionFalse() throws Exception { + void doFilterGetSessionGetSessionFalse() throws Exception { doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { @@ -606,7 +588,7 @@ public class SessionRepositoryFilterTests { // gh-229 @Test - public void doFilterGetSessionGetSessionOnError() throws Exception { + void doFilterGetSessionGetSessionOnError() throws Exception { doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { @@ -627,7 +609,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterCookieSecuritySettings() throws Exception { + void doFilterCookieSecuritySettings() throws Exception { this.request.setSecure(true); doFilter(new DoInFilter() { @Override @@ -637,19 +619,16 @@ public class SessionRepositoryFilterTests { }); Cookie session = getSessionCookie(); - assertThat(session.isHttpOnly()).describedAs("Session Cookie should be HttpOnly") - .isTrue(); - assertThat(session.getSecure()) - .describedAs("Session Cookie should be marked as Secure").isTrue(); + assertThat(session.isHttpOnly()).describedAs("Session Cookie should be HttpOnly").isTrue(); + assertThat(session.getSecure()).describedAs("Session Cookie should be marked as Secure").isTrue(); } @Test - public void doFilterSessionContext() throws Exception { + void doFilterSessionContext() throws Exception { doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { - HttpSessionContext sessionContext = wrappedRequest.getSession() - .getSessionContext(); + HttpSessionContext sessionContext = wrappedRequest.getSession().getSessionContext(); assertThat(sessionContext).isNotNull(); assertThat(sessionContext.getSession("a")).isNull(); assertThat(sessionContext.getIds()).isNotNull(); @@ -668,7 +647,7 @@ public class SessionRepositoryFilterTests { // --- saving @Test - public void doFilterGetAttr() throws Exception { + void doFilterGetAttr() throws Exception { final String ATTR_NAME = "attr"; final String ATTR_VALUE = "value"; final String ATTR_NAME2 = "attr2"; @@ -689,10 +668,8 @@ public class SessionRepositoryFilterTests { doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { - assertThat(wrappedRequest.getSession().getAttribute(ATTR_NAME)) - .isEqualTo(ATTR_VALUE); - assertThat(wrappedRequest.getSession().getAttribute(ATTR_NAME2)) - .isEqualTo(ATTR_VALUE2); + assertThat(wrappedRequest.getSession().getAttribute(ATTR_NAME)).isEqualTo(ATTR_VALUE); + assertThat(wrappedRequest.getSession().getAttribute(ATTR_NAME2)).isEqualTo(ATTR_VALUE2); } }); } @@ -700,7 +677,7 @@ public class SessionRepositoryFilterTests { // --- invalidate @Test - public void doFilterInvalidateInvalidateIllegalState() throws Exception { + void doFilterInvalidateInvalidateIllegalState() throws Exception { doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { @@ -717,7 +694,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterInvalidateCreationTimeIllegalState() throws Exception { + void doFilterInvalidateCreationTimeIllegalState() throws Exception { doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { @@ -734,7 +711,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterInvalidateAttributeIllegalState() throws Exception { + void doFilterInvalidateAttributeIllegalState() throws Exception { doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { @@ -751,7 +728,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterInvalidateValueIllegalState() throws Exception { + void doFilterInvalidateValueIllegalState() throws Exception { doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { @@ -768,7 +745,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterInvalidateAttributeNamesIllegalState() throws Exception { + void doFilterInvalidateAttributeNamesIllegalState() throws Exception { doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { @@ -785,7 +762,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterInvalidateValueNamesIllegalState() throws Exception { + void doFilterInvalidateValueNamesIllegalState() throws Exception { doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { @@ -802,7 +779,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterInvalidateSetAttributeIllegalState() throws Exception { + void doFilterInvalidateSetAttributeIllegalState() throws Exception { doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { @@ -819,7 +796,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterInvalidatePutValueIllegalState() throws Exception { + void doFilterInvalidatePutValueIllegalState() throws Exception { doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { @@ -836,7 +813,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterInvalidateRemoveAttributeIllegalState() throws Exception { + void doFilterInvalidateRemoveAttributeIllegalState() throws Exception { doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { @@ -853,7 +830,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterInvalidateRemoveValueIllegalState() throws Exception { + void doFilterInvalidateRemoveValueIllegalState() throws Exception { doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { @@ -870,7 +847,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterInvalidateNewIllegalState() throws Exception { + void doFilterInvalidateNewIllegalState() throws Exception { doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { @@ -887,7 +864,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterInvalidateLastAccessedTimeIllegalState() throws Exception { + void doFilterInvalidateLastAccessedTimeIllegalState() throws Exception { doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { @@ -904,7 +881,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterInvalidateId() throws Exception { + void doFilterInvalidateId() throws Exception { doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { @@ -917,7 +894,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterInvalidateServletContext() throws Exception { + void doFilterInvalidateServletContext() throws Exception { doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { @@ -931,7 +908,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterInvalidateSessionContext() throws Exception { + void doFilterInvalidateSessionContext() throws Exception { doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { @@ -945,7 +922,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterInvalidateMaxInteractiveInterval() throws Exception { + void doFilterInvalidateMaxInteractiveInterval() throws Exception { doFilter(new DoInFilter() { @Override public void doFilter(HttpServletRequest wrappedRequest) { @@ -960,7 +937,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterInvalidateAndGetSession() throws Exception { + void doFilterInvalidateAndGetSession() throws Exception { final String ATTR_NAME = "attr"; final String ATTR_VALUE = "value"; final String ATTR_NAME2 = "attr2"; @@ -983,8 +960,7 @@ public class SessionRepositoryFilterTests { @Override public void doFilter(HttpServletRequest wrappedRequest) { assertThat(wrappedRequest.getSession().getAttribute(ATTR_NAME)).isNull(); - assertThat(wrappedRequest.getSession().getAttribute(ATTR_NAME2)) - .isEqualTo(ATTR_VALUE2); + assertThat(wrappedRequest.getSession().getAttribute(ATTR_NAME2)).isEqualTo(ATTR_VALUE2); } }); } @@ -992,7 +968,7 @@ public class SessionRepositoryFilterTests { // --- invalid session ids @Test - public void doFilterGetSessionInvalidSessionId() throws Exception { + void doFilterGetSessionInvalidSessionId() throws Exception { setSessionCookie("INVALID"); doFilter(new DoInFilter() { @Override @@ -1005,7 +981,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterGetSessionTrueInvalidSessionId() throws Exception { + void doFilterGetSessionTrueInvalidSessionId() throws Exception { setSessionCookie("INVALID"); doFilter(new DoInFilter() { @Override @@ -1018,7 +994,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterGetSessionFalseInvalidSessionId() throws Exception { + void doFilterGetSessionFalseInvalidSessionId() throws Exception { setSessionCookie("INVALID"); doFilter(new DoInFilter() { @Override @@ -1033,139 +1009,118 @@ public class SessionRepositoryFilterTests { // --- commit response saves immediately @Test - public void doFilterSendError() throws Exception { + void doFilterSendError() throws Exception { doFilter(new DoInFilter() { @Override - public void doFilter(HttpServletRequest wrappedRequest, - HttpServletResponse wrappedResponse) throws IOException { + public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) + throws IOException { String id = wrappedRequest.getSession().getId(); wrappedResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - assertThat( - SessionRepositoryFilterTests.this.sessionRepository.findById(id)) - .isNotNull(); + assertThat(SessionRepositoryFilterTests.this.sessionRepository.findById(id)).isNotNull(); } }); } @Test - public void doFilterSendErrorAndMessage() throws Exception { + void doFilterSendErrorAndMessage() throws Exception { doFilter(new DoInFilter() { @Override - public void doFilter(HttpServletRequest wrappedRequest, - HttpServletResponse wrappedResponse) throws IOException { + public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) + throws IOException { String id = wrappedRequest.getSession().getId(); - wrappedResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, - "Error"); - assertThat( - SessionRepositoryFilterTests.this.sessionRepository.findById(id)) - .isNotNull(); + wrappedResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error"); + assertThat(SessionRepositoryFilterTests.this.sessionRepository.findById(id)).isNotNull(); } }); } @Test - public void doFilterSendRedirect() throws Exception { + void doFilterSendRedirect() throws Exception { doFilter(new DoInFilter() { @Override - public void doFilter(HttpServletRequest wrappedRequest, - HttpServletResponse wrappedResponse) throws IOException { + public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) + throws IOException { String id = wrappedRequest.getSession().getId(); wrappedResponse.sendRedirect("/"); - assertThat( - SessionRepositoryFilterTests.this.sessionRepository.findById(id)) - .isNotNull(); + assertThat(SessionRepositoryFilterTests.this.sessionRepository.findById(id)).isNotNull(); } }); } @Test - public void doFilterFlushBuffer() throws Exception { + void doFilterFlushBuffer() throws Exception { doFilter(new DoInFilter() { @Override - public void doFilter(HttpServletRequest wrappedRequest, - HttpServletResponse wrappedResponse) throws IOException { + public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) + throws IOException { String id = wrappedRequest.getSession().getId(); wrappedResponse.flushBuffer(); - assertThat( - SessionRepositoryFilterTests.this.sessionRepository.findById(id)) - .isNotNull(); + assertThat(SessionRepositoryFilterTests.this.sessionRepository.findById(id)).isNotNull(); } }); } @Test - public void doFilterOutputFlush() throws Exception { + void doFilterOutputFlush() throws Exception { doFilter(new DoInFilter() { @Override - public void doFilter(HttpServletRequest wrappedRequest, - HttpServletResponse wrappedResponse) throws IOException { + public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) + throws IOException { String id = wrappedRequest.getSession().getId(); wrappedResponse.getOutputStream().flush(); - assertThat( - SessionRepositoryFilterTests.this.sessionRepository.findById(id)) - .isNotNull(); + assertThat(SessionRepositoryFilterTests.this.sessionRepository.findById(id)).isNotNull(); } }); } @Test - public void doFilterOutputClose() throws Exception { + void doFilterOutputClose() throws Exception { doFilter(new DoInFilter() { @Override - public void doFilter(HttpServletRequest wrappedRequest, - HttpServletResponse wrappedResponse) throws IOException { + public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) + throws IOException { String id = wrappedRequest.getSession().getId(); wrappedResponse.getOutputStream().close(); - assertThat( - SessionRepositoryFilterTests.this.sessionRepository.findById(id)) - .isNotNull(); + assertThat(SessionRepositoryFilterTests.this.sessionRepository.findById(id)).isNotNull(); } }); } @Test - public void doFilterWriterFlush() throws Exception { + void doFilterWriterFlush() throws Exception { doFilter(new DoInFilter() { @Override - public void doFilter(HttpServletRequest wrappedRequest, - HttpServletResponse wrappedResponse) throws IOException { + public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) + throws IOException { String id = wrappedRequest.getSession().getId(); wrappedResponse.getWriter().flush(); - assertThat( - SessionRepositoryFilterTests.this.sessionRepository.findById(id)) - .isNotNull(); + assertThat(SessionRepositoryFilterTests.this.sessionRepository.findById(id)).isNotNull(); } }); } @Test - public void doFilterWriterClose() throws Exception { + void doFilterWriterClose() throws Exception { doFilter(new DoInFilter() { @Override - public void doFilter(HttpServletRequest wrappedRequest, - HttpServletResponse wrappedResponse) throws IOException { + public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) + throws IOException { String id = wrappedRequest.getSession().getId(); wrappedResponse.getWriter().close(); - assertThat( - SessionRepositoryFilterTests.this.sessionRepository.findById(id)) - .isNotNull(); + assertThat(SessionRepositoryFilterTests.this.sessionRepository.findById(id)).isNotNull(); } }); } @Test // gh-1243 - public void doFilterInclude() throws Exception { + void doFilterInclude() throws Exception { doFilter(new DoInFilter() { @Override - public void doFilter(HttpServletRequest wrappedRequest, - HttpServletResponse wrappedResponse) + public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws IOException, ServletException { String id = wrappedRequest.getSession().getId(); - wrappedRequest.getRequestDispatcher("/").include(wrappedRequest, - wrappedResponse); - assertThat( - SessionRepositoryFilterTests.this.sessionRepository.findById(id)) - .isNotNull(); + wrappedRequest.getRequestDispatcher("/").include(wrappedRequest, wrappedResponse); + assertThat(SessionRepositoryFilterTests.this.sessionRepository.findById(id)).isNotNull(); } }); } @@ -1173,9 +1128,8 @@ public class SessionRepositoryFilterTests { // --- HttpSessionIdResolver @Test - public void doFilterAdapterGetRequestedSessionId() throws Exception { - SessionRepository sessionRepository = spy( - new MapSessionRepository(new ConcurrentHashMap<>())); + void doFilterAdapterGetRequestedSessionId() throws Exception { + SessionRepository sessionRepository = spy(new MapSessionRepository(new ConcurrentHashMap<>())); this.filter = new SessionRepositoryFilter<>(sessionRepository); this.filter.setHttpSessionIdResolver(this.strategy); @@ -1183,13 +1137,12 @@ public class SessionRepositoryFilterTests { given(this.strategy.resolveSessionIds(any(HttpServletRequest.class))) .willReturn(Collections.singletonList(expectedId)); - given(sessionRepository.findById(anyString())) - .willReturn(new MapSession(expectedId)); + given(sessionRepository.findById(anyString())).willReturn(new MapSession(expectedId)); doFilter(new DoInFilter() { @Override - public void doFilter(HttpServletRequest wrappedRequest, - HttpServletResponse wrappedResponse) throws IOException { + public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) + throws IOException { String actualId = wrappedRequest.getRequestedSessionId(); assertThat(actualId).isEqualTo(expectedId); } @@ -1197,9 +1150,8 @@ public class SessionRepositoryFilterTests { } @Test // gh-1229 - public void doFilterAdapterGetRequestedSessionIdForInvalidSession() throws Exception { - SessionRepository sessionRepository = new MapSessionRepository( - new HashMap<>()); + void doFilterAdapterGetRequestedSessionIdForInvalidSession() throws Exception { + SessionRepository sessionRepository = new MapSessionRepository(new HashMap<>()); this.filter = new SessionRepositoryFilter<>(sessionRepository); this.filter.setHttpSessionIdResolver(this.strategy); @@ -1211,8 +1163,7 @@ public class SessionRepositoryFilterTests { doFilter(new DoInFilter() { @Override - public void doFilter(HttpServletRequest wrappedRequest, - HttpServletResponse wrappedResponse) { + public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) { assertThat(wrappedRequest.getRequestedSessionId()).isEqualTo(expectedId); assertThat(wrappedRequest.isRequestedSessionIdValid()).isFalse(); } @@ -1220,96 +1171,89 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterAdapterOnNewSession() throws Exception { + void doFilterAdapterOnNewSession() throws Exception { this.filter.setHttpSessionIdResolver(this.strategy); doFilter(new DoInFilter() { @Override - public void doFilter(HttpServletRequest wrappedRequest, - HttpServletResponse wrappedResponse) throws IOException { + public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) + throws IOException { wrappedRequest.getSession(); } }); HttpServletRequest request = (HttpServletRequest) this.chain.getRequest(); Session session = this.sessionRepository.findById(request.getSession().getId()); - verify(this.strategy).setSessionId(any(HttpServletRequest.class), - any(HttpServletResponse.class), eq(session.getId())); + verify(this.strategy).setSessionId(any(HttpServletRequest.class), any(HttpServletResponse.class), + eq(session.getId())); } @Test - public void doFilterAdapterOnInvalidate() throws Exception { + void doFilterAdapterOnInvalidate() throws Exception { this.filter.setHttpSessionIdResolver(this.strategy); doFilter(new DoInFilter() { @Override - public void doFilter(HttpServletRequest wrappedRequest, - HttpServletResponse wrappedResponse) throws IOException { + public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) + throws IOException { wrappedRequest.getSession().getId(); } }); HttpServletRequest request = (HttpServletRequest) this.chain.getRequest(); String id = request.getSession().getId(); - given(this.strategy.resolveSessionIds(any(HttpServletRequest.class))) - .willReturn(Collections.singletonList(id)); + given(this.strategy.resolveSessionIds(any(HttpServletRequest.class))).willReturn(Collections.singletonList(id)); setupRequest(); doFilter(new DoInFilter() { @Override - public void doFilter(HttpServletRequest wrappedRequest, - HttpServletResponse wrappedResponse) throws IOException { + public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) + throws IOException { wrappedRequest.getSession().invalidate(); } }); - verify(this.strategy).expireSession(any(HttpServletRequest.class), - any(HttpServletResponse.class)); + verify(this.strategy).expireSession(any(HttpServletRequest.class), any(HttpServletResponse.class)); } // gh-188 @Test - public void doFilterRequestSessionNoRequestSessionDoesNotInvalidate() - throws Exception { + void doFilterRequestSessionNoRequestSessionDoesNotInvalidate() throws Exception { this.filter.setHttpSessionIdResolver(this.strategy); doFilter(new DoInFilter() { @Override - public void doFilter(HttpServletRequest wrappedRequest, - HttpServletResponse wrappedResponse) throws IOException { + public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) + throws IOException { wrappedRequest.getSession().getId(); } }); HttpServletRequest request = (HttpServletRequest) this.chain.getRequest(); String id = request.getSession().getId(); - given(this.strategy.resolveSessionIds(any(HttpServletRequest.class))) - .willReturn(Collections.singletonList(id)); + given(this.strategy.resolveSessionIds(any(HttpServletRequest.class))).willReturn(Collections.singletonList(id)); doFilter(new DoInFilter() { @Override - public void doFilter(HttpServletRequest wrappedRequest, - HttpServletResponse wrappedResponse) throws IOException { + public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) + throws IOException { } }); - verify(this.strategy, never()).expireSession(any(HttpServletRequest.class), - any(HttpServletResponse.class)); + verify(this.strategy, never()).expireSession(any(HttpServletRequest.class), any(HttpServletResponse.class)); } @Test @SuppressWarnings("unchecked") - public void doFilterRequestSessionNoRequestSessionNoSessionRepositoryInteractions() - throws Exception { - SessionRepository sessionRepository = spy( - new MapSessionRepository(new ConcurrentHashMap<>())); + void doFilterRequestSessionNoRequestSessionNoSessionRepositoryInteractions() throws Exception { + SessionRepository sessionRepository = spy(new MapSessionRepository(new ConcurrentHashMap<>())); this.filter = new SessionRepositoryFilter<>(sessionRepository); doFilter(new DoInFilter() { @Override - public void doFilter(HttpServletRequest wrappedRequest, - HttpServletResponse wrappedResponse) throws IOException { + public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) + throws IOException { wrappedRequest.getSession().getId(); } }); @@ -1319,8 +1263,8 @@ public class SessionRepositoryFilterTests { doFilter(new DoInFilter() { @Override - public void doFilter(HttpServletRequest wrappedRequest, - HttpServletResponse wrappedResponse) throws IOException { + public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) + throws IOException { } }); @@ -1328,16 +1272,15 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterLazySessionCreation() throws Exception { - SessionRepository sessionRepository = spy( - new MapSessionRepository(new ConcurrentHashMap<>())); + void doFilterLazySessionCreation() throws Exception { + SessionRepository sessionRepository = spy(new MapSessionRepository(new ConcurrentHashMap<>())); this.filter = new SessionRepositoryFilter<>(sessionRepository); doFilter(new DoInFilter() { @Override - public void doFilter(HttpServletRequest wrappedRequest, - HttpServletResponse wrappedResponse) throws IOException { + public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) + throws IOException { } }); @@ -1345,7 +1288,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterLazySessionUpdates() throws Exception { + void doFilterLazySessionUpdates() throws Exception { MapSession session = this.sessionRepository.createSession(); this.sessionRepository.save(session); SessionRepository sessionRepository = spy(this.sessionRepository); @@ -1355,8 +1298,8 @@ public class SessionRepositoryFilterTests { doFilter(new DoInFilter() { @Override - public void doFilter(HttpServletRequest wrappedRequest, - HttpServletResponse wrappedResponse) throws IOException { + public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) + throws IOException { } }); @@ -1364,7 +1307,7 @@ public class SessionRepositoryFilterTests { } @Test - public void doFilterSessionRetrievalIsCached() throws Exception { + void doFilterSessionRetrievalIsCached() throws Exception { MapSession session = this.sessionRepository.createSession(); this.sessionRepository.save(session); SessionRepository sessionRepository = spy(this.sessionRepository); @@ -1374,8 +1317,7 @@ public class SessionRepositoryFilterTests { doFilter(new DoInFilter() { @Override - public void doFilter(HttpServletRequest wrappedRequest, - HttpServletResponse wrappedResponse) { + public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) { wrappedRequest.getSession().invalidate(); wrappedRequest.getSession(); } @@ -1392,7 +1334,7 @@ public class SessionRepositoryFilterTests { // --- order @Test - public void order() { + void order() { assertThat(AnnotationAwareOrderComparator.INSTANCE.compare(this.filter, new SessionRepositoryFilterDefaultOrder())); } @@ -1400,21 +1342,20 @@ public class SessionRepositoryFilterTests { // We want the filter to work without any dependencies on Spring @Test @SuppressWarnings("unused") - public void doesNotImplementOrdered() { + void doesNotImplementOrdered() { assertThatExceptionOfType(ClassCastException.class).isThrownBy(() -> { Ordered o = (Ordered) this.filter; }); } @Test - public void setHttpSessionIdResolverNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.filter.setHttpSessionIdResolver(null)) + void setHttpSessionIdResolverNull() { + assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setHttpSessionIdResolver(null)) .withMessage("httpSessionIdResolver cannot be null"); } @Test - public void bindingListenerBindListener() throws Exception { + void bindingListenerBindListener() throws Exception { String bindingListenerName = "bindingListener"; CountingHttpSessionBindingListener bindingListener = new CountingHttpSessionBindingListener(); @@ -1432,7 +1373,7 @@ public class SessionRepositoryFilterTests { } @Test - public void bindingListenerBindListenerThenUnbind() throws Exception { + void bindingListenerBindListenerThenUnbind() throws Exception { String bindingListenerName = "bindingListener"; CountingHttpSessionBindingListener bindingListener = new CountingHttpSessionBindingListener(); @@ -1451,7 +1392,7 @@ public class SessionRepositoryFilterTests { } @Test - public void bindingListenerBindSameListenerTwice() throws Exception { + void bindingListenerBindSameListenerTwice() throws Exception { String bindingListenerName = "bindingListener"; CountingHttpSessionBindingListener bindingListener = new CountingHttpSessionBindingListener(); @@ -1470,7 +1411,7 @@ public class SessionRepositoryFilterTests { } @Test - public void bindingListenerBindListenerOverwrite() throws Exception { + void bindingListenerBindListenerOverwrite() throws Exception { String bindingListenerName = "bindingListener"; CountingHttpSessionBindingListener bindingListener1 = new CountingHttpSessionBindingListener(); CountingHttpSessionBindingListener bindingListener2 = new CountingHttpSessionBindingListener(); @@ -1491,7 +1432,7 @@ public class SessionRepositoryFilterTests { } @Test - public void bindingListenerBindThrowsException() throws Exception { + void bindingListenerBindThrowsException() throws Exception { String bindingListenerName = "bindingListener"; CountingHttpSessionBindingListener bindingListener = new CountingHttpSessionBindingListener(); @@ -1510,7 +1451,7 @@ public class SessionRepositoryFilterTests { } @Test - public void bindingListenerBindListenerThenUnbindThrowsException() throws Exception { + void bindingListenerBindListenerThenUnbindThrowsException() throws Exception { String bindingListenerName = "bindingListener"; CountingHttpSessionBindingListener bindingListener = new CountingHttpSessionBindingListener(); @@ -1536,23 +1477,18 @@ public class SessionRepositoryFilterTests { assertThat(cookie).isNotNull(); assertThat(cookie.getMaxAge()).isEqualTo(-1); assertThat(cookie.getValue()).isNotEqualTo("INVALID"); - assertThat(cookie.isHttpOnly()).describedAs("Cookie is expected to be HTTP Only") - .isTrue(); - assertThat(cookie.getSecure()) - .describedAs( - "Cookie secured is expected to be " + this.request.isSecure()) + assertThat(cookie.isHttpOnly()).describedAs("Cookie is expected to be HTTP Only").isTrue(); + assertThat(cookie.getSecure()).describedAs("Cookie secured is expected to be " + this.request.isSecure()) .isEqualTo(this.request.isSecure()); assertThat(this.request.getSession(false)) - .describedAs("The original HttpServletRequest HttpSession should be null") - .isNull(); + .describedAs("The original HttpServletRequest HttpSession should be null").isNull(); } private void assertNoSession() { Cookie cookie = getSessionCookie(); assertThat(cookie).isNull(); assertThat(this.request.getSession(false)) - .describedAs("The original HttpServletRequest HttpSession should be null") - .isNull(); + .describedAs("The original HttpServletRequest HttpSession should be null").isNull(); } private Cookie getSessionCookie() { @@ -1579,22 +1515,19 @@ public class SessionRepositoryFilterTests { for (Cookie cookie : this.response.getCookies()) { nameToCookie.put(cookie.getName(), cookie); } - Cookie[] nextRequestCookies = new ArrayList<>(nameToCookie.values()) - .toArray(new Cookie[0]); + Cookie[] nextRequestCookies = new ArrayList<>(nameToCookie.values()).toArray(new Cookie[0]); setupRequest(); this.request.setCookies(nextRequestCookies); } - private void doFilter(final DoInFilter doInFilter) - throws ServletException, IOException { + private void doFilter(final DoInFilter doInFilter) throws ServletException, IOException { this.chain = new MockFilterChain(new HttpServlet() { }, new OncePerRequestFilter() { @Override - protected void doFilterInternal(HttpServletRequest request, - HttpServletResponse response, FilterChain filterChain) - throws ServletException, IOException { + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, + FilterChain filterChain) throws ServletException, IOException { doInFilter.doFilter(request, response); } }); @@ -1620,8 +1553,7 @@ public class SessionRepositoryFilterTests { private abstract class DoInFilter { - void doFilter(HttpServletRequest wrappedRequest, - HttpServletResponse wrappedResponse) + void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) throws ServletException, IOException { doFilter(wrappedRequest); } @@ -1631,8 +1563,7 @@ public class SessionRepositoryFilterTests { } - private static class CountingHttpSessionBindingListener - implements HttpSessionBindingListener { + private static class CountingHttpSessionBindingListener implements HttpSessionBindingListener { private final AtomicInteger counter = new AtomicInteger(0); diff --git a/spring-session-core/src/test/java/org/springframework/session/web/server/session/SpringSessionWebSessionStoreTests.java b/spring-session-core/src/test/java/org/springframework/session/web/server/session/SpringSessionWebSessionStoreTests.java index a8aa5876..77073619 100644 --- a/spring-session-core/src/test/java/org/springframework/session/web/server/session/SpringSessionWebSessionStoreTests.java +++ b/spring-session-core/src/test/java/org/springframework/session/web/server/session/SpringSessionWebSessionStoreTests.java @@ -43,7 +43,7 @@ import static org.mockito.Mockito.verify; * @author Rob Winch * @author Vedran Pavic */ -public class SpringSessionWebSessionStoreTests { +class SpringSessionWebSessionStoreTests { @Mock private ReactiveSessionRepository sessionRepository; @@ -57,68 +57,62 @@ public class SpringSessionWebSessionStoreTests { private SpringSessionWebSessionStore webSessionStore; @BeforeEach - public void setup() { + void setup() { MockitoAnnotations.initMocks(this); this.webSessionStore = new SpringSessionWebSessionStore<>(this.sessionRepository); - given(this.sessionRepository.findById(any())) - .willReturn(Mono.just(this.findByIdSession)); - given(this.sessionRepository.createSession()) - .willReturn(Mono.just(this.createSession)); + given(this.sessionRepository.findById(any())).willReturn(Mono.just(this.findByIdSession)); + given(this.sessionRepository.createSession()).willReturn(Mono.just(this.createSession)); } @Test - public void constructorWhenNullRepositoryThenThrowsIllegalArgumentException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new SpringSessionWebSessionStore(null)) + void constructorWhenNullRepositoryThenThrowsIllegalArgumentException() { + assertThatIllegalArgumentException().isThrownBy(() -> new SpringSessionWebSessionStore(null)) .withMessage("reactiveSessionRepository cannot be null"); } @Test - public void createSessionWhenNoAttributesThenNotStarted() { + void createSessionWhenNoAttributesThenNotStarted() { WebSession createdWebSession = this.webSessionStore.createWebSession().block(); assertThat(createdWebSession.isStarted()).isFalse(); } @Test - public void createSessionWhenAddAttributeThenStarted() { - given(this.createSession.getAttributeNames()) - .willReturn(Collections.singleton("a")); + void createSessionWhenAddAttributeThenStarted() { + given(this.createSession.getAttributeNames()).willReturn(Collections.singleton("a")); WebSession createdWebSession = this.webSessionStore.createWebSession().block(); assertThat(createdWebSession.isStarted()).isTrue(); } @Test - public void createSessionWhenGetAttributesAndSizeThenDelegatesToCreateSession() { + void createSessionWhenGetAttributesAndSizeThenDelegatesToCreateSession() { WebSession createdWebSession = this.webSessionStore.createWebSession().block(); Map attributes = createdWebSession.getAttributes(); assertThat(attributes.size()).isEqualTo(0); - given(this.createSession.getAttributeNames()) - .willReturn(Collections.singleton("a")); + given(this.createSession.getAttributeNames()).willReturn(Collections.singleton("a")); assertThat(attributes.size()).isEqualTo(1); } @Test - public void createSessionWhenGetAttributesAndIsEmptyThenDelegatesToCreateSession() { + void createSessionWhenGetAttributesAndIsEmptyThenDelegatesToCreateSession() { WebSession createdWebSession = this.webSessionStore.createWebSession().block(); Map attributes = createdWebSession.getAttributes(); assertThat(attributes.isEmpty()).isTrue(); - given(this.createSession.getAttributeNames()) - .willReturn(Collections.singleton("a")); + given(this.createSession.getAttributeNames()).willReturn(Collections.singleton("a")); assertThat(attributes.isEmpty()).isFalse(); } @Test - public void createSessionWhenGetAttributesAndContainsKeyAndNotStringThenFalse() { + void createSessionWhenGetAttributesAndContainsKeyAndNotStringThenFalse() { WebSession createdWebSession = this.webSessionStore.createWebSession().block(); Map attributes = createdWebSession.getAttributes(); @@ -127,7 +121,7 @@ public class SpringSessionWebSessionStoreTests { } @Test - public void createSessionWhenGetAttributesAndContainsKeyAndNotFoundThenFalse() { + void createSessionWhenGetAttributesAndContainsKeyAndNotFoundThenFalse() { WebSession createdWebSession = this.webSessionStore.createWebSession().block(); Map attributes = createdWebSession.getAttributes(); @@ -136,9 +130,8 @@ public class SpringSessionWebSessionStoreTests { } @Test - public void createSessionWhenGetAttributesAndContainsKeyAndFoundThenTrue() { - given(this.createSession.getAttributeNames()) - .willReturn(Collections.singleton("a")); + void createSessionWhenGetAttributesAndContainsKeyAndFoundThenTrue() { + given(this.createSession.getAttributeNames()).willReturn(Collections.singleton("a")); WebSession createdWebSession = this.webSessionStore.createWebSession().block(); Map attributes = createdWebSession.getAttributes(); @@ -147,7 +140,7 @@ public class SpringSessionWebSessionStoreTests { } @Test - public void createSessionWhenGetAttributesAndPutThenDelegatesToCreateSession() { + void createSessionWhenGetAttributesAndPutThenDelegatesToCreateSession() { WebSession createdWebSession = this.webSessionStore.createWebSession().block(); Map attributes = createdWebSession.getAttributes(); @@ -157,7 +150,7 @@ public class SpringSessionWebSessionStoreTests { } @Test - public void createSessionWhenGetAttributesAndPutNullThenDelegatesToCreateSession() { + void createSessionWhenGetAttributesAndPutNullThenDelegatesToCreateSession() { WebSession createdWebSession = this.webSessionStore.createWebSession().block(); Map attributes = createdWebSession.getAttributes(); @@ -167,7 +160,7 @@ public class SpringSessionWebSessionStoreTests { } @Test - public void createSessionWhenGetAttributesAndRemoveThenDelegatesToCreateSession() { + void createSessionWhenGetAttributesAndRemoveThenDelegatesToCreateSession() { WebSession createdWebSession = this.webSessionStore.createWebSession().block(); Map attributes = createdWebSession.getAttributes(); @@ -177,7 +170,7 @@ public class SpringSessionWebSessionStoreTests { } @Test - public void createSessionWhenGetAttributesAndPutAllThenDelegatesToCreateSession() { + void createSessionWhenGetAttributesAndPutAllThenDelegatesToCreateSession() { WebSession createdWebSession = this.webSessionStore.createWebSession().block(); Map attributes = createdWebSession.getAttributes(); @@ -187,9 +180,8 @@ public class SpringSessionWebSessionStoreTests { } @Test - public void createSessionWhenGetAttributesAndClearThenDelegatesToCreateSession() { - given(this.createSession.getAttributeNames()) - .willReturn(Collections.singleton("a")); + void createSessionWhenGetAttributesAndClearThenDelegatesToCreateSession() { + given(this.createSession.getAttributeNames()).willReturn(Collections.singleton("a")); WebSession createdWebSession = this.webSessionStore.createWebSession().block(); Map attributes = createdWebSession.getAttributes(); @@ -199,9 +191,8 @@ public class SpringSessionWebSessionStoreTests { } @Test - public void createSessionWhenGetAttributesAndKeySetThenDelegatesToCreateSession() { - given(this.createSession.getAttributeNames()) - .willReturn(Collections.singleton("a")); + void createSessionWhenGetAttributesAndKeySetThenDelegatesToCreateSession() { + given(this.createSession.getAttributeNames()).willReturn(Collections.singleton("a")); WebSession createdWebSession = this.webSessionStore.createWebSession().block(); Map attributes = createdWebSession.getAttributes(); @@ -210,9 +201,8 @@ public class SpringSessionWebSessionStoreTests { } @Test - public void createSessionWhenGetAttributesAndValuesThenDelegatesToCreateSession() { - given(this.createSession.getAttributeNames()) - .willReturn(Collections.singleton("a")); + void createSessionWhenGetAttributesAndValuesThenDelegatesToCreateSession() { + given(this.createSession.getAttributeNames()).willReturn(Collections.singleton("a")); given(this.createSession.getAttribute("a")).willReturn("b"); WebSession createdWebSession = this.webSessionStore.createWebSession().block(); @@ -222,10 +212,9 @@ public class SpringSessionWebSessionStoreTests { } @Test - public void createSessionWhenGetAttributesAndEntrySetThenDelegatesToCreateSession() { + void createSessionWhenGetAttributesAndEntrySetThenDelegatesToCreateSession() { String attrName = "attrName"; - given(this.createSession.getAttributeNames()) - .willReturn(Collections.singleton(attrName)); + given(this.createSession.getAttributeNames()).willReturn(Collections.singleton(attrName)); String attrValue = "attrValue"; given(this.createSession.getAttribute(attrName)).willReturn(attrValue); WebSession createdWebSession = this.webSessionStore.createWebSession().block(); @@ -233,12 +222,11 @@ public class SpringSessionWebSessionStoreTests { Map attributes = createdWebSession.getAttributes(); Set> entries = attributes.entrySet(); - assertThat(entries) - .containsExactly(new AbstractMap.SimpleEntry<>(attrName, attrValue)); + assertThat(entries).containsExactly(new AbstractMap.SimpleEntry<>(attrName, attrValue)); } @Test - public void retrieveSessionThenStarted() { + void retrieveSessionThenStarted() { String id = "id"; WebSession retrievedWebSession = this.webSessionStore.retrieveSession(id).block(); @@ -247,7 +235,7 @@ public class SpringSessionWebSessionStoreTests { } @Test - public void removeSessionWhenInvokedThenSessionSaved() { + void removeSessionWhenInvokedThenSessionSaved() { String sessionId = "session-id"; given(this.sessionRepository.deleteById(sessionId)).willReturn(Mono.empty()); @@ -257,21 +245,20 @@ public class SpringSessionWebSessionStoreTests { } @Test - public void setClockWhenNullThenException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.webSessionStore.setClock(null)) + void setClockWhenNullThenException() { + assertThatIllegalArgumentException().isThrownBy(() -> this.webSessionStore.setClock(null)) .withMessage("clock cannot be null"); } @Test // gh-1114 - public void createSessionThenSessionIsNotExpired() { + void createSessionThenSessionIsNotExpired() { WebSession createdWebSession = this.webSessionStore.createWebSession().block(); assertThat(createdWebSession.isExpired()).isFalse(); } @Test // gh-1114 - public void invalidateSessionThenSessionIsExpired() { + void invalidateSessionThenSessionIsExpired() { WebSession createdWebSession = this.webSessionStore.createWebSession().block(); given(createdWebSession.invalidate()).willReturn(Mono.empty()); diff --git a/spring-session-core/src/test/java/org/springframework/session/web/socket/handler/WebSocketConnectHandlerDecoratorFactoryTests.java b/spring-session-core/src/test/java/org/springframework/session/web/socket/handler/WebSocketConnectHandlerDecoratorFactoryTests.java index 9cac3728..13e387a0 100644 --- a/spring-session-core/src/test/java/org/springframework/session/web/socket/handler/WebSocketConnectHandlerDecoratorFactoryTests.java +++ b/spring-session-core/src/test/java/org/springframework/session/web/socket/handler/WebSocketConnectHandlerDecoratorFactoryTests.java @@ -35,33 +35,36 @@ import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.any; import static org.mockito.Mockito.verify; -public class WebSocketConnectHandlerDecoratorFactoryTests { +class WebSocketConnectHandlerDecoratorFactoryTests { + @Mock ApplicationEventPublisher eventPublisher; + @Mock WebSocketHandler delegate; + @Mock WebSocketSession session; + @Captor ArgumentCaptor event; - WebSocketConnectHandlerDecoratorFactory factory; + private WebSocketConnectHandlerDecoratorFactory factory; @BeforeEach - public void setup() { + void setup() { MockitoAnnotations.initMocks(this); this.factory = new WebSocketConnectHandlerDecoratorFactory(this.eventPublisher); } @Test - public void constructorNullEventPublisher() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new WebSocketConnectHandlerDecoratorFactory(null)) + void constructorNullEventPublisher() { + assertThatIllegalArgumentException().isThrownBy(() -> new WebSocketConnectHandlerDecoratorFactory(null)) .withMessage("eventPublisher cannot be null"); } @Test - public void decorateAfterConnectionEstablished() throws Exception { + void decorateAfterConnectionEstablished() throws Exception { WebSocketHandler decorated = this.factory.decorate(this.delegate); decorated.afterConnectionEstablished(this.session); @@ -71,13 +74,14 @@ public class WebSocketConnectHandlerDecoratorFactoryTests { } @Test - public void decorateAfterConnectionEstablishedEventError() throws Exception { + void decorateAfterConnectionEstablishedEventError() throws Exception { WebSocketHandler decorated = this.factory.decorate(this.delegate); - willThrow(new IllegalStateException("Test throw on publishEvent")) - .given(this.eventPublisher).publishEvent(any(ApplicationEvent.class)); + willThrow(new IllegalStateException("Test throw on publishEvent")).given(this.eventPublisher) + .publishEvent(any(ApplicationEvent.class)); decorated.afterConnectionEstablished(this.session); verify(this.eventPublisher).publishEvent(any(SessionConnectEvent.class)); } + } diff --git a/spring-session-core/src/test/java/org/springframework/session/web/socket/handler/WebSocketRegistryListenerTests.java b/spring-session-core/src/test/java/org/springframework/session/web/socket/handler/WebSocketRegistryListenerTests.java index 8d0a8d5a..b15e0cb8 100644 --- a/spring-session-core/src/test/java/org/springframework/session/web/socket/handler/WebSocketRegistryListenerTests.java +++ b/spring-session-core/src/test/java/org/springframework/session/web/socket/handler/WebSocketRegistryListenerTests.java @@ -44,7 +44,7 @@ import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -public class WebSocketRegistryListenerTests { +class WebSocketRegistryListenerTests { @Mock private WebSocketSession wsSession; @@ -73,7 +73,7 @@ public class WebSocketRegistryListenerTests { private WebSocketRegistryListener listener; @BeforeEach - public void setup() { + void setup() { MockitoAnnotations.initMocks(this); String sessionId = "session-id"; MapSession session = new MapSession(sessionId); @@ -96,14 +96,14 @@ public class WebSocketRegistryListenerTests { this.listener = new WebSocketRegistryListener(); this.connect = new SessionConnectEvent(this.listener, this.wsSession); this.connect2 = new SessionConnectEvent(this.listener, this.wsSession2); - this.disconnect = new SessionDisconnectEvent(this.listener, this.message, - this.wsSession.getId(), CloseStatus.NORMAL); + this.disconnect = new SessionDisconnectEvent(this.listener, this.message, this.wsSession.getId(), + CloseStatus.NORMAL); this.deleted = new SessionDeletedEvent(this.listener, session); this.expired = new SessionExpiredEvent(this.listener, session); } @Test - public void onApplicationEventConnectSessionDeleted() throws Exception { + void onApplicationEventConnectSessionDeleted() throws Exception { this.listener.onApplicationEvent(this.connect); this.listener.onApplicationEvent(this.deleted); @@ -112,7 +112,7 @@ public class WebSocketRegistryListenerTests { } @Test - public void onApplicationEventConnectSessionExpired() throws Exception { + void onApplicationEventConnectSessionExpired() throws Exception { this.listener.onApplicationEvent(this.connect); this.listener.onApplicationEvent(this.expired); @@ -121,7 +121,7 @@ public class WebSocketRegistryListenerTests { } @Test - public void onApplicationEventConnectSessionDeletedNullPrincipal() throws Exception { + void onApplicationEventConnectSessionDeletedNullPrincipal() throws Exception { given(this.wsSession.getPrincipal()).willReturn(null); this.listener.onApplicationEvent(this.connect); @@ -131,7 +131,7 @@ public class WebSocketRegistryListenerTests { } @Test - public void onApplicationEventConnectDisconnect() throws Exception { + void onApplicationEventConnectDisconnect() throws Exception { this.listener.onApplicationEvent(this.connect); this.listener.onApplicationEvent(this.disconnect); @@ -143,7 +143,7 @@ public class WebSocketRegistryListenerTests { // gh-76 @Test @SuppressWarnings("unchecked") - public void onApplicationEventConnectDisconnectCleanup() { + void onApplicationEventConnectDisconnectCleanup() { this.listener.onApplicationEvent(this.connect); this.listener.onApplicationEvent(this.disconnect); @@ -154,7 +154,7 @@ public class WebSocketRegistryListenerTests { } @Test - public void onApplicationEventConnectDisconnectNullSession() throws Exception { + void onApplicationEventConnectDisconnectNullSession() throws Exception { this.listener.onApplicationEvent(this.connect); this.attributes.clear(); @@ -164,7 +164,7 @@ public class WebSocketRegistryListenerTests { } @Test - public void onApplicationEventConnectConnectDisonnect() throws Exception { + void onApplicationEventConnectConnectDisonnect() throws Exception { this.listener.onApplicationEvent(this.connect); this.listener.onApplicationEvent(this.connect2); this.listener.onApplicationEvent(this.disconnect); diff --git a/spring-session-core/src/test/java/org/springframework/session/web/socket/server/SessionRepositoryMessageInterceptorTests.java b/spring-session-core/src/test/java/org/springframework/session/web/socket/server/SessionRepositoryMessageInterceptorTests.java index 70b14d8b..cd530e4b 100644 --- a/spring-session-core/src/test/java/org/springframework/session/web/socket/server/SessionRepositoryMessageInterceptorTests.java +++ b/spring-session-core/src/test/java/org/springframework/session/web/socket/server/SessionRepositoryMessageInterceptorTests.java @@ -51,25 +51,27 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; -public class SessionRepositoryMessageInterceptorTests { +class SessionRepositoryMessageInterceptorTests { + @Mock SessionRepository sessionRepository; + @Mock MessageChannel channel; + @Mock Session session; - Message createMessage; + private Message createMessage; - SimpMessageHeaderAccessor headers; + private SimpMessageHeaderAccessor headers; - SessionRepositoryMessageInterceptor interceptor; + private SessionRepositoryMessageInterceptor interceptor; @BeforeEach - public void setup() { + void setup() { MockitoAnnotations.initMocks(this); - this.interceptor = new SessionRepositoryMessageInterceptor<>( - this.sessionRepository); + this.interceptor = new SessionRepositoryMessageInterceptor<>(this.sessionRepository); this.headers = SimpMessageHeaderAccessor.create(); this.headers.setSessionId("session"); this.headers.setSessionAttributes(new HashMap<>()); @@ -80,123 +82,112 @@ public class SessionRepositoryMessageInterceptorTests { } @Test - public void preSendconstructorNullRepository() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new SessionRepositoryMessageInterceptor<>(null)) + void preSendconstructorNullRepository() { + assertThatIllegalArgumentException().isThrownBy(() -> new SessionRepositoryMessageInterceptor<>(null)) .withMessage("sessionRepository cannot be null"); } @Test - public void preSendNullMessage() { + void preSendNullMessage() { assertThat(this.interceptor.preSend(null, this.channel)).isNull(); } @Test - public void preSendConnectAckDoesNotInvokeSessionRepository() { + void preSendConnectAckDoesNotInvokeSessionRepository() { setMessageType(SimpMessageType.CONNECT_ACK); - assertThat(this.interceptor.preSend(createMessage(), this.channel)) - .isSameAs(this.createMessage); + assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage); verifyZeroInteractions(this.sessionRepository); } @Test - public void preSendHeartbeatDoesNotInvokeSessionRepository() { + void preSendHeartbeatDoesNotInvokeSessionRepository() { setMessageType(SimpMessageType.HEARTBEAT); - assertThat(this.interceptor.preSend(createMessage(), this.channel)) - .isSameAs(this.createMessage); + assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage); verifyZeroInteractions(this.sessionRepository); } @Test - public void preSendDisconnectDoesNotInvokeSessionRepository() { + void preSendDisconnectDoesNotInvokeSessionRepository() { setMessageType(SimpMessageType.DISCONNECT); - assertThat(this.interceptor.preSend(createMessage(), this.channel)) - .isSameAs(this.createMessage); + assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage); verifyZeroInteractions(this.sessionRepository); } @Test - public void preSendOtherDoesNotInvokeSessionRepository() { + void preSendOtherDoesNotInvokeSessionRepository() { setMessageType(SimpMessageType.OTHER); - assertThat(this.interceptor.preSend(createMessage(), this.channel)) - .isSameAs(this.createMessage); + assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage); verifyZeroInteractions(this.sessionRepository); } @Test - public void setMatchingMessageTypesNull() { + void setMatchingMessageTypesNull() { + assertThatIllegalArgumentException().isThrownBy(() -> this.interceptor.setMatchingMessageTypes(null)) + .withMessage("matchingMessageTypes cannot be null or empty"); + } + + @Test + void setMatchingMessageTypesEmpty() { assertThatIllegalArgumentException() - .isThrownBy(() -> this.interceptor.setMatchingMessageTypes(null)) + .isThrownBy(() -> this.interceptor.setMatchingMessageTypes(Collections.emptySet())) .withMessage("matchingMessageTypes cannot be null or empty"); } @Test - public void setMatchingMessageTypesEmpty() { - assertThatIllegalArgumentException().isThrownBy( - () -> this.interceptor.setMatchingMessageTypes(Collections.emptySet())) - .withMessage("matchingMessageTypes cannot be null or empty"); - } - - @Test - public void preSendSetMatchingMessageTypes() { + void preSendSetMatchingMessageTypes() { this.interceptor.setMatchingMessageTypes(EnumSet.of(SimpMessageType.DISCONNECT)); setMessageType(SimpMessageType.DISCONNECT); - assertThat(this.interceptor.preSend(createMessage(), this.channel)) - .isSameAs(this.createMessage); + assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage); verify(this.sessionRepository).findById(anyString()); verify(this.sessionRepository).save(this.session); } @Test - public void preSendConnectUpdatesLastUpdateTime() { + void preSendConnectUpdatesLastUpdateTime() { setMessageType(SimpMessageType.CONNECT); - assertThat(this.interceptor.preSend(createMessage(), this.channel)) - .isSameAs(this.createMessage); + assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage); verify(this.session).setLastAccessedTime(argThat(isAlmostNow())); verify(this.sessionRepository).save(this.session); } @Test - public void preSendMessageUpdatesLastUpdateTime() { + void preSendMessageUpdatesLastUpdateTime() { setMessageType(SimpMessageType.MESSAGE); - assertThat(this.interceptor.preSend(createMessage(), this.channel)) - .isSameAs(this.createMessage); + assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage); verify(this.session).setLastAccessedTime(argThat(isAlmostNow())); verify(this.sessionRepository).save(this.session); } @Test - public void preSendSubscribeUpdatesLastUpdateTime() { + void preSendSubscribeUpdatesLastUpdateTime() { setMessageType(SimpMessageType.SUBSCRIBE); - assertThat(this.interceptor.preSend(createMessage(), this.channel)) - .isSameAs(this.createMessage); + assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage); verify(this.session).setLastAccessedTime(argThat(isAlmostNow())); verify(this.sessionRepository).save(this.session); } @Test - public void preSendUnsubscribeUpdatesLastUpdateTime() { + void preSendUnsubscribeUpdatesLastUpdateTime() { setMessageType(SimpMessageType.UNSUBSCRIBE); this.session.setLastAccessedTime(Instant.EPOCH); - assertThat(this.interceptor.preSend(createMessage(), this.channel)) - .isSameAs(this.createMessage); + assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage); verify(this.session).setLastAccessedTime(argThat(isAlmostNow())); verify(this.sessionRepository).save(this.session); @@ -204,7 +195,7 @@ public class SessionRepositoryMessageInterceptorTests { // This will updated when SPR-12288 is resolved @Test - public void preSendExpiredSession() { + void preSendExpiredSession() { setSessionId("expired"); this.interceptor.preSend(createMessage(), this.channel); @@ -213,74 +204,67 @@ public class SessionRepositoryMessageInterceptorTests { } @Test - public void preSendNullSessionId() { + void preSendNullSessionId() { setSessionId(null); - assertThat(this.interceptor.preSend(createMessage(), this.channel)) - .isSameAs(this.createMessage); + assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage); verifyZeroInteractions(this.sessionRepository); } @Test - public void preSendNullSessionAttributes() { + void preSendNullSessionAttributes() { this.headers.setSessionAttributes(null); - assertThat(this.interceptor.preSend(createMessage(), this.channel)) - .isSameAs(this.createMessage); + assertThat(this.interceptor.preSend(createMessage(), this.channel)).isSameAs(this.createMessage); verifyZeroInteractions(this.sessionRepository); } @Test - public void beforeHandshakeNotServletServerHttpRequest() throws Exception { + void beforeHandshakeNotServletServerHttpRequest() throws Exception { assertThat(this.interceptor.beforeHandshake(null, null, null, null)).isTrue(); verifyZeroInteractions(this.sessionRepository); } @Test - public void beforeHandshakeNullSession() throws Exception { - ServletServerHttpRequest request = new ServletServerHttpRequest( - new MockHttpServletRequest()); + void beforeHandshakeNullSession() throws Exception { + ServletServerHttpRequest request = new ServletServerHttpRequest(new MockHttpServletRequest()); assertThat(this.interceptor.beforeHandshake(request, null, null, null)).isTrue(); verifyZeroInteractions(this.sessionRepository); } @Test - public void beforeHandshakeSession() throws Exception { + void beforeHandshakeSession() throws Exception { MockHttpServletRequest httpRequest = new MockHttpServletRequest(); HttpSession httpSession = httpRequest.getSession(); ServletServerHttpRequest request = new ServletServerHttpRequest(httpRequest); Map attributes = new HashMap<>(); - assertThat(this.interceptor.beforeHandshake(request, null, null, attributes)) - .isTrue(); + assertThat(this.interceptor.beforeHandshake(request, null, null, attributes)).isTrue(); assertThat(attributes.size()).isEqualTo(1); - assertThat(SessionRepositoryMessageInterceptor.getSessionId(attributes)) - .isEqualTo(httpSession.getId()); + assertThat(SessionRepositoryMessageInterceptor.getSessionId(attributes)).isEqualTo(httpSession.getId()); } /** * At the moment there is no need for afterHandshake to do anything. */ @Test - public void afterHandshakeDoesNothing() { + void afterHandshakeDoesNothing() { this.interceptor.afterHandshake(null, null, null, null); verifyZeroInteractions(this.sessionRepository); } private void setSessionId(String id) { - SessionRepositoryMessageInterceptor - .setSessionId(this.headers.getSessionAttributes(), id); + SessionRepositoryMessageInterceptor.setSessionId(this.headers.getSessionAttributes(), id); } private Message createMessage() { - this.createMessage = MessageBuilder.createMessage("", - this.headers.getMessageHeaders()); + this.createMessage = MessageBuilder.createMessage("", this.headers.getMessageHeaders()); return this.createMessage; } @@ -302,4 +286,5 @@ public class SessionRepositoryMessageInterceptorTests { } } + } diff --git a/spring-session-data-redis/src/integration-test/java/org/springframework/session/data/SessionEventRegistry.java b/spring-session-data-redis/src/integration-test/java/org/springframework/session/data/SessionEventRegistry.java index a15c92fb..a82d4756 100644 --- a/spring-session-data-redis/src/integration-test/java/org/springframework/session/data/SessionEventRegistry.java +++ b/spring-session-data-redis/src/integration-test/java/org/springframework/session/data/SessionEventRegistry.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,9 @@ import org.springframework.context.ApplicationListener; import org.springframework.session.events.AbstractSessionEvent; public class SessionEventRegistry implements ApplicationListener { + private Map events = new HashMap<>(); + private ConcurrentMap locks = new ConcurrentHashMap<>(); @Override @@ -48,14 +50,12 @@ public class SessionEventRegistry implements ApplicationListener E getEvent(String sessionId) - throws InterruptedException { + public E getEvent(String sessionId) throws InterruptedException { return (E) waitForEvent(sessionId); } @SuppressWarnings("unchecked") - private E waitForEvent(String sessionId) - throws InterruptedException { + private E waitForEvent(String sessionId) throws InterruptedException { Object lock = getLock(sessionId); synchronized (lock) { if (!this.events.containsKey(sessionId)) { @@ -68,4 +68,5 @@ public class SessionEventRegistry implements ApplicationListener new Object()); } + } diff --git a/spring-session-data-redis/src/integration-test/java/org/springframework/session/data/redis/AbstractRedisITests.java b/spring-session-data-redis/src/integration-test/java/org/springframework/session/data/redis/AbstractRedisITests.java index 76afac28..83c29857 100644 --- a/spring-session-data-redis/src/integration-test/java/org/springframework/session/data/redis/AbstractRedisITests.java +++ b/spring-session-data-redis/src/integration-test/java/org/springframework/session/data/redis/AbstractRedisITests.java @@ -35,8 +35,7 @@ public abstract class AbstractRedisITests { @Bean public GenericContainer redisContainer() { - GenericContainer redisContainer = new GenericContainer(DOCKER_IMAGE) - .withExposedPorts(6379); + GenericContainer redisContainer = new GenericContainer(DOCKER_IMAGE).withExposedPorts(6379); redisContainer.start(); return redisContainer; } @@ -44,8 +43,7 @@ public abstract class AbstractRedisITests { @Bean public LettuceConnectionFactory redisConnectionFactory() { RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration( - redisContainer().getContainerIpAddress(), - redisContainer().getFirstMappedPort()); + redisContainer().getContainerIpAddress(), redisContainer().getFirstMappedPort()); return new LettuceConnectionFactory(configuration); } diff --git a/spring-session-data-redis/src/integration-test/java/org/springframework/session/data/redis/ReactiveRedisOperationsSessionRepositoryITests.java b/spring-session-data-redis/src/integration-test/java/org/springframework/session/data/redis/ReactiveRedisOperationsSessionRepositoryITests.java index 2015ca18..2d9d9195 100644 --- a/spring-session-data-redis/src/integration-test/java/org/springframework/session/data/redis/ReactiveRedisOperationsSessionRepositoryITests.java +++ b/spring-session-data-redis/src/integration-test/java/org/springframework/session/data/redis/ReactiveRedisOperationsSessionRepositoryITests.java @@ -41,15 +41,14 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; @ExtendWith(SpringExtension.class) @ContextConfiguration @WebAppConfiguration -public class ReactiveRedisOperationsSessionRepositoryITests extends AbstractRedisITests { +class ReactiveRedisOperationsSessionRepositoryITests extends AbstractRedisITests { @Autowired private ReactiveRedisOperationsSessionRepository repository; @Test - public void saves() throws InterruptedException { - ReactiveRedisOperationsSessionRepository.RedisSession toSave = this.repository - .createSession().block(); + void saves() throws InterruptedException { + ReactiveRedisOperationsSessionRepository.RedisSession toSave = this.repository.createSession().block(); String expectedAttributeName = "a"; String expectedAttributeValue = "b"; @@ -70,9 +69,8 @@ public class ReactiveRedisOperationsSessionRepositoryITests extends AbstractRedi } @Test // gh-1399 - public void saveMultipleTimes() { - ReactiveRedisOperationsSessionRepository.RedisSession session = this.repository - .createSession().block(); + void saveMultipleTimes() { + ReactiveRedisOperationsSessionRepository.RedisSession session = this.repository.createSession().block(); session.setAttribute("attribute1", "value1"); Mono save1 = this.repository.save(session); session.setAttribute("attribute2", "value2"); @@ -81,9 +79,8 @@ public class ReactiveRedisOperationsSessionRepositoryITests extends AbstractRedi } @Test - public void putAllOnSingleAttrDoesNotRemoveOld() { - ReactiveRedisOperationsSessionRepository.RedisSession toSave = this.repository - .createSession().block(); + void putAllOnSingleAttrDoesNotRemoveOld() { + ReactiveRedisOperationsSessionRepository.RedisSession toSave = this.repository.createSession().block(); toSave.setAttribute("a", "b"); this.repository.save(toSave).block(); @@ -103,17 +100,16 @@ public class ReactiveRedisOperationsSessionRepositoryITests extends AbstractRedi } @Test - public void changeSessionIdWhenOnlyChangeId() throws Exception { + void changeSessionIdWhenOnlyChangeId() throws Exception { String attrName = "changeSessionId"; String attrValue = "changeSessionId-value"; - ReactiveRedisOperationsSessionRepository.RedisSession toSave = this.repository - .createSession().block(); + ReactiveRedisOperationsSessionRepository.RedisSession toSave = this.repository.createSession().block(); toSave.setAttribute(attrName, attrValue); this.repository.save(toSave).block(); - ReactiveRedisOperationsSessionRepository.RedisSession findById = this.repository - .findById(toSave.getId()).block(); + ReactiveRedisOperationsSessionRepository.RedisSession findById = this.repository.findById(toSave.getId()) + .block(); assertThat(findById.getAttribute(attrName)).isEqualTo(attrValue); @@ -127,14 +123,12 @@ public class ReactiveRedisOperationsSessionRepositoryITests extends AbstractRedi ReactiveRedisOperationsSessionRepository.RedisSession findByChangeSessionId = this.repository .findById(changeSessionId).block(); - assertThat(findByChangeSessionId.getAttribute(attrName)) - .isEqualTo(attrValue); + assertThat(findByChangeSessionId.getAttribute(attrName)).isEqualTo(attrValue); } @Test - public void changeSessionIdWhenChangeTwice() throws Exception { - ReactiveRedisOperationsSessionRepository.RedisSession toSave = this.repository - .createSession().block(); + void changeSessionIdWhenChangeTwice() throws Exception { + ReactiveRedisOperationsSessionRepository.RedisSession toSave = this.repository.createSession().block(); this.repository.save(toSave).block(); @@ -150,17 +144,16 @@ public class ReactiveRedisOperationsSessionRepositoryITests extends AbstractRedi } @Test - public void changeSessionIdWhenSetAttributeOnChangedSession() throws Exception { + void changeSessionIdWhenSetAttributeOnChangedSession() throws Exception { String attrName = "changeSessionId"; String attrValue = "changeSessionId-value"; - ReactiveRedisOperationsSessionRepository.RedisSession toSave = this.repository - .createSession().block(); + ReactiveRedisOperationsSessionRepository.RedisSession toSave = this.repository.createSession().block(); this.repository.save(toSave).block(); - ReactiveRedisOperationsSessionRepository.RedisSession findById = this.repository - .findById(toSave.getId()).block(); + ReactiveRedisOperationsSessionRepository.RedisSession findById = this.repository.findById(toSave.getId()) + .block(); findById.setAttribute(attrName, attrValue); @@ -174,14 +167,12 @@ public class ReactiveRedisOperationsSessionRepositoryITests extends AbstractRedi ReactiveRedisOperationsSessionRepository.RedisSession findByChangeSessionId = this.repository .findById(changeSessionId).block(); - assertThat(findByChangeSessionId.getAttribute(attrName)) - .isEqualTo(attrValue); + assertThat(findByChangeSessionId.getAttribute(attrName)).isEqualTo(attrValue); } @Test - public void changeSessionIdWhenHasNotSaved() throws Exception { - ReactiveRedisOperationsSessionRepository.RedisSession toSave = this.repository - .createSession().block(); + void changeSessionIdWhenHasNotSaved() throws Exception { + ReactiveRedisOperationsSessionRepository.RedisSession toSave = this.repository.createSession().block(); String originalId = toSave.getId(); toSave.changeSessionId(); @@ -193,9 +184,8 @@ public class ReactiveRedisOperationsSessionRepositoryITests extends AbstractRedi // gh-954 @Test - public void changeSessionIdSaveTwice() { - ReactiveRedisOperationsSessionRepository.RedisSession toSave = this.repository - .createSession().block(); + void changeSessionIdSaveTwice() { + ReactiveRedisOperationsSessionRepository.RedisSession toSave = this.repository.createSession().block(); String originalId = toSave.getId(); toSave.changeSessionId(); @@ -208,23 +198,20 @@ public class ReactiveRedisOperationsSessionRepositoryITests extends AbstractRedi // gh-1111 @Test - public void changeSessionSaveOldSessionInstance() { - ReactiveRedisOperationsSessionRepository.RedisSession toSave = this.repository - .createSession().block(); + void changeSessionSaveOldSessionInstance() { + ReactiveRedisOperationsSessionRepository.RedisSession toSave = this.repository.createSession().block(); String sessionId = toSave.getId(); this.repository.save(toSave).block(); - ReactiveRedisOperationsSessionRepository.RedisSession session = this.repository - .findById(sessionId).block(); + ReactiveRedisOperationsSessionRepository.RedisSession session = this.repository.findById(sessionId).block(); session.changeSessionId(); session.setLastAccessedTime(Instant.now()); this.repository.save(session).block(); toSave.setLastAccessedTime(Instant.now()); - assertThatIllegalStateException() - .isThrownBy(() -> this.repository.save(toSave).block()) + assertThatIllegalStateException().isThrownBy(() -> this.repository.save(toSave).block()) .withMessage("Session was invalidated"); assertThat(this.repository.findById(sessionId).block()).isNull(); diff --git a/spring-session-data-redis/src/integration-test/java/org/springframework/session/data/redis/RedisOperationsSessionRepositoryITests.java b/spring-session-data-redis/src/integration-test/java/org/springframework/session/data/redis/RedisOperationsSessionRepositoryITests.java index 3b05d485..18e422ce 100644 --- a/spring-session-data-redis/src/integration-test/java/org/springframework/session/data/redis/RedisOperationsSessionRepositoryITests.java +++ b/spring-session-data-redis/src/integration-test/java/org/springframework/session/data/redis/RedisOperationsSessionRepositoryITests.java @@ -51,7 +51,7 @@ import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(SpringExtension.class) @ContextConfiguration @WebAppConfiguration -public class RedisOperationsSessionRepositoryITests extends AbstractRedisITests { +class RedisOperationsSessionRepositoryITests extends AbstractRedisITests { private static final String SPRING_SECURITY_CONTEXT = "SPRING_SECURITY_CONTEXT"; @@ -71,34 +71,31 @@ public class RedisOperationsSessionRepositoryITests extends AbstractRedisITests private SecurityContext changedContext; @BeforeEach - public void setup() { + void setup() { if (this.registry != null) { this.registry.clear(); } this.context = SecurityContextHolder.createEmptyContext(); - this.context.setAuthentication( - new UsernamePasswordAuthenticationToken("username-" + UUID.randomUUID(), - "na", AuthorityUtils.createAuthorityList("ROLE_USER"))); + this.context.setAuthentication(new UsernamePasswordAuthenticationToken("username-" + UUID.randomUUID(), "na", + AuthorityUtils.createAuthorityList("ROLE_USER"))); this.changedContext = SecurityContextHolder.createEmptyContext(); this.changedContext.setAuthentication(new UsernamePasswordAuthenticationToken( - "changedContext-" + UUID.randomUUID(), "na", - AuthorityUtils.createAuthorityList("ROLE_USER"))); + "changedContext-" + UUID.randomUUID(), "na", AuthorityUtils.createAuthorityList("ROLE_USER"))); } @Test - public void saves() throws InterruptedException { + void saves() throws InterruptedException { String username = "saves-" + System.currentTimeMillis(); - String usernameSessionKey = "RedisOperationsSessionRepositoryITests:index:" - + INDEX_NAME + ":" + username; + String usernameSessionKey = "RedisOperationsSessionRepositoryITests:index:" + INDEX_NAME + ":" + username; RedisSession toSave = this.repository.createSession(); String expectedAttributeName = "a"; String expectedAttributeValue = "b"; toSave.setAttribute(expectedAttributeName, expectedAttributeValue); - Authentication toSaveToken = new UsernamePasswordAuthenticationToken(username, - "password", AuthorityUtils.createAuthorityList("ROLE_USER")); + Authentication toSaveToken = new UsernamePasswordAuthenticationToken(username, "password", + AuthorityUtils.createAuthorityList("ROLE_USER")); SecurityContext toSaveContext = SecurityContextHolder.createEmptyContext(); toSaveContext.setAuthentication(toSaveToken); toSave.setAttribute(SPRING_SECURITY_CONTEXT, toSaveContext); @@ -108,10 +105,8 @@ public class RedisOperationsSessionRepositoryITests extends AbstractRedisITests this.repository.save(toSave); assertThat(this.registry.receivedEvent(toSave.getId())).isTrue(); - assertThat(this.registry.getEvent(toSave.getId())) - .isInstanceOf(SessionCreatedEvent.class); - assertThat(this.redis.boundSetOps(usernameSessionKey).members()) - .contains(toSave.getId()); + assertThat(this.registry.getEvent(toSave.getId())).isInstanceOf(SessionCreatedEvent.class); + assertThat(this.redis.boundSetOps(usernameSessionKey).members()).contains(toSave.getId()); Session session = this.repository.findById(toSave.getId()); @@ -127,16 +122,14 @@ public class RedisOperationsSessionRepositoryITests extends AbstractRedisITests assertThat(this.repository.findById(toSave.getId())).isNull(); assertThat(this.registry.getEvent(toSave.getId())) .isInstanceOf(SessionDestroyedEvent.class); - assertThat(this.redis.boundSetOps(usernameSessionKey).members()) - .doesNotContain(toSave.getId()); + assertThat(this.redis.boundSetOps(usernameSessionKey).members()).doesNotContain(toSave.getId()); - assertThat(this.registry.getEvent(toSave.getId()).getSession() - .getAttribute(expectedAttributeName)) + assertThat(this.registry.getEvent(toSave.getId()).getSession().getAttribute(expectedAttributeName)) .isEqualTo(expectedAttributeValue); } @Test - public void putAllOnSingleAttrDoesNotRemoveOld() { + void putAllOnSingleAttrDoesNotRemoveOld() { RedisSession toSave = this.repository.createSession(); toSave.setAttribute("a", "b"); @@ -157,15 +150,15 @@ public class RedisOperationsSessionRepositoryITests extends AbstractRedisITests } @Test - public void findByPrincipalName() throws Exception { + void findByPrincipalName() throws Exception { String principalName = "findByPrincipalName" + UUID.randomUUID(); RedisSession toSave = this.repository.createSession(); toSave.setAttribute(INDEX_NAME, principalName); this.repository.save(toSave); - Map findByPrincipalName = this.repository - .findByIndexNameAndIndexValue(INDEX_NAME, principalName); + Map findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, + principalName); assertThat(findByPrincipalName).hasSize(1); assertThat(findByPrincipalName.keySet()).containsOnly(toSave.getId()); @@ -173,7 +166,28 @@ public class RedisOperationsSessionRepositoryITests extends AbstractRedisITests this.repository.deleteById(toSave.getId()); assertThat(this.registry.receivedEvent(toSave.getId())).isTrue(); - findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, + findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, principalName); + + assertThat(findByPrincipalName).hasSize(0); + assertThat(findByPrincipalName.keySet()).doesNotContain(toSave.getId()); + } + + @Test + void findByPrincipalNameExpireRemovesIndex() throws Exception { + String principalName = "findByPrincipalNameExpireRemovesIndex" + UUID.randomUUID(); + RedisSession toSave = this.repository.createSession(); + toSave.setAttribute(INDEX_NAME, principalName); + + this.repository.save(toSave); + + String body = "RedisOperationsSessionRepositoryITests:sessions:expires:" + toSave.getId(); + String channel = "__keyevent@0__:expired"; + DefaultMessage message = new DefaultMessage(channel.getBytes(StandardCharsets.UTF_8), + body.getBytes(StandardCharsets.UTF_8)); + byte[] pattern = new byte[] {}; + this.repository.onMessage(message, pattern); + + Map findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, principalName); assertThat(findByPrincipalName).hasSize(0); @@ -181,34 +195,8 @@ public class RedisOperationsSessionRepositoryITests extends AbstractRedisITests } @Test - public void findByPrincipalNameExpireRemovesIndex() throws Exception { - String principalName = "findByPrincipalNameExpireRemovesIndex" - + UUID.randomUUID(); - RedisSession toSave = this.repository.createSession(); - toSave.setAttribute(INDEX_NAME, principalName); - - this.repository.save(toSave); - - String body = "RedisOperationsSessionRepositoryITests:sessions:expires:" - + toSave.getId(); - String channel = "__keyevent@0__:expired"; - DefaultMessage message = new DefaultMessage( - channel.getBytes(StandardCharsets.UTF_8), - body.getBytes(StandardCharsets.UTF_8)); - byte[] pattern = new byte[] {}; - this.repository.onMessage(message, pattern); - - Map findByPrincipalName = this.repository - .findByIndexNameAndIndexValue(INDEX_NAME, principalName); - - assertThat(findByPrincipalName).hasSize(0); - assertThat(findByPrincipalName.keySet()).doesNotContain(toSave.getId()); - } - - @Test - public void findByPrincipalNameNoPrincipalNameChange() throws Exception { - String principalName = "findByPrincipalNameNoPrincipalNameChange" - + UUID.randomUUID(); + void findByPrincipalNameNoPrincipalNameChange() throws Exception { + String principalName = "findByPrincipalNameNoPrincipalNameChange" + UUID.randomUUID(); RedisSession toSave = this.repository.createSession(); toSave.setAttribute(INDEX_NAME, principalName); @@ -217,17 +205,16 @@ public class RedisOperationsSessionRepositoryITests extends AbstractRedisITests toSave.setAttribute("other", "value"); this.repository.save(toSave); - Map findByPrincipalName = this.repository - .findByIndexNameAndIndexValue(INDEX_NAME, principalName); + Map findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, + principalName); assertThat(findByPrincipalName).hasSize(1); assertThat(findByPrincipalName.keySet()).containsOnly(toSave.getId()); } @Test - public void findByPrincipalNameNoPrincipalNameChangeReload() throws Exception { - String principalName = "findByPrincipalNameNoPrincipalNameChangeReload" - + UUID.randomUUID(); + void findByPrincipalNameNoPrincipalNameChangeReload() throws Exception { + String principalName = "findByPrincipalNameNoPrincipalNameChangeReload" + UUID.randomUUID(); RedisSession toSave = this.repository.createSession(); toSave.setAttribute(INDEX_NAME, principalName); @@ -238,15 +225,15 @@ public class RedisOperationsSessionRepositoryITests extends AbstractRedisITests toSave.setAttribute("other", "value"); this.repository.save(toSave); - Map findByPrincipalName = this.repository - .findByIndexNameAndIndexValue(INDEX_NAME, principalName); + Map findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, + principalName); assertThat(findByPrincipalName).hasSize(1); assertThat(findByPrincipalName.keySet()).containsOnly(toSave.getId()); } @Test - public void findByDeletedPrincipalName() throws Exception { + void findByDeletedPrincipalName() throws Exception { String principalName = "findByDeletedPrincipalName" + UUID.randomUUID(); RedisSession toSave = this.repository.createSession(); toSave.setAttribute(INDEX_NAME, principalName); @@ -256,14 +243,14 @@ public class RedisOperationsSessionRepositoryITests extends AbstractRedisITests toSave.setAttribute(INDEX_NAME, null); this.repository.save(toSave); - Map findByPrincipalName = this.repository - .findByIndexNameAndIndexValue(INDEX_NAME, principalName); + Map findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, + principalName); assertThat(findByPrincipalName).isEmpty(); } @Test - public void findByChangedPrincipalName() throws Exception { + void findByChangedPrincipalName() throws Exception { String principalName = "findByChangedPrincipalName" + UUID.randomUUID(); String principalNameChanged = "findByChangedPrincipalName" + UUID.randomUUID(); RedisSession toSave = this.repository.createSession(); @@ -274,19 +261,18 @@ public class RedisOperationsSessionRepositoryITests extends AbstractRedisITests toSave.setAttribute(INDEX_NAME, principalNameChanged); this.repository.save(toSave); - Map findByPrincipalName = this.repository - .findByIndexNameAndIndexValue(INDEX_NAME, principalName); + Map findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, + principalName); assertThat(findByPrincipalName).isEmpty(); - findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, - principalNameChanged); + findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, principalNameChanged); assertThat(findByPrincipalName).hasSize(1); assertThat(findByPrincipalName.keySet()).containsOnly(toSave.getId()); } @Test - public void findByDeletedPrincipalNameReload() throws Exception { + void findByDeletedPrincipalNameReload() throws Exception { String principalName = "findByDeletedPrincipalName" + UUID.randomUUID(); RedisSession toSave = this.repository.createSession(); toSave.setAttribute(INDEX_NAME, principalName); @@ -297,14 +283,14 @@ public class RedisOperationsSessionRepositoryITests extends AbstractRedisITests getSession.setAttribute(INDEX_NAME, null); this.repository.save(getSession); - Map findByPrincipalName = this.repository - .findByIndexNameAndIndexValue(INDEX_NAME, principalName); + Map findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, + principalName); assertThat(findByPrincipalName).isEmpty(); } @Test - public void findByChangedPrincipalNameReload() throws Exception { + void findByChangedPrincipalNameReload() throws Exception { String principalName = "findByChangedPrincipalName" + UUID.randomUUID(); String principalNameChanged = "findByChangedPrincipalName" + UUID.randomUUID(); RedisSession toSave = this.repository.createSession(); @@ -317,26 +303,25 @@ public class RedisOperationsSessionRepositoryITests extends AbstractRedisITests getSession.setAttribute(INDEX_NAME, principalNameChanged); this.repository.save(getSession); - Map findByPrincipalName = this.repository - .findByIndexNameAndIndexValue(INDEX_NAME, principalName); + Map findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, + principalName); assertThat(findByPrincipalName).isEmpty(); - findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, - principalNameChanged); + findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, principalNameChanged); assertThat(findByPrincipalName).hasSize(1); assertThat(findByPrincipalName.keySet()).containsOnly(toSave.getId()); } @Test - public void findBySecurityPrincipalName() throws Exception { + void findBySecurityPrincipalName() throws Exception { RedisSession toSave = this.repository.createSession(); toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.context); this.repository.save(toSave); - Map findByPrincipalName = this.repository - .findByIndexNameAndIndexValue(INDEX_NAME, getSecurityName()); + Map findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, + getSecurityName()); assertThat(findByPrincipalName).hasSize(1); assertThat(findByPrincipalName.keySet()).containsOnly(toSave.getId()); @@ -344,7 +329,27 @@ public class RedisOperationsSessionRepositoryITests extends AbstractRedisITests this.repository.deleteById(toSave.getId()); assertThat(this.registry.receivedEvent(toSave.getId())).isTrue(); - findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, + findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, getSecurityName()); + + assertThat(findByPrincipalName).hasSize(0); + assertThat(findByPrincipalName.keySet()).doesNotContain(toSave.getId()); + } + + @Test + void findBySecurityPrincipalNameExpireRemovesIndex() throws Exception { + RedisSession toSave = this.repository.createSession(); + toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.context); + + this.repository.save(toSave); + + String body = "RedisOperationsSessionRepositoryITests:sessions:expires:" + toSave.getId(); + String channel = "__keyevent@0__:expired"; + DefaultMessage message = new DefaultMessage(channel.getBytes(StandardCharsets.UTF_8), + body.getBytes(StandardCharsets.UTF_8)); + byte[] pattern = new byte[] {}; + this.repository.onMessage(message, pattern); + + Map findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, getSecurityName()); assertThat(findByPrincipalName).hasSize(0); @@ -352,30 +357,7 @@ public class RedisOperationsSessionRepositoryITests extends AbstractRedisITests } @Test - public void findBySecurityPrincipalNameExpireRemovesIndex() throws Exception { - RedisSession toSave = this.repository.createSession(); - toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.context); - - this.repository.save(toSave); - - String body = "RedisOperationsSessionRepositoryITests:sessions:expires:" - + toSave.getId(); - String channel = "__keyevent@0__:expired"; - DefaultMessage message = new DefaultMessage( - channel.getBytes(StandardCharsets.UTF_8), - body.getBytes(StandardCharsets.UTF_8)); - byte[] pattern = new byte[] {}; - this.repository.onMessage(message, pattern); - - Map findByPrincipalName = this.repository - .findByIndexNameAndIndexValue(INDEX_NAME, getSecurityName()); - - assertThat(findByPrincipalName).hasSize(0); - assertThat(findByPrincipalName.keySet()).doesNotContain(toSave.getId()); - } - - @Test - public void findByPrincipalNameNoSecurityPrincipalNameChange() throws Exception { + void findByPrincipalNameNoSecurityPrincipalNameChange() throws Exception { RedisSession toSave = this.repository.createSession(); toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.context); @@ -384,16 +366,15 @@ public class RedisOperationsSessionRepositoryITests extends AbstractRedisITests toSave.setAttribute("other", "value"); this.repository.save(toSave); - Map findByPrincipalName = this.repository - .findByIndexNameAndIndexValue(INDEX_NAME, getSecurityName()); + Map findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, + getSecurityName()); assertThat(findByPrincipalName).hasSize(1); assertThat(findByPrincipalName.keySet()).containsOnly(toSave.getId()); } @Test - public void findByPrincipalNameNoSecurityPrincipalNameChangeReload() - throws Exception { + void findByPrincipalNameNoSecurityPrincipalNameChangeReload() throws Exception { RedisSession toSave = this.repository.createSession(); toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.context); @@ -404,15 +385,15 @@ public class RedisOperationsSessionRepositoryITests extends AbstractRedisITests toSave.setAttribute("other", "value"); this.repository.save(toSave); - Map findByPrincipalName = this.repository - .findByIndexNameAndIndexValue(INDEX_NAME, getSecurityName()); + Map findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, + getSecurityName()); assertThat(findByPrincipalName).hasSize(1); assertThat(findByPrincipalName.keySet()).containsOnly(toSave.getId()); } @Test - public void findByDeletedSecurityPrincipalName() throws Exception { + void findByDeletedSecurityPrincipalName() throws Exception { RedisSession toSave = this.repository.createSession(); toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.context); @@ -421,14 +402,14 @@ public class RedisOperationsSessionRepositoryITests extends AbstractRedisITests toSave.setAttribute(SPRING_SECURITY_CONTEXT, null); this.repository.save(toSave); - Map findByPrincipalName = this.repository - .findByIndexNameAndIndexValue(INDEX_NAME, getSecurityName()); + Map findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, + getSecurityName()); assertThat(findByPrincipalName).isEmpty(); } @Test - public void findByChangedSecurityPrincipalName() throws Exception { + void findByChangedSecurityPrincipalName() throws Exception { RedisSession toSave = this.repository.createSession(); toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.context); @@ -437,19 +418,18 @@ public class RedisOperationsSessionRepositoryITests extends AbstractRedisITests toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.changedContext); this.repository.save(toSave); - Map findByPrincipalName = this.repository - .findByIndexNameAndIndexValue(INDEX_NAME, getSecurityName()); + Map findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, + getSecurityName()); assertThat(findByPrincipalName).isEmpty(); - findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, - getChangedSecurityName()); + findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, getChangedSecurityName()); assertThat(findByPrincipalName).hasSize(1); assertThat(findByPrincipalName.keySet()).containsOnly(toSave.getId()); } @Test - public void findByDeletedSecurityPrincipalNameReload() throws Exception { + void findByDeletedSecurityPrincipalNameReload() throws Exception { RedisSession toSave = this.repository.createSession(); toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.context); @@ -459,14 +439,14 @@ public class RedisOperationsSessionRepositoryITests extends AbstractRedisITests getSession.setAttribute(INDEX_NAME, null); this.repository.save(getSession); - Map findByPrincipalName = this.repository - .findByIndexNameAndIndexValue(INDEX_NAME, getChangedSecurityName()); + Map findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, + getChangedSecurityName()); assertThat(findByPrincipalName).isEmpty(); } @Test - public void findByChangedSecurityPrincipalNameReload() throws Exception { + void findByChangedSecurityPrincipalNameReload() throws Exception { RedisSession toSave = this.repository.createSession(); toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.context); @@ -477,19 +457,18 @@ public class RedisOperationsSessionRepositoryITests extends AbstractRedisITests getSession.setAttribute(SPRING_SECURITY_CONTEXT, this.changedContext); this.repository.save(getSession); - Map findByPrincipalName = this.repository - .findByIndexNameAndIndexValue(INDEX_NAME, getSecurityName()); + Map findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, + getSecurityName()); assertThat(findByPrincipalName).isEmpty(); - findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, - getChangedSecurityName()); + findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, getChangedSecurityName()); assertThat(findByPrincipalName).hasSize(1); assertThat(findByPrincipalName.keySet()).containsOnly(toSave.getId()); } @Test - public void changeSessionIdWhenOnlyChangeId() throws Exception { + void changeSessionIdWhenOnlyChangeId() throws Exception { String attrName = "changeSessionId"; String attrValue = "changeSessionId-value"; RedisSession toSave = this.repository.createSession(); @@ -514,7 +493,7 @@ public class RedisOperationsSessionRepositoryITests extends AbstractRedisITests } @Test - public void changeSessionIdWhenChangeTwice() throws Exception { + void changeSessionIdWhenChangeTwice() throws Exception { RedisSession toSave = this.repository.createSession(); this.repository.save(toSave); @@ -531,7 +510,7 @@ public class RedisOperationsSessionRepositoryITests extends AbstractRedisITests } @Test - public void changeSessionIdWhenSetAttributeOnChangedSession() throws Exception { + void changeSessionIdWhenSetAttributeOnChangedSession() throws Exception { String attrName = "changeSessionId"; String attrValue = "changeSessionId-value"; @@ -556,7 +535,7 @@ public class RedisOperationsSessionRepositoryITests extends AbstractRedisITests } @Test - public void changeSessionIdWhenHasNotSaved() throws Exception { + void changeSessionIdWhenHasNotSaved() throws Exception { String attrName = "changeSessionId"; String attrValue = "changeSessionId-value"; @@ -572,7 +551,7 @@ public class RedisOperationsSessionRepositoryITests extends AbstractRedisITests // gh-962 @Test - public void changeSessionIdSaveTwice() { + void changeSessionIdSaveTwice() { RedisSession toSave = this.repository.createSession(); String originalId = toSave.getId(); toSave.changeSessionId(); @@ -586,7 +565,7 @@ public class RedisOperationsSessionRepositoryITests extends AbstractRedisITests // gh-1137 @Test - public void changeSessionIdWhenSessionIsDeleted() { + void changeSessionIdWhenSessionIsDeleted() { RedisSession toSave = this.repository.createSession(); String sessionId = toSave.getId(); this.repository.save(toSave); @@ -601,7 +580,7 @@ public class RedisOperationsSessionRepositoryITests extends AbstractRedisITests } @Test // gh-1270 - public void changeSessionIdSaveConcurrently() { + void changeSessionIdSaveConcurrently() { RedisSession toSave = this.repository.createSession(); String originalId = toSave.getId(); this.repository.save(toSave); diff --git a/spring-session-data-redis/src/integration-test/java/org/springframework/session/data/redis/SimpleRedisOperationsSessionRepositoryITests.java b/spring-session-data-redis/src/integration-test/java/org/springframework/session/data/redis/SimpleRedisOperationsSessionRepositoryITests.java index 9b18edb4..8bb63d2d 100644 --- a/spring-session-data-redis/src/integration-test/java/org/springframework/session/data/redis/SimpleRedisOperationsSessionRepositoryITests.java +++ b/spring-session-data-redis/src/integration-test/java/org/springframework/session/data/redis/SimpleRedisOperationsSessionRepositoryITests.java @@ -56,10 +56,9 @@ class SimpleRedisOperationsSessionRepositoryITests extends AbstractRedisITests { @Test void save_NewSession_ShouldSaveSession() { RedisSession session = createAndSaveSession(Instant.now()); - assertThat(session.getMaxInactiveInterval()).isEqualTo( - Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS)); - assertThat(session.getAttributeNames()) - .isEqualTo(Collections.singleton("attribute1")); + assertThat(session.getMaxInactiveInterval()) + .isEqualTo(Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS)); + assertThat(session.getAttributeNames()).isEqualTo(Collections.singleton("attribute1")); assertThat(session.getAttribute("attribute1")).isEqualTo("value1"); } @@ -72,8 +71,7 @@ class SimpleRedisOperationsSessionRepositoryITests extends AbstractRedisITests { void save_DeletedSession_ShouldThrowException() { RedisSession session = createAndSaveSession(Instant.now()); this.sessionRepository.deleteById(session.getId()); - assertThatIllegalStateException() - .isThrownBy(() -> this.sessionRepository.save(session)) + assertThatIllegalStateException().isThrownBy(() -> this.sessionRepository.save(session)) .withMessage("Session was invalidated"); } @@ -164,8 +162,7 @@ class SimpleRedisOperationsSessionRepositoryITests extends AbstractRedisITests { this.sessionRepository.deleteById(originalSessionId); updateSession(session, Instant.now(), "attribute1", "value1"); String newSessionId = session.changeSessionId(); - assertThatIllegalStateException() - .isThrownBy(() -> this.sessionRepository.save(session)) + assertThatIllegalStateException().isThrownBy(() -> this.sessionRepository.save(session)) .withMessage("Session was invalidated"); assertThat(this.sessionRepository.findById(newSessionId)).isNull(); assertThat(this.sessionRepository.findById(originalSessionId)).isNull(); @@ -182,8 +179,7 @@ class SimpleRedisOperationsSessionRepositoryITests extends AbstractRedisITests { this.sessionRepository.save(copy1); updateSession(copy2, now.plusSeconds(2L), "attribute3", "value3"); String newSessionId2 = copy2.changeSessionId(); - assertThatIllegalStateException() - .isThrownBy(() -> this.sessionRepository.save(copy2)) + assertThatIllegalStateException().isThrownBy(() -> this.sessionRepository.save(copy2)) .withMessage("Session was invalidated"); assertThat(this.sessionRepository.findById(newSessionId1)).isNotNull(); assertThat(this.sessionRepository.findById(newSessionId2)).isNull(); @@ -220,8 +216,8 @@ class SimpleRedisOperationsSessionRepositoryITests extends AbstractRedisITests { return this.sessionRepository.findById(session.getId()); } - private static void updateSession(RedisSession session, Instant lastAccessedTime, - String attributeName, Object attributeValue) { + private static void updateSession(RedisSession session, Instant lastAccessedTime, String attributeName, + Object attributeValue) { session.setLastAccessedTime(lastAccessedTime); session.setAttribute(attributeName, attributeValue); } @@ -231,8 +227,7 @@ class SimpleRedisOperationsSessionRepositoryITests extends AbstractRedisITests { static class Config extends BaseConfig { @Bean - public SimpleRedisOperationsSessionRepository sessionRepository( - RedisConnectionFactory redisConnectionFactory) { + public SimpleRedisOperationsSessionRepository sessionRepository(RedisConnectionFactory redisConnectionFactory) { RedisTemplate redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); redisTemplate.afterPropertiesSet(); diff --git a/spring-session-data-redis/src/integration-test/java/org/springframework/session/data/redis/config/annotation/web/http/EnableRedisHttpSessionExpireSessionDestroyedTests.java b/spring-session-data-redis/src/integration-test/java/org/springframework/session/data/redis/config/annotation/web/http/EnableRedisHttpSessionExpireSessionDestroyedTests.java index 45efcbaa..530f432b 100644 --- a/spring-session-data-redis/src/integration-test/java/org/springframework/session/data/redis/config/annotation/web/http/EnableRedisHttpSessionExpireSessionDestroyedTests.java +++ b/spring-session-data-redis/src/integration-test/java/org/springframework/session/data/redis/config/annotation/web/http/EnableRedisHttpSessionExpireSessionDestroyedTests.java @@ -44,8 +44,7 @@ import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(SpringExtension.class) @ContextConfiguration @WebAppConfiguration -public class EnableRedisHttpSessionExpireSessionDestroyedTests - extends AbstractRedisITests { +class EnableRedisHttpSessionExpireSessionDestroyedTests extends AbstractRedisITests { @Autowired private SessionRepository repository; @@ -56,16 +55,16 @@ public class EnableRedisHttpSessionExpireSessionDestroyedTests { + static class SessionExpiredEventRegistry implements ApplicationListener { + private boolean receivedEvent; + private Object lock; @Override @@ -109,6 +109,7 @@ public class EnableRedisHttpSessionExpireSessionDestroyedTests - extends AbstractRedisITests { +class RedisOperationsSessionRepositoryFlushImmediatelyITests extends AbstractRedisITests { @Autowired private SessionRepository sessionRepository; @Test - public void savesOnCreate() throws InterruptedException { + void savesOnCreate() throws InterruptedException { S created = this.sessionRepository.createSession(); S getSession = this.sessionRepository.findById(created.getId()); diff --git a/spring-session-data-redis/src/integration-test/java/org/springframework/session/data/redis/taskexecutor/RedisListenerContainerTaskExecutorITests.java b/spring-session-data-redis/src/integration-test/java/org/springframework/session/data/redis/taskexecutor/RedisListenerContainerTaskExecutorITests.java index 8b180b6c..218d9107 100644 --- a/spring-session-data-redis/src/integration-test/java/org/springframework/session/data/redis/taskexecutor/RedisListenerContainerTaskExecutorITests.java +++ b/spring-session-data-redis/src/integration-test/java/org/springframework/session/data/redis/taskexecutor/RedisListenerContainerTaskExecutorITests.java @@ -45,7 +45,7 @@ import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(SpringExtension.class) @ContextConfiguration @WebAppConfiguration -public class RedisListenerContainerTaskExecutorITests extends AbstractRedisITests { +class RedisListenerContainerTaskExecutorITests extends AbstractRedisITests { @Autowired private SessionTaskExecutor executor; @@ -54,10 +54,9 @@ public class RedisListenerContainerTaskExecutorITests extends AbstractRedisITest private RedisOperations redis; @Test - public void testRedisDelEventsAreDispatchedInSessionTaskExecutor() - throws InterruptedException { - BoundSetOperations ops = this.redis.boundSetOps( - "spring:session:RedisListenerContainerTaskExecutorITests:expirations:dummy"); + void testRedisDelEventsAreDispatchedInSessionTaskExecutor() throws InterruptedException { + BoundSetOperations ops = this.redis + .boundSetOps("spring:session:RedisListenerContainerTaskExecutorITests:expirations:dummy"); ops.add("value"); ops.remove("value"); assertThat(this.executor.taskDispatched()).isTrue(); @@ -65,6 +64,7 @@ public class RedisListenerContainerTaskExecutorITests extends AbstractRedisITest } static class SessionTaskExecutor implements TaskExecutor { + private Object lock = new Object(); private final Executor executor; @@ -97,6 +97,7 @@ public class RedisListenerContainerTaskExecutorITests extends AbstractRedisITest } return (this.taskDispatched != null) ? this.taskDispatched : Boolean.FALSE; } + } @Configuration diff --git a/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/ReactiveRedisOperationsSessionRepository.java b/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/ReactiveRedisOperationsSessionRepository.java index 0901e75a..6df1ecad 100644 --- a/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/ReactiveRedisOperationsSessionRepository.java +++ b/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/ReactiveRedisOperationsSessionRepository.java @@ -38,8 +38,8 @@ import org.springframework.util.Assert; * @author Vedran Pavic * @since 2.0 */ -public class ReactiveRedisOperationsSessionRepository implements - ReactiveSessionRepository { +public class ReactiveRedisOperationsSessionRepository + implements ReactiveSessionRepository { /** * The default namespace for each key and channel in Redis used by Spring Session. @@ -61,8 +61,7 @@ public class ReactiveRedisOperationsSessionRepository implements private RedisFlushMode redisFlushMode = RedisFlushMode.ON_SAVE; - public ReactiveRedisOperationsSessionRepository( - ReactiveRedisOperations sessionRedisOperations) { + public ReactiveRedisOperationsSessionRepository(ReactiveRedisOperations sessionRedisOperations) { Assert.notNull(sessionRedisOperations, "sessionRedisOperations cannot be null"); this.sessionRedisOperations = sessionRedisOperations; } @@ -76,7 +75,6 @@ public class ReactiveRedisOperationsSessionRepository implements * Sets the maximum inactive interval in seconds between requests before newly created * sessions will be invalidated. A negative time indicates that the session will never * timeout. The default is 1800 (30 minutes). - * * @param defaultMaxInactiveInterval the number of seconds that the {@link Session} * should be kept alive between client requests. */ @@ -86,7 +84,6 @@ public class ReactiveRedisOperationsSessionRepository implements /** * Sets the redis flush mode. Default flush mode is {@link RedisFlushMode#ON_SAVE}. - * * @param redisFlushMode the new redis flush mode */ public void setRedisFlushMode(RedisFlushMode redisFlushMode) { @@ -109,8 +106,7 @@ public class ReactiveRedisOperationsSessionRepository implements RedisSession session = new RedisSession(); if (this.defaultMaxInactiveInterval != null) { - session.setMaxInactiveInterval( - Duration.ofSeconds(this.defaultMaxInactiveInterval)); + session.setMaxInactiveInterval(Duration.ofSeconds(this.defaultMaxInactiveInterval)); } return Mono.just(session); @@ -122,12 +118,9 @@ public class ReactiveRedisOperationsSessionRepository implements if (session.isNew) { return session.save(); } - String sessionKey = getSessionKey( - session.hasChangedSessionId() ? session.originalSessionId - : session.getId()); - return this.sessionRedisOperations.hasKey(sessionKey).flatMap((exists) -> exists - ? session.save() - : Mono.error(new IllegalStateException("Session was invalidated"))); + String sessionKey = getSessionKey(session.hasChangedSessionId() ? session.originalSessionId : session.getId()); + return this.sessionRedisOperations.hasKey(sessionKey).flatMap( + (exists) -> exists ? session.save() : Mono.error(new IllegalStateException("Session was invalidated"))); } @Override @@ -182,19 +175,15 @@ public class ReactiveRedisOperationsSessionRepository implements */ RedisSession() { this(new MapSession()); - this.delta.put(RedisSessionMapper.CREATION_TIME_KEY, - getCreationTime().toEpochMilli()); - this.delta.put(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, - (int) getMaxInactiveInterval().getSeconds()); - this.delta.put(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, - getLastAccessedTime().toEpochMilli()); + this.delta.put(RedisSessionMapper.CREATION_TIME_KEY, getCreationTime().toEpochMilli()); + this.delta.put(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, (int) getMaxInactiveInterval().getSeconds()); + this.delta.put(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, getLastAccessedTime().toEpochMilli()); this.isNew = true; this.flushImmediateIfNecessary(); } /** * Creates a new instance from the provided {@link MapSession}. - * * @param mapSession the {@link MapSession} that represents the persisted session * that was retrieved. Cannot be null. */ @@ -244,8 +233,7 @@ public class ReactiveRedisOperationsSessionRepository implements @Override public void setLastAccessedTime(Instant lastAccessedTime) { this.cached.setLastAccessedTime(lastAccessedTime); - putAndFlush(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, - getLastAccessedTime().toEpochMilli()); + putAndFlush(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, getLastAccessedTime().toEpochMilli()); } @Override @@ -256,8 +244,7 @@ public class ReactiveRedisOperationsSessionRepository implements @Override public void setMaxInactiveInterval(Duration interval) { this.cached.setMaxInactiveInterval(interval); - putAndFlush(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, - (int) getMaxInactiveInterval().getSeconds()); + putAndFlush(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, (int) getMaxInactiveInterval().getSeconds()); } @Override @@ -286,8 +273,7 @@ public class ReactiveRedisOperationsSessionRepository implements } private Mono save() { - return Mono.defer(() -> saveChangeSessionId().then(saveDelta()) - .doOnSuccess((aVoid) -> this.isNew = false)); + return Mono.defer(() -> saveChangeSessionId().then(saveDelta()).doOnSuccess((aVoid) -> this.isNew = false)); } private Mono saveDelta() { @@ -296,8 +282,8 @@ public class ReactiveRedisOperationsSessionRepository implements } String sessionKey = getSessionKey(getId()); - Mono update = ReactiveRedisOperationsSessionRepository.this.sessionRedisOperations - .opsForHash().putAll(sessionKey, new HashMap<>(this.delta)); + Mono update = ReactiveRedisOperationsSessionRepository.this.sessionRedisOperations.opsForHash() + .putAll(sessionKey, new HashMap<>(this.delta)); Mono setTtl = ReactiveRedisOperationsSessionRepository.this.sessionRedisOperations .expire(sessionKey, getMaxInactiveInterval()); diff --git a/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/RedisFlushMode.java b/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/RedisFlushMode.java index adc12879..31b5b48a 100644 --- a/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/RedisFlushMode.java +++ b/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/RedisFlushMode.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,7 @@ import org.springframework.session.SessionRepository; * @since 1.1 */ public enum RedisFlushMode { + /** * Only writes to Redis when * {@link SessionRepository#save(org.springframework.session.Session)} is invoked. In @@ -39,4 +40,5 @@ public enum RedisFlushMode { * immediately. */ IMMEDIATE + } diff --git a/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/RedisOperationsSessionRepository.java b/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/RedisOperationsSessionRepository.java index 2201817e..49cd8601 100644 --- a/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/RedisOperationsSessionRepository.java +++ b/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/RedisOperationsSessionRepository.java @@ -72,8 +72,8 @@ import org.springframework.util.Assert; * *

    * For additional information on how to create a RedisTemplate, refer to the - * - * Spring Data Redis Reference. + * Spring Data Redis Reference. *

    * *

    Storage Details

    @@ -123,10 +123,12 @@ import org.springframework.util.Assert; *

    Optimized Writes

    * *

    - * The {@link org.springframework.session.data.redis.RedisOperationsSessionRepository.RedisSession} keeps track of the properties that have changed and only - * updates those. This means if an attribute is written once and read many times we only - * need to write that attribute once. For example, assume the session attribute - * "sessionAttr2" from earlier was updated. The following would be executed upon saving: + * The + * {@link org.springframework.session.data.redis.RedisOperationsSessionRepository.RedisSession} + * keeps track of the properties that have changed and only updates those. This means if + * an attribute is written once and read many times we only need to write that attribute + * once. For example, assume the session attribute "sessionAttr2" from earlier was + * updated. The following would be executed upon saving: *

    * *
    @@ -170,15 +172,14 @@ import org.springframework.util.Assert;
      * 

    * *

    - * NOTE: The {@link #findById(String)} method ensures that no expired sessions - * will be returned. This means there is no need to check the expiration before using a - * session + * NOTE: The {@link #findById(String)} method ensures that no expired sessions will + * be returned. This means there is no need to check the expiration before using a session *

    * *

    * Spring Session relies on the expired and delete - * keyspace notifications from Redis to - * fire a SessionDestroyedEvent. It is the SessionDestroyedEvent that ensures resources + * keyspace notifications from Redis + * to fire a SessionDestroyedEvent. It is the SessionDestroyedEvent that ensures resources * associated with the Session are cleaned up. For example, when using Spring Session's * WebSocket support the Redis expired or delete event is what triggers any WebSocket * connections associated with the session to be closed. @@ -244,11 +245,10 @@ import org.springframework.util.Assert; * @author Vedran Pavic * @since 1.0 */ -public class RedisOperationsSessionRepository implements - FindByIndexNameSessionRepository, - MessageListener { - private static final Log logger = LogFactory - .getLog(RedisOperationsSessionRepository.class); +public class RedisOperationsSessionRepository + implements FindByIndexNameSessionRepository, MessageListener { + + private static final Log logger = LogFactory.getLog(RedisOperationsSessionRepository.class); private static final String SPRING_SECURITY_CONTEXT = "SPRING_SECURITY_CONTEXT"; @@ -303,16 +303,14 @@ public class RedisOperationsSessionRepository implements /** * Creates a new instance. For an example, refer to the class level javadoc. - * * @param sessionRedisOperations the {@link RedisOperations} to use for managing the * sessions. Cannot be null. */ - public RedisOperationsSessionRepository( - RedisOperations sessionRedisOperations) { + public RedisOperationsSessionRepository(RedisOperations sessionRedisOperations) { Assert.notNull(sessionRedisOperations, "sessionRedisOperations cannot be null"); this.sessionRedisOperations = sessionRedisOperations; - this.expirationPolicy = new RedisSessionExpirationPolicy(sessionRedisOperations, - this::getExpirationsKey, this::getSessionKey); + this.expirationPolicy = new RedisSessionExpirationPolicy(sessionRedisOperations, this::getExpirationsKey, + this::getSessionKey); configureSessionChannels(); } @@ -320,14 +318,11 @@ public class RedisOperationsSessionRepository implements * Sets the {@link ApplicationEventPublisher} that is used to publish * {@link SessionDestroyedEvent}. The default is to not publish a * {@link SessionDestroyedEvent}. - * * @param applicationEventPublisher the {@link ApplicationEventPublisher} that is used * to publish {@link SessionDestroyedEvent}. Cannot be null. */ - public void setApplicationEventPublisher( - ApplicationEventPublisher applicationEventPublisher) { - Assert.notNull(applicationEventPublisher, - "applicationEventPublisher cannot be null"); + public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { + Assert.notNull(applicationEventPublisher, "applicationEventPublisher cannot be null"); this.eventPublisher = applicationEventPublisher; } @@ -335,7 +330,6 @@ public class RedisOperationsSessionRepository implements * Sets the maximum inactive interval in seconds between requests before newly created * sessions will be invalidated. A negative time indicates that the session will never * timeout. The default is 1800 (30 minutes). - * * @param defaultMaxInactiveInterval the number of seconds that the {@link Session} * should be kept alive between client requests. */ @@ -346,7 +340,6 @@ public class RedisOperationsSessionRepository implements /** * Sets the default redis serializer. Replaces default serializer which is based on * {@link JdkSerializationRedisSerializer}. - * * @param defaultSerializer the new default redis serializer */ public void setDefaultSerializer(RedisSerializer defaultSerializer) { @@ -356,7 +349,6 @@ public class RedisOperationsSessionRepository implements /** * Sets the redis flush mode. Default flush mode is {@link RedisFlushMode#ON_SAVE}. - * * @param redisFlushMode the new redis flush mode */ public void setRedisFlushMode(RedisFlushMode redisFlushMode) { @@ -374,8 +366,7 @@ public class RedisOperationsSessionRepository implements } private void configureSessionChannels() { - this.sessionCreatedChannelPrefix = this.namespace + "event:" + this.database - + ":created:"; + this.sessionCreatedChannelPrefix = this.namespace + "event:" + this.database + ":created:"; this.sessionDeletedChannel = "__keyevent@" + this.database + "__:del"; this.sessionExpiredChannel = "__keyevent@" + this.database + "__:expired"; } @@ -409,16 +400,13 @@ public class RedisOperationsSessionRepository implements } @Override - public Map findByIndexNameAndIndexValue(String indexName, - String indexValue) { + public Map findByIndexNameAndIndexValue(String indexName, String indexValue) { if (!PRINCIPAL_NAME_INDEX_NAME.equals(indexName)) { return Collections.emptyMap(); } String principalKey = getPrincipalKey(indexValue); - Set sessionIds = this.sessionRedisOperations.boundSetOps(principalKey) - .members(); - Map sessions = new HashMap<>( - sessionIds.size()); + Set sessionIds = this.sessionRedisOperations.boundSetOps(principalKey).members(); + Map sessions = new HashMap<>(sessionIds.size()); for (Object id : sessionIds) { RedisSession session = findById((String) id); if (session != null) { @@ -463,9 +451,7 @@ public class RedisOperationsSessionRepository implements loaded.setLastAccessedTime(Instant.ofEpochMilli((long) entry.getValue())); } else if (key.startsWith(RedisSessionMapper.ATTRIBUTE_PREFIX)) { - loaded.setAttribute( - key.substring(RedisSessionMapper.ATTRIBUTE_PREFIX.length()), - entry.getValue()); + loaded.setAttribute(key.substring(RedisSessionMapper.ATTRIBUTE_PREFIX.length()), entry.getValue()); } } return loaded; @@ -490,10 +476,8 @@ public class RedisOperationsSessionRepository implements @Override public RedisSession createSession() { - Duration maxInactiveInterval = Duration - .ofSeconds((this.defaultMaxInactiveInterval != null) - ? this.defaultMaxInactiveInterval - : MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS); + Duration maxInactiveInterval = Duration.ofSeconds((this.defaultMaxInactiveInterval != null) + ? this.defaultMaxInactiveInterval : MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS); RedisSession session = new RedisSession(maxInactiveInterval); session.flushImmediateIfNecessary(); return session; @@ -509,8 +493,7 @@ public class RedisOperationsSessionRepository implements if (channel.startsWith(this.sessionCreatedChannelPrefix)) { // TODO: is this thread safe? - Map loaded = (Map) this.defaultSerializer - .deserialize(message.getBody()); + Map loaded = (Map) this.defaultSerializer.deserialize(message.getBody()); handleCreated(loaded, channel); return; } @@ -529,8 +512,7 @@ public class RedisOperationsSessionRepository implements RedisSession session = getSession(sessionId, true); if (session == null) { - logger.warn("Unable to publish SessionDestroyedEvent for session " - + sessionId); + logger.warn("Unable to publish SessionDestroyedEvent for session " + sessionId); return; } @@ -553,8 +535,7 @@ public class RedisOperationsSessionRepository implements String sessionId = session.getId(); String principal = PRINCIPAL_NAME_RESOLVER.resolvePrincipal(session); if (principal != null) { - this.sessionRedisOperations.boundSetOps(getPrincipalKey(principal)) - .remove(sessionId); + this.sessionRedisOperations.boundSetOps(getPrincipalKey(principal)).remove(sessionId); } } @@ -589,7 +570,6 @@ public class RedisOperationsSessionRepository implements /** * Gets the Hash key for this session by prefixing it appropriately. - * * @param sessionId the session id * @return the Hash key for this session by prefixing it appropriately. */ @@ -598,8 +578,7 @@ public class RedisOperationsSessionRepository implements } String getPrincipalKey(String principalName) { - return this.namespace + "index:" - + FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME + ":" + return this.namespace + "index:" + FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME + ":" + principalName; } @@ -650,15 +629,13 @@ public class RedisOperationsSessionRepository implements * @param sessionId the id of the {@link Session} to work with * @return the {@link BoundHashOperations} to operate on a {@link Session} */ - private BoundHashOperations getSessionBoundHashOperations( - String sessionId) { + private BoundHashOperations getSessionBoundHashOperations(String sessionId) { String key = getSessionKey(sessionId); return this.sessionRedisOperations.boundHashOps(key); } /** * Gets the key for the specified session attribute. - * * @param attributeName the attribute name * @return the attribute key name */ @@ -676,35 +653,36 @@ public class RedisOperationsSessionRepository implements * @since 1.0 */ final class RedisSession implements Session { + private final MapSession cached; + private Instant originalLastAccessTime; + private Map delta = new HashMap<>(); + private boolean isNew; + private String originalPrincipalName; + private String originalSessionId; /** * Creates a new instance ensuring to mark all of the new attributes to be * persisted in the next save operation. - * * @param maxInactiveInterval the amount of time that the {@link Session} should * be kept alive between client requests. */ RedisSession(Duration maxInactiveInterval) { this(new MapSession()); this.cached.setMaxInactiveInterval(maxInactiveInterval); - this.delta.put(RedisSessionMapper.CREATION_TIME_KEY, - getCreationTime().toEpochMilli()); - this.delta.put(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, - (int) getMaxInactiveInterval().getSeconds()); - this.delta.put(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, - getLastAccessedTime().toEpochMilli()); + this.delta.put(RedisSessionMapper.CREATION_TIME_KEY, getCreationTime().toEpochMilli()); + this.delta.put(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, (int) getMaxInactiveInterval().getSeconds()); + this.delta.put(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, getLastAccessedTime().toEpochMilli()); this.isNew = true; } /** * Creates a new instance from the provided {@link MapSession}. - * * @param cached the {@link MapSession} that represents the persisted session that * was retrieved. Cannot be null. */ @@ -722,8 +700,7 @@ public class RedisOperationsSessionRepository implements @Override public void setLastAccessedTime(Instant lastAccessedTime) { this.cached.setLastAccessedTime(lastAccessedTime); - this.putAndFlush(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, - getLastAccessedTime().toEpochMilli()); + this.putAndFlush(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, getLastAccessedTime().toEpochMilli()); } @Override @@ -758,8 +735,7 @@ public class RedisOperationsSessionRepository implements @Override public void setMaxInactiveInterval(Duration interval) { this.cached.setMaxInactiveInterval(interval); - this.putAndFlush(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, - (int) getMaxInactiveInterval().getSeconds()); + this.putAndFlush(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, (int) getMaxInactiveInterval().getSeconds()); } @Override @@ -817,33 +793,27 @@ public class RedisOperationsSessionRepository implements getSessionBoundHashOperations(sessionId).putAll(this.delta); String principalSessionKey = getSessionAttrNameKey( FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME); - String securityPrincipalSessionKey = getSessionAttrNameKey( - SPRING_SECURITY_CONTEXT); - if (this.delta.containsKey(principalSessionKey) - || this.delta.containsKey(securityPrincipalSessionKey)) { + String securityPrincipalSessionKey = getSessionAttrNameKey(SPRING_SECURITY_CONTEXT); + if (this.delta.containsKey(principalSessionKey) || this.delta.containsKey(securityPrincipalSessionKey)) { if (this.originalPrincipalName != null) { - String originalPrincipalRedisKey = getPrincipalKey( - this.originalPrincipalName); - RedisOperationsSessionRepository.this.sessionRedisOperations - .boundSetOps(originalPrincipalRedisKey).remove(sessionId); + String originalPrincipalRedisKey = getPrincipalKey(this.originalPrincipalName); + RedisOperationsSessionRepository.this.sessionRedisOperations.boundSetOps(originalPrincipalRedisKey) + .remove(sessionId); } String principal = PRINCIPAL_NAME_RESOLVER.resolvePrincipal(this); this.originalPrincipalName = principal; if (principal != null) { String principalRedisKey = getPrincipalKey(principal); - RedisOperationsSessionRepository.this.sessionRedisOperations - .boundSetOps(principalRedisKey).add(sessionId); + RedisOperationsSessionRepository.this.sessionRedisOperations.boundSetOps(principalRedisKey) + .add(sessionId); } } this.delta = new HashMap<>(this.delta.size()); Long originalExpiration = (this.originalLastAccessTime != null) - ? this.originalLastAccessTime.plus(getMaxInactiveInterval()) - .toEpochMilli() - : null; - RedisOperationsSessionRepository.this.expirationPolicy - .onExpirationUpdated(originalExpiration, this); + ? this.originalLastAccessTime.plus(getMaxInactiveInterval()).toEpochMilli() : null; + RedisOperationsSessionRepository.this.expirationPolicy.onExpirationUpdated(originalExpiration, this); } private void saveChangeSessionId() { @@ -855,8 +825,8 @@ public class RedisOperationsSessionRepository implements String originalSessionIdKey = getSessionKey(this.originalSessionId); String sessionIdKey = getSessionKey(sessionId); try { - RedisOperationsSessionRepository.this.sessionRedisOperations - .rename(originalSessionIdKey, sessionIdKey); + RedisOperationsSessionRepository.this.sessionRedisOperations.rename(originalSessionIdKey, + sessionIdKey); } catch (NonTransientDataAccessException ex) { handleErrNoSuchKeyError(ex); @@ -864,8 +834,7 @@ public class RedisOperationsSessionRepository implements String originalExpiredKey = getExpiredKey(this.originalSessionId); String expiredKey = getExpiredKey(sessionId); try { - RedisOperationsSessionRepository.this.sessionRedisOperations - .rename(originalExpiredKey, expiredKey); + RedisOperationsSessionRepository.this.sessionRedisOperations.rename(originalExpiredKey, expiredKey); } catch (NonTransientDataAccessException ex) { handleErrNoSuchKeyError(ex); @@ -875,8 +844,7 @@ public class RedisOperationsSessionRepository implements } private void handleErrNoSuchKeyError(NonTransientDataAccessException ex) { - if (!"ERR no such key" - .equals(NestedExceptionUtils.getMostSpecificCause(ex).getMessage())) { + if (!"ERR no such key".equals(NestedExceptionUtils.getMostSpecificCause(ex).getMessage())) { throw ex; } } @@ -887,6 +855,7 @@ public class RedisOperationsSessionRepository implements * Principal name resolver helper class. */ static class PrincipalNameResolver { + private SpelExpressionParser parser = new SpelExpressionParser(); public String resolvePrincipal(Session session) { @@ -896,12 +865,12 @@ public class RedisOperationsSessionRepository implements } Object authentication = session.getAttribute(SPRING_SECURITY_CONTEXT); if (authentication != null) { - Expression expression = this.parser - .parseExpression("authentication?.name"); + Expression expression = this.parser.parseExpression("authentication?.name"); return expression.getValue(authentication, String.class); } return null; } } + } diff --git a/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/RedisSessionExpirationPolicy.java b/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/RedisSessionExpirationPolicy.java index 0499c638..4465fcf7 100644 --- a/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/RedisSessionExpirationPolicy.java +++ b/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/RedisSessionExpirationPolicy.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,11 +48,12 @@ import org.springframework.session.data.redis.RedisOperationsSessionRepository.R */ final class RedisSessionExpirationPolicy { - private static final Log logger = LogFactory - .getLog(RedisSessionExpirationPolicy.class); + private static final Log logger = LogFactory.getLog(RedisSessionExpirationPolicy.class); private final RedisOperations redis; + private final Function lookupExpirationKey; + private final Function lookupSessionKey; RedisSessionExpirationPolicy(RedisOperations sessionRedisOperations, @@ -92,12 +93,10 @@ final class RedisSessionExpirationPolicy { } String expireKey = getExpirationKey(toExpire); - BoundSetOperations expireOperations = this.redis - .boundSetOps(expireKey); + BoundSetOperations expireOperations = this.redis.boundSetOps(expireKey); expireOperations.add(keyToExpire); - long fiveMinutesAfterExpires = sessionExpireInSeconds - + TimeUnit.MINUTES.toSeconds(5); + long fiveMinutesAfterExpires = sessionExpireInSeconds + TimeUnit.MINUTES.toSeconds(5); expireOperations.expire(fiveMinutesAfterExpires, TimeUnit.SECONDS); if (sessionExpireInSeconds == 0) { @@ -105,11 +104,9 @@ final class RedisSessionExpirationPolicy { } else { this.redis.boundValueOps(sessionKey).append(""); - this.redis.boundValueOps(sessionKey).expire(sessionExpireInSeconds, - TimeUnit.SECONDS); + this.redis.boundValueOps(sessionKey).expire(sessionExpireInSeconds, TimeUnit.SECONDS); } - this.redis.boundHashOps(getSessionKey(session.getId())) - .expire(fiveMinutesAfterExpires, TimeUnit.SECONDS); + this.redis.boundHashOps(getSessionKey(session.getId())).expire(fiveMinutesAfterExpires, TimeUnit.SECONDS); } String getExpirationKey(long expires) { @@ -141,7 +138,6 @@ final class RedisSessionExpirationPolicy { * By trying to access the session we only trigger a deletion if it the TTL is * expired. This is done to handle * https://github.com/spring-projects/spring-session/issues/93 - * * @param key the key */ private void touch(String key) { @@ -171,4 +167,5 @@ final class RedisSessionExpirationPolicy { date.clear(Calendar.MILLISECOND); return date.getTimeInMillis(); } + } diff --git a/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/SimpleRedisOperationsSessionRepository.java b/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/SimpleRedisOperationsSessionRepository.java index 3eb0829a..75fac9e4 100644 --- a/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/SimpleRedisOperationsSessionRepository.java +++ b/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/SimpleRedisOperationsSessionRepository.java @@ -38,15 +38,14 @@ import org.springframework.util.Assert; * @author Vedran Pavic * @since 2.2.0 */ -public class SimpleRedisOperationsSessionRepository implements - SessionRepository { +public class SimpleRedisOperationsSessionRepository + implements SessionRepository { private static final String DEFAULT_KEY_NAMESPACE = "spring:session:"; private final RedisOperations sessionRedisOperations; - private Duration defaultMaxInactiveInterval = Duration - .ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS); + private Duration defaultMaxInactiveInterval = Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS); private String keyNamespace = DEFAULT_KEY_NAMESPACE; @@ -55,10 +54,9 @@ public class SimpleRedisOperationsSessionRepository implements /** * Create a new {@link SimpleRedisOperationsSessionRepository} instance. * @param sessionRedisOperations the {@link RedisOperations} to use for managing - * sessions + * sessions */ - public SimpleRedisOperationsSessionRepository( - RedisOperations sessionRedisOperations) { + public SimpleRedisOperationsSessionRepository(RedisOperations sessionRedisOperations) { Assert.notNull(sessionRedisOperations, "sessionRedisOperations mut not be null"); this.sessionRedisOperations = sessionRedisOperations; } @@ -68,8 +66,7 @@ public class SimpleRedisOperationsSessionRepository implements * @param defaultMaxInactiveInterval the default maxInactiveInterval */ public void setDefaultMaxInactiveInterval(Duration defaultMaxInactiveInterval) { - Assert.notNull(defaultMaxInactiveInterval, - "defaultMaxInactiveInterval must not be null"); + Assert.notNull(defaultMaxInactiveInterval, "defaultMaxInactiveInterval must not be null"); this.defaultMaxInactiveInterval = defaultMaxInactiveInterval; } @@ -101,9 +98,7 @@ public class SimpleRedisOperationsSessionRepository implements @Override public void save(RedisSession session) { if (!session.isNew) { - String key = getSessionKey( - session.hasChangedSessionId() ? session.originalSessionId - : session.getId()); + String key = getSessionKey(session.hasChangedSessionId() ? session.originalSessionId : session.getId()); Boolean sessionExists = this.sessionRedisOperations.hasKey(key); if (sessionExists == null || !sessionExists) { throw new IllegalStateException("Session was invalidated"); @@ -115,8 +110,7 @@ public class SimpleRedisOperationsSessionRepository implements @Override public RedisSession findById(String sessionId) { String key = getSessionKey(sessionId); - Map entries = this.sessionRedisOperations - .opsForHash().entries(key); + Map entries = this.sessionRedisOperations.opsForHash().entries(key); if (entries.isEmpty()) { return null; } @@ -162,12 +156,9 @@ public class SimpleRedisOperationsSessionRepository implements RedisSession(Duration maxInactiveInterval) { this(new MapSession()); this.cached.setMaxInactiveInterval(maxInactiveInterval); - this.delta.put(RedisSessionMapper.CREATION_TIME_KEY, - getCreationTime().toEpochMilli()); - this.delta.put(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, - (int) getMaxInactiveInterval().getSeconds()); - this.delta.put(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, - getLastAccessedTime().toEpochMilli()); + this.delta.put(RedisSessionMapper.CREATION_TIME_KEY, getCreationTime().toEpochMilli()); + this.delta.put(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, (int) getMaxInactiveInterval().getSeconds()); + this.delta.put(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, getLastAccessedTime().toEpochMilli()); this.isNew = true; } @@ -199,8 +190,7 @@ public class SimpleRedisOperationsSessionRepository implements @Override public void setAttribute(String attributeName, Object attributeValue) { this.cached.setAttribute(attributeName, attributeValue); - putAttribute(RedisSessionMapper.ATTRIBUTE_PREFIX + attributeName, - attributeValue); + putAttribute(RedisSessionMapper.ATTRIBUTE_PREFIX + attributeName, attributeValue); } @Override @@ -216,8 +206,7 @@ public class SimpleRedisOperationsSessionRepository implements @Override public void setLastAccessedTime(Instant lastAccessedTime) { this.cached.setLastAccessedTime(lastAccessedTime); - putAttribute(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, - getLastAccessedTime().toEpochMilli()); + putAttribute(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, getLastAccessedTime().toEpochMilli()); } @Override @@ -228,8 +217,7 @@ public class SimpleRedisOperationsSessionRepository implements @Override public void setMaxInactiveInterval(Duration interval) { this.cached.setMaxInactiveInterval(interval); - putAttribute(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, - (int) getMaxInactiveInterval().getSeconds()); + putAttribute(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, (int) getMaxInactiveInterval().getSeconds()); } @Override @@ -265,8 +253,8 @@ public class SimpleRedisOperationsSessionRepository implements if (!this.isNew) { String originalSessionIdKey = getSessionKey(this.originalSessionId); String sessionIdKey = getSessionKey(getId()); - SimpleRedisOperationsSessionRepository.this.sessionRedisOperations - .rename(originalSessionIdKey, sessionIdKey); + SimpleRedisOperationsSessionRepository.this.sessionRedisOperations.rename(originalSessionIdKey, + sessionIdKey); } this.originalSessionId = getId(); } @@ -277,13 +265,11 @@ public class SimpleRedisOperationsSessionRepository implements return; } String key = getSessionKey(getId()); - SimpleRedisOperationsSessionRepository.this.sessionRedisOperations - .opsForHash().putAll(key, new HashMap<>(this.delta)); - SimpleRedisOperationsSessionRepository.this.sessionRedisOperations - .expireAt(key, - Date.from(Instant - .ofEpochMilli(getLastAccessedTime().toEpochMilli()) - .plusSeconds(getMaxInactiveInterval().getSeconds()))); + SimpleRedisOperationsSessionRepository.this.sessionRedisOperations.opsForHash().putAll(key, + new HashMap<>(this.delta)); + SimpleRedisOperationsSessionRepository.this.sessionRedisOperations.expireAt(key, + Date.from(Instant.ofEpochMilli(getLastAccessedTime().toEpochMilli()) + .plusSeconds(getMaxInactiveInterval().getSeconds()))); this.delta.clear(); } diff --git a/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/config/annotation/SpringSessionRedisConnectionFactory.java b/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/config/annotation/SpringSessionRedisConnectionFactory.java index ed2cd7e5..6ec11fa6 100644 --- a/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/config/annotation/SpringSessionRedisConnectionFactory.java +++ b/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/config/annotation/SpringSessionRedisConnectionFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,7 @@ import org.springframework.session.data.redis.RedisOperationsSessionRepository; * @author Vedran Pavic * @since 2.0.0 */ -@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, - ElementType.ANNOTATION_TYPE }) +@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented @Qualifier diff --git a/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/config/annotation/SpringSessionRedisOperations.java b/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/config/annotation/SpringSessionRedisOperations.java index 828c7d99..69f7fdcb 100644 --- a/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/config/annotation/SpringSessionRedisOperations.java +++ b/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/config/annotation/SpringSessionRedisOperations.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,7 @@ import org.springframework.beans.factory.annotation.Value; * @see org.springframework.session.data.redis.ReactiveRedisOperationsSessionRepository#getSessionRedisOperations() * @since 2.0.0 */ -@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, - ElementType.ANNOTATION_TYPE }) +@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented @Value("#{sessionRepository.sessionRedisOperations}") diff --git a/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfiguration.java b/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfiguration.java index 470f164e..5d305206 100644 --- a/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfiguration.java +++ b/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfiguration.java @@ -75,8 +75,7 @@ import org.springframework.util.StringValueResolver; @Configuration(proxyBeanMethods = false) @EnableScheduling public class RedisHttpSessionConfiguration extends SpringHttpSessionConfiguration - implements BeanClassLoaderAware, EmbeddedValueResolverAware, ImportAware, - SchedulingConfigurer { + implements BeanClassLoaderAware, EmbeddedValueResolverAware, ImportAware, SchedulingConfigurer { static final String DEFAULT_CLEANUP_CRON = "0 * * * * *"; @@ -107,14 +106,12 @@ public class RedisHttpSessionConfiguration extends SpringHttpSessionConfiguratio @Bean public RedisOperationsSessionRepository sessionRepository() { RedisTemplate redisTemplate = createRedisTemplate(); - RedisOperationsSessionRepository sessionRepository = new RedisOperationsSessionRepository( - redisTemplate); + RedisOperationsSessionRepository sessionRepository = new RedisOperationsSessionRepository(redisTemplate); sessionRepository.setApplicationEventPublisher(this.applicationEventPublisher); if (this.defaultRedisSerializer != null) { sessionRepository.setDefaultSerializer(this.defaultRedisSerializer); } - sessionRepository - .setDefaultMaxInactiveInterval(this.maxInactiveIntervalInSeconds); + sessionRepository.setDefaultMaxInactiveInterval(this.maxInactiveIntervalInSeconds); if (StringUtils.hasText(this.redisNamespace)) { sessionRepository.setRedisKeyNamespace(this.redisNamespace); } @@ -136,19 +133,16 @@ public class RedisHttpSessionConfiguration extends SpringHttpSessionConfiguratio container.setSubscriptionExecutor(this.redisSubscriptionExecutor); } container.addMessageListener(sessionRepository, - Arrays.asList( - new ChannelTopic(sessionRepository.getSessionDeletedChannel()), + Arrays.asList(new ChannelTopic(sessionRepository.getSessionDeletedChannel()), new ChannelTopic(sessionRepository.getSessionExpiredChannel()))); container.addMessageListener(sessionRepository, - Collections.singletonList(new PatternTopic( - sessionRepository.getSessionCreatedChannelPrefix() + "*"))); + Collections.singletonList(new PatternTopic(sessionRepository.getSessionCreatedChannelPrefix() + "*"))); return container; } @Bean public InitializingBean enableRedisKeyspaceNotificationsInitializer() { - return new EnableRedisKeyspaceNotificationsInitializer( - this.redisConnectionFactory, this.configureRedisAction); + return new EnableRedisKeyspaceNotificationsInitializer(this.redisConnectionFactory, this.configureRedisAction); } public void setMaxInactiveIntervalInSeconds(int maxInactiveIntervalInSeconds) { @@ -170,7 +164,6 @@ public class RedisHttpSessionConfiguration extends SpringHttpSessionConfiguratio /** * Sets the action to perform for configuring Redis. - * * @param configureRedisAction the configureRedis to set. The default is * {@link ConfigureNotifyKeyspaceEventsAction}. */ @@ -183,8 +176,7 @@ public class RedisHttpSessionConfiguration extends SpringHttpSessionConfiguratio public void setRedisConnectionFactory( @SpringSessionRedisConnectionFactory ObjectProvider springSessionRedisConnectionFactory, ObjectProvider redisConnectionFactory) { - RedisConnectionFactory redisConnectionFactoryToUse = springSessionRedisConnectionFactory - .getIfAvailable(); + RedisConnectionFactory redisConnectionFactoryToUse = springSessionRedisConnectionFactory.getIfAvailable(); if (redisConnectionFactoryToUse == null) { redisConnectionFactoryToUse = redisConnectionFactory.getObject(); } @@ -193,14 +185,12 @@ public class RedisHttpSessionConfiguration extends SpringHttpSessionConfiguratio @Autowired(required = false) @Qualifier("springSessionDefaultRedisSerializer") - public void setDefaultRedisSerializer( - RedisSerializer defaultRedisSerializer) { + public void setDefaultRedisSerializer(RedisSerializer defaultRedisSerializer) { this.defaultRedisSerializer = defaultRedisSerializer; } @Autowired - public void setApplicationEventPublisher( - ApplicationEventPublisher applicationEventPublisher) { + public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.applicationEventPublisher = applicationEventPublisher; } @@ -231,12 +221,10 @@ public class RedisHttpSessionConfiguration extends SpringHttpSessionConfiguratio Map attributeMap = importMetadata .getAnnotationAttributes(EnableRedisHttpSession.class.getName()); AnnotationAttributes attributes = AnnotationAttributes.fromMap(attributeMap); - this.maxInactiveIntervalInSeconds = attributes - .getNumber("maxInactiveIntervalInSeconds"); + this.maxInactiveIntervalInSeconds = attributes.getNumber("maxInactiveIntervalInSeconds"); String redisNamespaceValue = attributes.getString("redisNamespace"); if (StringUtils.hasText(redisNamespaceValue)) { - this.redisNamespace = this.embeddedValueResolver - .resolveStringValue(redisNamespaceValue); + this.redisNamespace = this.embeddedValueResolver.resolveStringValue(redisNamespaceValue); } this.redisFlushMode = attributes.getEnum("redisFlushMode"); String cleanupCron = attributes.getString("cleanupCron"); @@ -247,8 +235,7 @@ public class RedisHttpSessionConfiguration extends SpringHttpSessionConfiguratio @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { - taskRegistrar.addCronTask(() -> sessionRepository().cleanupExpiredSessions(), - this.cleanupCron); + taskRegistrar.addCronTask(() -> sessionRepository().cleanupExpiredSessions(), this.cleanupCron); } private RedisTemplate createRedisTemplate() { @@ -289,8 +276,7 @@ public class RedisHttpSessionConfiguration extends SpringHttpSessionConfiguratio private ConfigureRedisAction configure; - EnableRedisKeyspaceNotificationsInitializer( - RedisConnectionFactory connectionFactory, + EnableRedisKeyspaceNotificationsInitializer(RedisConnectionFactory connectionFactory, ConfigureRedisAction configure) { this.connectionFactory = connectionFactory; this.configure = configure; @@ -310,8 +296,7 @@ public class RedisHttpSessionConfiguration extends SpringHttpSessionConfiguratio connection.close(); } catch (Exception ex) { - LogFactory.getLog(getClass()).error("Error closing RedisConnection", - ex); + LogFactory.getLog(getClass()).error("Error closing RedisConnection", ex); } } } diff --git a/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/config/annotation/web/server/RedisWebSessionConfiguration.java b/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/config/annotation/web/server/RedisWebSessionConfiguration.java index 34b858bd..f69e8b09 100644 --- a/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/config/annotation/web/server/RedisWebSessionConfiguration.java +++ b/spring-session-data-redis/src/main/java/org/springframework/session/data/redis/config/annotation/web/server/RedisWebSessionConfiguration.java @@ -76,8 +76,7 @@ public class RedisWebSessionConfiguration extends SpringWebSessionConfiguration ReactiveRedisTemplate reactiveRedisTemplate = createReactiveRedisTemplate(); ReactiveRedisOperationsSessionRepository sessionRepository = new ReactiveRedisOperationsSessionRepository( reactiveRedisTemplate); - sessionRepository - .setDefaultMaxInactiveInterval(this.maxInactiveIntervalInSeconds); + sessionRepository.setDefaultMaxInactiveInterval(this.maxInactiveIntervalInSeconds); if (StringUtils.hasText(this.redisNamespace)) { sessionRepository.setRedisKeyNamespace(this.redisNamespace); } @@ -112,8 +111,7 @@ public class RedisWebSessionConfiguration extends SpringWebSessionConfiguration @Autowired(required = false) @Qualifier("springSessionDefaultRedisSerializer") - public void setDefaultRedisSerializer( - RedisSerializer defaultRedisSerializer) { + public void setDefaultRedisSerializer(RedisSerializer defaultRedisSerializer) { this.defaultRedisSerializer = defaultRedisSerializer; } @@ -132,26 +130,22 @@ public class RedisWebSessionConfiguration extends SpringWebSessionConfiguration Map attributeMap = importMetadata .getAnnotationAttributes(EnableRedisWebSession.class.getName()); AnnotationAttributes attributes = AnnotationAttributes.fromMap(attributeMap); - this.maxInactiveIntervalInSeconds = attributes - .getNumber("maxInactiveIntervalInSeconds"); + this.maxInactiveIntervalInSeconds = attributes.getNumber("maxInactiveIntervalInSeconds"); String redisNamespaceValue = attributes.getString("redisNamespace"); if (StringUtils.hasText(redisNamespaceValue)) { - this.redisNamespace = this.embeddedValueResolver - .resolveStringValue(redisNamespaceValue); + this.redisNamespace = this.embeddedValueResolver.resolveStringValue(redisNamespaceValue); } this.redisFlushMode = attributes.getEnum("redisFlushMode"); } private ReactiveRedisTemplate createReactiveRedisTemplate() { RedisSerializer keySerializer = new StringRedisSerializer(); - RedisSerializer defaultSerializer = (this.defaultRedisSerializer != null) - ? this.defaultRedisSerializer + RedisSerializer defaultSerializer = (this.defaultRedisSerializer != null) ? this.defaultRedisSerializer : new JdkSerializationRedisSerializer(this.classLoader); RedisSerializationContext serializationContext = RedisSerializationContext - .newSerializationContext(defaultSerializer) - .key(keySerializer).hashKey(keySerializer).build(); - return new ReactiveRedisTemplate<>(this.redisConnectionFactory, - serializationContext); + .newSerializationContext(defaultSerializer).key(keySerializer).hashKey(keySerializer) + .build(); + return new ReactiveRedisTemplate<>(this.redisConnectionFactory, serializationContext); } } diff --git a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/ReactiveRedisOperationsSessionRepositoryTests.java b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/ReactiveRedisOperationsSessionRepositoryTests.java index 472e939f..8a572397 100644 --- a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/ReactiveRedisOperationsSessionRepositoryTests.java +++ b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/ReactiveRedisOperationsSessionRepositoryTests.java @@ -49,28 +49,24 @@ import static org.mockito.Mockito.verifyZeroInteractions; * * @author Vedran Pavic */ -public class ReactiveRedisOperationsSessionRepositoryTests { +class ReactiveRedisOperationsSessionRepositoryTests { @SuppressWarnings("unchecked") - private ReactiveRedisOperations redisOperations = mock( - ReactiveRedisOperations.class); + private ReactiveRedisOperations redisOperations = mock(ReactiveRedisOperations.class); @SuppressWarnings("unchecked") - private ReactiveHashOperations hashOperations = mock( - ReactiveHashOperations.class); + private ReactiveHashOperations hashOperations = mock(ReactiveHashOperations.class); @SuppressWarnings("unchecked") - private ArgumentCaptor> delta = ArgumentCaptor - .forClass(Map.class); + private ArgumentCaptor> delta = ArgumentCaptor.forClass(Map.class); private ReactiveRedisOperationsSessionRepository repository; private MapSession cached; @BeforeEach - public void setUp() { - this.repository = new ReactiveRedisOperationsSessionRepository( - this.redisOperations); + void setUp() { + this.repository = new ReactiveRedisOperationsSessionRepository(this.redisOperations); this.cached = new MapSession(); this.cached.setId("session-id"); @@ -79,82 +75,73 @@ public class ReactiveRedisOperationsSessionRepositoryTests { } @Test - public void constructorWithNullReactiveRedisOperations() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new ReactiveRedisOperationsSessionRepository(null)) + void constructorWithNullReactiveRedisOperations() { + assertThatIllegalArgumentException().isThrownBy(() -> new ReactiveRedisOperationsSessionRepository(null)) .withMessageContaining("sessionRedisOperations cannot be null"); } @Test - public void customRedisKeyNamespace() { + void customRedisKeyNamespace() { this.repository.setRedisKeyNamespace("test"); - assertThat(ReflectionTestUtils.getField(this.repository, "namespace")) - .isEqualTo("test:"); + assertThat(ReflectionTestUtils.getField(this.repository, "namespace")).isEqualTo("test:"); } @Test - public void nullRedisKeyNamespace() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.repository.setRedisKeyNamespace(null)) + void nullRedisKeyNamespace() { + assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setRedisKeyNamespace(null)) .withMessage("namespace cannot be null or empty"); } @Test - public void emptyRedisKeyNamespace() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.repository.setRedisKeyNamespace("")) + void emptyRedisKeyNamespace() { + assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setRedisKeyNamespace("")) .withMessage("namespace cannot be null or empty"); } @Test - public void customMaxInactiveInterval() { + void customMaxInactiveInterval() { this.repository.setDefaultMaxInactiveInterval(600); - assertThat(ReflectionTestUtils.getField(this.repository, - "defaultMaxInactiveInterval")).isEqualTo(600); + assertThat(ReflectionTestUtils.getField(this.repository, "defaultMaxInactiveInterval")).isEqualTo(600); } @Test - public void customRedisFlushMode() { + void customRedisFlushMode() { this.repository.setRedisFlushMode(RedisFlushMode.IMMEDIATE); - assertThat(ReflectionTestUtils.getField(this.repository, "redisFlushMode")) - .isEqualTo(RedisFlushMode.IMMEDIATE); + assertThat(ReflectionTestUtils.getField(this.repository, "redisFlushMode")).isEqualTo(RedisFlushMode.IMMEDIATE); } @Test - public void nullRedisFlushMode() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.repository.setRedisFlushMode(null)) + void nullRedisFlushMode() { + assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setRedisFlushMode(null)) .withMessage("redisFlushMode cannot be null"); } @Test - public void createSessionDefaultMaxInactiveInterval() { + void createSessionDefaultMaxInactiveInterval() { StepVerifier.create(this.repository.createSession()) .consumeNextWith((session) -> assertThat(session.getMaxInactiveInterval()) - .isEqualTo(Duration.ofSeconds( - MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS))) + .isEqualTo(Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS))) .verifyComplete(); } @Test - public void createSessionCustomMaxInactiveInterval() { + void createSessionCustomMaxInactiveInterval() { this.repository.setDefaultMaxInactiveInterval(600); StepVerifier.create(this.repository.createSession()) - .consumeNextWith((session) -> assertThat(session.getMaxInactiveInterval()) - .isEqualTo(Duration.ofSeconds(600))) + .consumeNextWith( + (session) -> assertThat(session.getMaxInactiveInterval()).isEqualTo(Duration.ofSeconds(600))) .verifyComplete(); } @Test - public void saveNewSession() { + void saveNewSession() { given(this.redisOperations.opsForHash()).willReturn(this.hashOperations); given(this.hashOperations.putAll(anyString(), any())).willReturn(Mono.just(true)); - given(this.redisOperations.expire(anyString(), any())) - .willReturn(Mono.just(true)); + given(this.redisOperations.expire(anyString(), any())).willReturn(Mono.just(true)); RedisSession newSession = this.repository.new RedisSession(); StepVerifier.create(this.repository.save(newSession)).verifyComplete(); @@ -176,13 +163,11 @@ public class ReactiveRedisOperationsSessionRepositoryTests { } @Test - public void saveSessionNothingChanged() { + void saveSessionNothingChanged() { given(this.redisOperations.hasKey(anyString())).willReturn(Mono.just(true)); - given(this.redisOperations.expire(anyString(), any())) - .willReturn(Mono.just(true)); + given(this.redisOperations.expire(anyString(), any())).willReturn(Mono.just(true)); - RedisSession session = this.repository.new RedisSession( - new MapSession(this.cached)); + RedisSession session = this.repository.new RedisSession(new MapSession(this.cached)); StepVerifier.create(this.repository.save(session)).verifyComplete(); @@ -192,12 +177,11 @@ public class ReactiveRedisOperationsSessionRepositoryTests { } @Test - public void saveLastAccessChanged() { + void saveLastAccessChanged() { given(this.redisOperations.hasKey(anyString())).willReturn(Mono.just(true)); given(this.redisOperations.opsForHash()).willReturn(this.hashOperations); given(this.hashOperations.putAll(anyString(), any())).willReturn(Mono.just(true)); - given(this.redisOperations.expire(anyString(), any())) - .willReturn(Mono.just(true)); + given(this.redisOperations.expire(anyString(), any())).willReturn(Mono.just(true)); RedisSession session = this.repository.new RedisSession(this.cached); session.setLastAccessedTime(Instant.ofEpochMilli(12345678L)); @@ -210,18 +194,16 @@ public class ReactiveRedisOperationsSessionRepositoryTests { verifyZeroInteractions(this.redisOperations); verifyZeroInteractions(this.hashOperations); - assertThat(this.delta.getAllValues().get(0)) - .isEqualTo(map(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, - session.getLastAccessedTime().toEpochMilli())); + assertThat(this.delta.getAllValues().get(0)).isEqualTo( + map(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, session.getLastAccessedTime().toEpochMilli())); } @Test - public void saveSetAttribute() { + void saveSetAttribute() { given(this.redisOperations.hasKey(anyString())).willReturn(Mono.just(true)); given(this.redisOperations.opsForHash()).willReturn(this.hashOperations); given(this.hashOperations.putAll(anyString(), any())).willReturn(Mono.just(true)); - given(this.redisOperations.expire(anyString(), any())) - .willReturn(Mono.just(true)); + given(this.redisOperations.expire(anyString(), any())).willReturn(Mono.just(true)); String attrName = "attrName"; RedisSession session = this.repository.new RedisSession(this.cached); @@ -236,17 +218,15 @@ public class ReactiveRedisOperationsSessionRepositoryTests { verifyZeroInteractions(this.hashOperations); assertThat(this.delta.getAllValues().get(0)).isEqualTo( - map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), - session.getAttribute(attrName))); + map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), session.getAttribute(attrName))); } @Test - public void saveRemoveAttribute() { + void saveRemoveAttribute() { given(this.redisOperations.hasKey(anyString())).willReturn(Mono.just(true)); given(this.redisOperations.opsForHash()).willReturn(this.hashOperations); given(this.hashOperations.putAll(anyString(), any())).willReturn(Mono.just(true)); - given(this.redisOperations.expire(anyString(), any())) - .willReturn(Mono.just(true)); + given(this.redisOperations.expire(anyString(), any())).willReturn(Mono.just(true)); String attrName = "attrName"; RedisSession session = this.repository.new RedisSession(new MapSession()); @@ -260,12 +240,12 @@ public class ReactiveRedisOperationsSessionRepositoryTests { verifyZeroInteractions(this.redisOperations); verifyZeroInteractions(this.hashOperations); - assertThat(this.delta.getAllValues().get(0)).isEqualTo(map( - RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), null)); + assertThat(this.delta.getAllValues().get(0)) + .isEqualTo(map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), null)); } @Test - public void redisSessionGetAttributes() { + void redisSessionGetAttributes() { String attrName = "attrName"; RedisSession session = this.repository.new RedisSession(this.cached); assertThat(session.getAttributeNames()).isEmpty(); @@ -278,7 +258,7 @@ public class ReactiveRedisOperationsSessionRepositoryTests { } @Test - public void delete() { + void delete() { given(this.redisOperations.delete(anyString())).willReturn(Mono.just(1L)); StepVerifier.create(this.repository.deleteById("test")).verifyComplete(); @@ -289,7 +269,7 @@ public class ReactiveRedisOperationsSessionRepositoryTests { } @Test - public void getSessionNotFound() { + void getSessionNotFound() { given(this.redisOperations.opsForHash()).willReturn(this.hashOperations); given(this.hashOperations.entries(anyString())).willReturn(Flux.empty()); given(this.redisOperations.delete(anyString())).willReturn(Mono.just(0L)); @@ -305,7 +285,7 @@ public class ReactiveRedisOperationsSessionRepositoryTests { @Test @SuppressWarnings("unchecked") - public void getSessionFound() { + void getSessionFound() { given(this.redisOperations.opsForHash()).willReturn(this.hashOperations); String attribute1 = "attribute1"; String attribute2 = "attribute2"; @@ -313,54 +293,38 @@ public class ReactiveRedisOperationsSessionRepositoryTests { expected.setLastAccessedTime(Instant.now().minusSeconds(60)); expected.setAttribute(attribute1, "test"); expected.setAttribute(attribute2, null); - Map map = map(RedisSessionMapper.ATTRIBUTE_PREFIX + attribute1, - expected.getAttribute(attribute1), - RedisSessionMapper.ATTRIBUTE_PREFIX + attribute2, - expected.getAttribute(attribute2), RedisSessionMapper.CREATION_TIME_KEY, - expected.getCreationTime().toEpochMilli(), - RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, - (int) expected.getMaxInactiveInterval().getSeconds(), - RedisSessionMapper.LAST_ACCESSED_TIME_KEY, - expected.getLastAccessedTime().toEpochMilli()); - given(this.hashOperations.entries(anyString())) - .willReturn(Flux.fromIterable(map.entrySet())); + Map map = map(RedisSessionMapper.ATTRIBUTE_PREFIX + attribute1, expected.getAttribute(attribute1), + RedisSessionMapper.ATTRIBUTE_PREFIX + attribute2, expected.getAttribute(attribute2), + RedisSessionMapper.CREATION_TIME_KEY, expected.getCreationTime().toEpochMilli(), + RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, (int) expected.getMaxInactiveInterval().getSeconds(), + RedisSessionMapper.LAST_ACCESSED_TIME_KEY, expected.getLastAccessedTime().toEpochMilli()); + given(this.hashOperations.entries(anyString())).willReturn(Flux.fromIterable(map.entrySet())); - StepVerifier.create(this.repository.findById("test")) - .consumeNextWith((session) -> { - verify(this.redisOperations).opsForHash(); - verify(this.hashOperations).entries(anyString()); - verifyZeroInteractions(this.redisOperations); - verifyZeroInteractions(this.hashOperations); + StepVerifier.create(this.repository.findById("test")).consumeNextWith((session) -> { + verify(this.redisOperations).opsForHash(); + verify(this.hashOperations).entries(anyString()); + verifyZeroInteractions(this.redisOperations); + verifyZeroInteractions(this.hashOperations); - assertThat(session.getId()).isEqualTo(expected.getId()); - assertThat(session.getAttributeNames()) - .isEqualTo(expected.getAttributeNames()); - assertThat(session.getAttribute(attribute1)) - .isEqualTo(expected.getAttribute(attribute1)); - assertThat(session.getAttribute(attribute2)) - .isEqualTo(expected.getAttribute(attribute2)); - assertThat(session.getCreationTime().truncatedTo(ChronoUnit.MILLIS)) - .isEqualTo(expected.getCreationTime() - .truncatedTo(ChronoUnit.MILLIS)); - assertThat(session.getMaxInactiveInterval()) - .isEqualTo(expected.getMaxInactiveInterval()); - assertThat( - session.getLastAccessedTime().truncatedTo(ChronoUnit.MILLIS)) - .isEqualTo(expected.getLastAccessedTime() - .truncatedTo(ChronoUnit.MILLIS)); - }).verifyComplete(); + assertThat(session.getId()).isEqualTo(expected.getId()); + assertThat(session.getAttributeNames()).isEqualTo(expected.getAttributeNames()); + assertThat(session.getAttribute(attribute1)).isEqualTo(expected.getAttribute(attribute1)); + assertThat(session.getAttribute(attribute2)).isEqualTo(expected.getAttribute(attribute2)); + assertThat(session.getCreationTime().truncatedTo(ChronoUnit.MILLIS)) + .isEqualTo(expected.getCreationTime().truncatedTo(ChronoUnit.MILLIS)); + assertThat(session.getMaxInactiveInterval()).isEqualTo(expected.getMaxInactiveInterval()); + assertThat(session.getLastAccessedTime().truncatedTo(ChronoUnit.MILLIS)) + .isEqualTo(expected.getLastAccessedTime().truncatedTo(ChronoUnit.MILLIS)); + }).verifyComplete(); } @Test @SuppressWarnings("unchecked") - public void getSessionExpired() { + void getSessionExpired() { given(this.redisOperations.opsForHash()).willReturn(this.hashOperations); - Map map = map(RedisSessionMapper.CREATION_TIME_KEY, 0L, - RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, 1, - RedisSessionMapper.LAST_ACCESSED_TIME_KEY, - Instant.now().minus(5, ChronoUnit.MINUTES).toEpochMilli()); - given(this.hashOperations.entries(anyString())) - .willReturn(Flux.fromIterable(map.entrySet())); + Map map = map(RedisSessionMapper.CREATION_TIME_KEY, 0L, RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, 1, + RedisSessionMapper.LAST_ACCESSED_TIME_KEY, Instant.now().minus(5, ChronoUnit.MINUTES).toEpochMilli()); + given(this.hashOperations.entries(anyString())).willReturn(Flux.fromIterable(map.entrySet())); given(this.redisOperations.delete(anyString())).willReturn(Mono.just(0L)); StepVerifier.create(this.repository.findById("test")).verifyComplete(); @@ -373,7 +337,7 @@ public class ReactiveRedisOperationsSessionRepositoryTests { } @Test // gh-1120 - public void getAttributeNamesAndRemove() { + void getAttributeNamesAndRemove() { RedisSession session = this.repository.new RedisSession(this.cached); session.setAttribute("attribute1", "value1"); session.setAttribute("attribute2", "value2"); diff --git a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/RedisOperationsSessionRepositoryTests.java b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/RedisOperationsSessionRepositoryTests.java index ede229b2..c695e289 100644 --- a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/RedisOperationsSessionRepositoryTests.java +++ b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/RedisOperationsSessionRepositoryTests.java @@ -72,27 +72,37 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; @SuppressWarnings({ "unchecked", "rawtypes" }) -public class RedisOperationsSessionRepositoryTests { - static final String SPRING_SECURITY_CONTEXT_KEY = "SPRING_SECURITY_CONTEXT"; +class RedisOperationsSessionRepositoryTests { + + private static final String SPRING_SECURITY_CONTEXT_KEY = "SPRING_SECURITY_CONTEXT"; @Mock RedisConnectionFactory factory; + @Mock RedisConnection connection; + @Mock RedisOperations redisOperations; + @Mock BoundValueOperations boundValueOperations; + @Mock BoundHashOperations boundHashOperations; + @Mock BoundSetOperations boundSetOperations; + @Mock ApplicationEventPublisher publisher; + @Mock RedisSerializer defaultSerializer; + @Captor ArgumentCaptor event; + @Captor ArgumentCaptor> delta; @@ -101,7 +111,7 @@ public class RedisOperationsSessionRepositoryTests { private RedisOperationsSessionRepository redisRepository; @BeforeEach - public void setup() { + void setup() { MockitoAnnotations.initMocks(this); this.redisRepository = new RedisOperationsSessionRepository(this.redisOperations); this.redisRepository.setDefaultSerializer(this.defaultSerializer); @@ -113,20 +123,16 @@ public class RedisOperationsSessionRepositoryTests { } @Test - public void setApplicationEventPublisherNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.redisRepository.setApplicationEventPublisher(null)) + void setApplicationEventPublisherNull() { + assertThatIllegalArgumentException().isThrownBy(() -> this.redisRepository.setApplicationEventPublisher(null)) .withMessage("applicationEventPublisher cannot be null"); } @Test - public void changeSessionIdWhenNotSaved() { - given(this.redisOperations.boundHashOps(anyString())) - .willReturn(this.boundHashOperations); - given(this.redisOperations.boundSetOps(anyString())) - .willReturn(this.boundSetOperations); - given(this.redisOperations.boundValueOps(anyString())) - .willReturn(this.boundValueOperations); + void changeSessionIdWhenNotSaved() { + given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); + given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations); RedisSession createSession = this.redisRepository.createSession(); String originalId = createSession.getId(); @@ -140,13 +146,10 @@ public class RedisOperationsSessionRepositoryTests { } @Test - public void changeSessionIdWhenSaved() { - given(this.redisOperations.boundHashOps(anyString())) - .willReturn(this.boundHashOperations); - given(this.redisOperations.boundSetOps(anyString())) - .willReturn(this.boundSetOperations); - given(this.redisOperations.boundValueOps(anyString())) - .willReturn(this.boundValueOperations); + void changeSessionIdWhenSaved() { + given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); + given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations); RedisSession session = this.redisRepository.new RedisSession(this.cached); session.setLastAccessedTime(session.getLastAccessedTime()); @@ -161,30 +164,25 @@ public class RedisOperationsSessionRepositoryTests { } @Test - public void createSessionDefaultMaxInactiveInterval() throws Exception { + void createSessionDefaultMaxInactiveInterval() throws Exception { Session session = this.redisRepository.createSession(); - assertThat(session.getMaxInactiveInterval()) - .isEqualTo(new MapSession().getMaxInactiveInterval()); + assertThat(session.getMaxInactiveInterval()).isEqualTo(new MapSession().getMaxInactiveInterval()); } @Test - public void createSessionCustomMaxInactiveInterval() throws Exception { + void createSessionCustomMaxInactiveInterval() throws Exception { int interval = 1; this.redisRepository.setDefaultMaxInactiveInterval(interval); Session session = this.redisRepository.createSession(); - assertThat(session.getMaxInactiveInterval()) - .isEqualTo(Duration.ofSeconds(interval)); + assertThat(session.getMaxInactiveInterval()).isEqualTo(Duration.ofSeconds(interval)); } @Test - public void saveNewSession() { + void saveNewSession() { RedisSession session = this.redisRepository.createSession(); - given(this.redisOperations.boundHashOps(anyString())) - .willReturn(this.boundHashOperations); - given(this.redisOperations.boundSetOps(anyString())) - .willReturn(this.boundSetOperations); - given(this.redisOperations.boundValueOps(anyString())) - .willReturn(this.boundValueOperations); + given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); + given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations); this.redisRepository.save(session); @@ -192,16 +190,15 @@ public class RedisOperationsSessionRepositoryTests { assertThat(delta.size()).isEqualTo(3); Object creationTime = delta.get(RedisSessionMapper.CREATION_TIME_KEY); assertThat(creationTime).isEqualTo(session.getCreationTime().toEpochMilli()); - assertThat(delta.get(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY)).isEqualTo( - (int) Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS) - .getSeconds()); + assertThat(delta.get(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY)) + .isEqualTo((int) Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS).getSeconds()); assertThat(delta.get(RedisSessionMapper.LAST_ACCESSED_TIME_KEY)) .isEqualTo(session.getCreationTime().toEpochMilli()); } // gh-467 @Test - public void saveSessionNothingChanged() { + void saveSessionNothingChanged() { RedisSession session = this.redisRepository.new RedisSession(this.cached); this.redisRepository.save(session); @@ -210,21 +207,17 @@ public class RedisOperationsSessionRepositoryTests { } @Test - public void saveJavadocSummary() { + void saveJavadocSummary() { RedisSession session = this.redisRepository.createSession(); String sessionKey = "spring:session:sessions:" + session.getId(); - String backgroundExpireKey = "spring:session:expirations:" - + RedisSessionExpirationPolicy.roundUpToNextMinute( - RedisSessionExpirationPolicy.expiresInMillis(session)); + String backgroundExpireKey = "spring:session:expirations:" + RedisSessionExpirationPolicy + .roundUpToNextMinute(RedisSessionExpirationPolicy.expiresInMillis(session)); String destroyedTriggerKey = "spring:session:sessions:expires:" + session.getId(); - given(this.redisOperations.boundHashOps(sessionKey)) - .willReturn(this.boundHashOperations); - given(this.redisOperations.boundSetOps(backgroundExpireKey)) - .willReturn(this.boundSetOperations); - given(this.redisOperations.boundValueOps(destroyedTriggerKey)) - .willReturn(this.boundValueOperations); + given(this.redisOperations.boundHashOps(sessionKey)).willReturn(this.boundHashOperations); + given(this.redisOperations.boundSetOps(backgroundExpireKey)).willReturn(this.boundSetOperations); + given(this.redisOperations.boundValueOps(destroyedTriggerKey)).willReturn(this.boundValueOperations); this.redisRepository.save(session); @@ -232,10 +225,8 @@ public class RedisOperationsSessionRepositoryTests { // can be accessed in expiration events // if the session is retrieved and expired it will not be returned since // findById checks if it is expired - long fiveMinutesAfterExpires = session.getMaxInactiveInterval().plusMinutes(5) - .getSeconds(); - verify(this.boundHashOperations).expire(fiveMinutesAfterExpires, - TimeUnit.SECONDS); + long fiveMinutesAfterExpires = session.getMaxInactiveInterval().plusMinutes(5).getSeconds(); + verify(this.boundHashOperations).expire(fiveMinutesAfterExpires, TimeUnit.SECONDS); verify(this.boundSetOperations).expire(fiveMinutesAfterExpires, TimeUnit.SECONDS); verify(this.boundSetOperations).add("expires:" + session.getId()); verify(this.boundValueOperations).expire(1800L, TimeUnit.SECONDS); @@ -243,18 +234,16 @@ public class RedisOperationsSessionRepositoryTests { } @Test - public void saveJavadoc() { + void saveJavadoc() { RedisSession session = this.redisRepository.new RedisSession(this.cached); session.setLastAccessedTime(session.getLastAccessedTime()); given(this.redisOperations.boundHashOps("spring:session:sessions:session-id")) .willReturn(this.boundHashOperations); - given(this.redisOperations - .boundSetOps("spring:session:expirations:1404361860000")) - .willReturn(this.boundSetOperations); - given(this.redisOperations - .boundValueOps("spring:session:sessions:expires:session-id")) - .willReturn(this.boundValueOperations); + given(this.redisOperations.boundSetOps("spring:session:expirations:1404361860000")) + .willReturn(this.boundSetOperations); + given(this.redisOperations.boundValueOps("spring:session:sessions:expires:session-id")) + .willReturn(this.boundValueOperations); this.redisRepository.save(session); @@ -262,74 +251,59 @@ public class RedisOperationsSessionRepositoryTests { // can be accessed in expiration events // if the session is retrieved and expired it will not be returned since // findById checks if it is expired - verify(this.boundHashOperations).expire( - session.getMaxInactiveInterval().plusMinutes(5).getSeconds(), + verify(this.boundHashOperations).expire(session.getMaxInactiveInterval().plusMinutes(5).getSeconds(), TimeUnit.SECONDS); } @Test - public void saveLastAccessChanged() { - RedisSession session = this.redisRepository.new RedisSession( - new MapSession(this.cached)); + void saveLastAccessChanged() { + RedisSession session = this.redisRepository.new RedisSession(new MapSession(this.cached)); session.setLastAccessedTime(Instant.ofEpochMilli(12345678L)); - given(this.redisOperations.boundHashOps(anyString())) - .willReturn(this.boundHashOperations); - given(this.redisOperations.boundSetOps(anyString())) - .willReturn(this.boundSetOperations); - given(this.redisOperations.boundValueOps(anyString())) - .willReturn(this.boundValueOperations); - - this.redisRepository.save(session); - - assertThat(getDelta()).isEqualTo(map(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, - session.getLastAccessedTime().toEpochMilli())); - } - - @Test - public void saveSetAttribute() { - String attrName = "attrName"; - RedisSession session = this.redisRepository.new RedisSession(new MapSession()); - session.setAttribute(attrName, "attrValue"); - given(this.redisOperations.boundHashOps(anyString())) - .willReturn(this.boundHashOperations); - given(this.redisOperations.boundSetOps(anyString())) - .willReturn(this.boundSetOperations); - given(this.redisOperations.boundValueOps(anyString())) - .willReturn(this.boundValueOperations); + given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); + given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations); this.redisRepository.save(session); assertThat(getDelta()).isEqualTo( - map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), - session.getAttribute(attrName))); + map(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, session.getLastAccessedTime().toEpochMilli())); } @Test - public void saveRemoveAttribute() { + void saveSetAttribute() { String attrName = "attrName"; RedisSession session = this.redisRepository.new RedisSession(new MapSession()); - session.removeAttribute(attrName); - given(this.redisOperations.boundHashOps(anyString())) - .willReturn(this.boundHashOperations); - given(this.redisOperations.boundSetOps(anyString())) - .willReturn(this.boundSetOperations); - given(this.redisOperations.boundValueOps(anyString())) - .willReturn(this.boundValueOperations); + session.setAttribute(attrName, "attrValue"); + given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); + given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations); this.redisRepository.save(session); - assertThat(getDelta()).isEqualTo(map( - RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), null)); + assertThat(getDelta()).isEqualTo( + map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), session.getAttribute(attrName))); } @Test - public void saveExpired() { + void saveRemoveAttribute() { + String attrName = "attrName"; + RedisSession session = this.redisRepository.new RedisSession(new MapSession()); + session.removeAttribute(attrName); + given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); + given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations); + + this.redisRepository.save(session); + + assertThat(getDelta()).isEqualTo(map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), null)); + } + + @Test + void saveExpired() { RedisSession session = this.redisRepository.new RedisSession(new MapSession()); session.setMaxInactiveInterval(Duration.ZERO); - given(this.redisOperations.boundHashOps(anyString())) - .willReturn(this.boundHashOperations); - given(this.redisOperations.boundSetOps(anyString())) - .willReturn(this.boundSetOperations); + given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); this.redisRepository.save(session); @@ -339,7 +313,7 @@ public class RedisOperationsSessionRepositoryTests { } @Test - public void redisSessionGetAttributes() { + void redisSessionGetAttributes() { String attrName = "attrName"; RedisSession session = this.redisRepository.new RedisSession( Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS)); @@ -351,39 +325,31 @@ public class RedisOperationsSessionRepositoryTests { } @Test - public void delete() { + void delete() { String attrName = "attrName"; MapSession expected = new MapSession(); expected.setLastAccessedTime(Instant.now().minusSeconds(60)); expected.setAttribute(attrName, "attrValue"); - given(this.redisOperations.boundHashOps(anyString())) - .willReturn(this.boundHashOperations); - given(this.redisOperations.boundSetOps(anyString())) - .willReturn(this.boundSetOperations); - Map map = map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), - expected.getAttribute(attrName), RedisSessionMapper.CREATION_TIME_KEY, - expected.getCreationTime().toEpochMilli(), - RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, - (int) expected.getMaxInactiveInterval().getSeconds(), - RedisSessionMapper.LAST_ACCESSED_TIME_KEY, - expected.getLastAccessedTime().toEpochMilli()); + given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); + Map map = map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), expected.getAttribute(attrName), + RedisSessionMapper.CREATION_TIME_KEY, expected.getCreationTime().toEpochMilli(), + RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, (int) expected.getMaxInactiveInterval().getSeconds(), + RedisSessionMapper.LAST_ACCESSED_TIME_KEY, expected.getLastAccessedTime().toEpochMilli()); given(this.boundHashOperations.entries()).willReturn(map); - given(this.redisOperations.boundSetOps(anyString())) - .willReturn(this.boundSetOperations); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); String id = expected.getId(); this.redisRepository.deleteById(id); - assertThat(getDelta().get(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY)) - .isEqualTo(0); + assertThat(getDelta().get(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY)).isEqualTo(0); verify(this.redisOperations, atLeastOnce()).delete(getKey("expires:" + id)); verify(this.redisOperations, never()).boundValueOps(getKey("expires:" + id)); } @Test - public void deleteNullSession() { - given(this.redisOperations.boundHashOps(anyString())) - .willReturn(this.boundHashOperations); + void deleteNullSession() { + given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations); String id = "abc"; this.redisRepository.deleteById(id); @@ -392,58 +358,48 @@ public class RedisOperationsSessionRepositoryTests { } @Test - public void getSessionNotFound() { + void getSessionNotFound() { String id = "abc"; - given(this.redisOperations.boundHashOps(getKey(id))) - .willReturn(this.boundHashOperations); + given(this.redisOperations.boundHashOps(getKey(id))).willReturn(this.boundHashOperations); given(this.boundHashOperations.entries()).willReturn(map()); assertThat(this.redisRepository.findById(id)).isNull(); } @Test - public void getSessionFound() { + void getSessionFound() { String attribute1 = "attribute1"; String attribute2 = "attribute2"; MapSession expected = new MapSession(); expected.setLastAccessedTime(Instant.now().minusSeconds(60)); expected.setAttribute(attribute1, "test"); expected.setAttribute(attribute2, null); - given(this.redisOperations.boundHashOps(getKey(expected.getId()))) - .willReturn(this.boundHashOperations); + given(this.redisOperations.boundHashOps(getKey(expected.getId()))).willReturn(this.boundHashOperations); Map map = map(RedisOperationsSessionRepository.getSessionAttrNameKey(attribute1), - expected.getAttribute(attribute1), - RedisOperationsSessionRepository.getSessionAttrNameKey(attribute2), + expected.getAttribute(attribute1), RedisOperationsSessionRepository.getSessionAttrNameKey(attribute2), expected.getAttribute(attribute2), RedisSessionMapper.CREATION_TIME_KEY, - expected.getCreationTime().toEpochMilli(), - RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, - (int) expected.getMaxInactiveInterval().getSeconds(), - RedisSessionMapper.LAST_ACCESSED_TIME_KEY, + expected.getCreationTime().toEpochMilli(), RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, + (int) expected.getMaxInactiveInterval().getSeconds(), RedisSessionMapper.LAST_ACCESSED_TIME_KEY, expected.getLastAccessedTime().toEpochMilli()); given(this.boundHashOperations.entries()).willReturn(map); RedisSession session = this.redisRepository.findById(expected.getId()); assertThat(session.getId()).isEqualTo(expected.getId()); assertThat(session.getAttributeNames()).isEqualTo(expected.getAttributeNames()); - assertThat(session.getAttribute(attribute1)) - .isEqualTo(expected.getAttribute(attribute1)); - assertThat(session.getAttribute(attribute2)) - .isEqualTo(expected.getAttribute(attribute2)); + assertThat(session.getAttribute(attribute1)).isEqualTo(expected.getAttribute(attribute1)); + assertThat(session.getAttribute(attribute2)).isEqualTo(expected.getAttribute(attribute2)); assertThat(session.getCreationTime().truncatedTo(ChronoUnit.MILLIS)) .isEqualTo(expected.getCreationTime().truncatedTo(ChronoUnit.MILLIS)); - assertThat(session.getMaxInactiveInterval()) - .isEqualTo(expected.getMaxInactiveInterval()); + assertThat(session.getMaxInactiveInterval()).isEqualTo(expected.getMaxInactiveInterval()); assertThat(session.getLastAccessedTime().truncatedTo(ChronoUnit.MILLIS)) .isEqualTo(expected.getLastAccessedTime().truncatedTo(ChronoUnit.MILLIS)); } @Test - public void getSessionExpired() { + void getSessionExpired() { String expiredId = "expired-id"; - given(this.redisOperations.boundHashOps(getKey(expiredId))) - .willReturn(this.boundHashOperations); - Map map = map(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, 1, - RedisSessionMapper.LAST_ACCESSED_TIME_KEY, + given(this.redisOperations.boundHashOps(getKey(expiredId))).willReturn(this.boundHashOperations); + Map map = map(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, 1, RedisSessionMapper.LAST_ACCESSED_TIME_KEY, Instant.now().minus(5, ChronoUnit.MINUTES).toEpochMilli()); given(this.boundHashOperations.entries()).willReturn(map); @@ -451,46 +407,36 @@ public class RedisOperationsSessionRepositoryTests { } @Test - public void findByPrincipalNameExpired() { + void findByPrincipalNameExpired() { String expiredId = "expired-id"; - given(this.redisOperations.boundSetOps(anyString())) - .willReturn(this.boundSetOperations); - given(this.boundSetOperations.members()) - .willReturn(Collections.singleton(expiredId)); - given(this.redisOperations.boundHashOps(getKey(expiredId))) - .willReturn(this.boundHashOperations); - Map map = map(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, 1, - RedisSessionMapper.LAST_ACCESSED_TIME_KEY, + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); + given(this.boundSetOperations.members()).willReturn(Collections.singleton(expiredId)); + given(this.redisOperations.boundHashOps(getKey(expiredId))).willReturn(this.boundHashOperations); + Map map = map(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, 1, RedisSessionMapper.LAST_ACCESSED_TIME_KEY, Instant.now().minus(5, ChronoUnit.MINUTES).toEpochMilli()); given(this.boundHashOperations.entries()).willReturn(map); - assertThat(this.redisRepository.findByIndexNameAndIndexValue( - FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, "principal")) + assertThat(this.redisRepository + .findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, "principal")) .isEmpty(); } @Test - public void findByPrincipalName() { + void findByPrincipalName() { Instant lastAccessed = Instant.now().minusMillis(10); Instant createdTime = lastAccessed.minusMillis(10); Duration maxInactive = Duration.ofHours(1); String sessionId = "some-id"; - given(this.redisOperations.boundSetOps(anyString())) - .willReturn(this.boundSetOperations); - given(this.boundSetOperations.members()) - .willReturn(Collections.singleton(sessionId)); - given(this.redisOperations.boundHashOps(getKey(sessionId))) - .willReturn(this.boundHashOperations); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); + given(this.boundSetOperations.members()).willReturn(Collections.singleton(sessionId)); + given(this.redisOperations.boundHashOps(getKey(sessionId))).willReturn(this.boundHashOperations); Map map = map(RedisSessionMapper.CREATION_TIME_KEY, createdTime.toEpochMilli(), - RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, - (int) maxInactive.getSeconds(), RedisSessionMapper.LAST_ACCESSED_TIME_KEY, - lastAccessed.toEpochMilli()); + RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, (int) maxInactive.getSeconds(), + RedisSessionMapper.LAST_ACCESSED_TIME_KEY, lastAccessed.toEpochMilli()); given(this.boundHashOperations.entries()).willReturn(map); Map sessionIdToSessions = this.redisRepository - .findByIndexNameAndIndexValue( - FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, - "principal"); + .findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, "principal"); assertThat(sessionIdToSessions).hasSize(1); RedisSession session = sessionIdToSessions.get(sessionId); @@ -504,13 +450,11 @@ public class RedisOperationsSessionRepositoryTests { } @Test - public void cleanupExpiredSessions() { + void cleanupExpiredSessions() { String expiredId = "expired-id"; - given(this.redisOperations.boundSetOps(anyString())) - .willReturn(this.boundSetOperations); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); - Set expiredIds = new HashSet<>( - Arrays.asList("expired-key1", "expired-key2")); + Set expiredIds = new HashSet<>(Arrays.asList("expired-key1", "expired-key2")); given(this.boundSetOperations.members()).willReturn(expiredIds); this.redisRepository.cleanupExpiredSessions(); @@ -523,15 +467,14 @@ public class RedisOperationsSessionRepositoryTests { } @Test - public void onMessageCreated() { + void onMessageCreated() { MapSession session = this.cached; byte[] pattern = "".getBytes(StandardCharsets.UTF_8); String channel = "spring:session:event:0:created:" + session.getId(); JdkSerializationRedisSerializer defaultSerailizer = new JdkSerializationRedisSerializer(); this.redisRepository.setDefaultSerializer(defaultSerailizer); byte[] body = defaultSerailizer.serialize(new HashMap()); - DefaultMessage message = new DefaultMessage( - channel.getBytes(StandardCharsets.UTF_8), body); + DefaultMessage message = new DefaultMessage(channel.getBytes(StandardCharsets.UTF_8), body); this.redisRepository.setApplicationEventPublisher(this.publisher); @@ -542,15 +485,13 @@ public class RedisOperationsSessionRepositoryTests { } @Test // gh-309 - public void onMessageCreatedCustomSerializer() { + void onMessageCreatedCustomSerializer() { MapSession session = this.cached; byte[] pattern = "".getBytes(StandardCharsets.UTF_8); byte[] body = new byte[0]; String channel = "spring:session:event:0:created:" + session.getId(); - given(this.defaultSerializer.deserialize(body)) - .willReturn(new HashMap()); - DefaultMessage message = new DefaultMessage( - channel.getBytes(StandardCharsets.UTF_8), body); + given(this.defaultSerializer.deserialize(body)).willReturn(new HashMap()); + DefaultMessage message = new DefaultMessage(channel.getBytes(StandardCharsets.UTF_8), body); this.redisRepository.setApplicationEventPublisher(this.publisher); this.redisRepository.onMessage(message, pattern); @@ -561,19 +502,16 @@ public class RedisOperationsSessionRepositoryTests { } @Test - public void onMessageDeletedSessionFound() { + void onMessageDeletedSessionFound() { String deletedId = "deleted-id"; - given(this.redisOperations.boundHashOps(getKey(deletedId))) - .willReturn(this.boundHashOperations); - Map map = map(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, 0, - RedisSessionMapper.LAST_ACCESSED_TIME_KEY, + given(this.redisOperations.boundHashOps(getKey(deletedId))).willReturn(this.boundHashOperations); + Map map = map(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, 0, RedisSessionMapper.LAST_ACCESSED_TIME_KEY, System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5)); given(this.boundHashOperations.entries()).willReturn(map); String channel = "__keyevent@0__:del"; String body = "spring:session:sessions:expires:" + deletedId; - DefaultMessage message = new DefaultMessage( - channel.getBytes(StandardCharsets.UTF_8), + DefaultMessage message = new DefaultMessage(channel.getBytes(StandardCharsets.UTF_8), body.getBytes(StandardCharsets.UTF_8)); this.redisRepository.setApplicationEventPublisher(this.publisher); @@ -590,16 +528,14 @@ public class RedisOperationsSessionRepositoryTests { } @Test - public void onMessageDeletedSessionNotFound() { + void onMessageDeletedSessionNotFound() { String deletedId = "deleted-id"; - given(this.redisOperations.boundHashOps(getKey(deletedId))) - .willReturn(this.boundHashOperations); + given(this.redisOperations.boundHashOps(getKey(deletedId))).willReturn(this.boundHashOperations); given(this.boundHashOperations.entries()).willReturn(map()); String channel = "__keyevent@0__:del"; String body = "spring:session:sessions:expires:" + deletedId; - DefaultMessage message = new DefaultMessage( - channel.getBytes(StandardCharsets.UTF_8), + DefaultMessage message = new DefaultMessage(channel.getBytes(StandardCharsets.UTF_8), body.getBytes(StandardCharsets.UTF_8)); this.redisRepository.setApplicationEventPublisher(this.publisher); @@ -614,19 +550,16 @@ public class RedisOperationsSessionRepositoryTests { } @Test - public void onMessageExpiredSessionFound() { + void onMessageExpiredSessionFound() { String expiredId = "expired-id"; - given(this.redisOperations.boundHashOps(getKey(expiredId))) - .willReturn(this.boundHashOperations); - Map map = map(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, 1, - RedisSessionMapper.LAST_ACCESSED_TIME_KEY, + given(this.redisOperations.boundHashOps(getKey(expiredId))).willReturn(this.boundHashOperations); + Map map = map(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, 1, RedisSessionMapper.LAST_ACCESSED_TIME_KEY, System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5)); given(this.boundHashOperations.entries()).willReturn(map); String channel = "__keyevent@0__:expired"; String body = "spring:session:sessions:expires:" + expiredId; - DefaultMessage message = new DefaultMessage( - channel.getBytes(StandardCharsets.UTF_8), + DefaultMessage message = new DefaultMessage(channel.getBytes(StandardCharsets.UTF_8), body.getBytes(StandardCharsets.UTF_8)); this.redisRepository.setApplicationEventPublisher(this.publisher); @@ -643,16 +576,14 @@ public class RedisOperationsSessionRepositoryTests { } @Test - public void onMessageExpiredSessionNotFound() { + void onMessageExpiredSessionNotFound() { String expiredId = "expired-id"; - given(this.redisOperations.boundHashOps(getKey(expiredId))) - .willReturn(this.boundHashOperations); + given(this.redisOperations.boundHashOps(getKey(expiredId))).willReturn(this.boundHashOperations); given(this.boundHashOperations.entries()).willReturn(map()); String channel = "__keyevent@0__:expired"; String body = "spring:session:sessions:expires:" + expiredId; - DefaultMessage message = new DefaultMessage( - channel.getBytes(StandardCharsets.UTF_8), + DefaultMessage message = new DefaultMessage(channel.getBytes(StandardCharsets.UTF_8), body.getBytes(StandardCharsets.UTF_8)); this.redisRepository.setApplicationEventPublisher(this.publisher); @@ -667,21 +598,20 @@ public class RedisOperationsSessionRepositoryTests { } @Test - public void resolvePrincipalIndex() { + void resolvePrincipalIndex() { PrincipalNameResolver resolver = RedisOperationsSessionRepository.PRINCIPAL_NAME_RESOLVER; String username = "username"; RedisSession session = this.redisRepository.createSession(); - session.setAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, - username); + session.setAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username); assertThat(resolver.resolvePrincipal(session)).isEqualTo(username); } @Test - public void resolveIndexOnSecurityContext() { + void resolveIndexOnSecurityContext() { String principal = "resolveIndexOnSecurityContext"; - Authentication authentication = new UsernamePasswordAuthenticationToken(principal, - "notused", AuthorityUtils.createAuthorityList("ROLE_USER")); + Authentication authentication = new UsernamePasswordAuthenticationToken(principal, "notused", + AuthorityUtils.createAuthorityList("ROLE_USER")); SecurityContext context = new SecurityContextImpl(); context.setAuthentication(authentication); @@ -694,14 +624,14 @@ public class RedisOperationsSessionRepositoryTests { } @Test - public void flushModeOnSaveCreate() { + void flushModeOnSaveCreate() { this.redisRepository.createSession(); verifyZeroInteractions(this.boundHashOperations); } @Test - public void flushModeOnSaveSetAttribute() { + void flushModeOnSaveSetAttribute() { RedisSession session = this.redisRepository.createSession(); session.setAttribute("something", "here"); @@ -709,7 +639,7 @@ public class RedisOperationsSessionRepositoryTests { } @Test - public void flushModeOnSaveRemoveAttribute() { + void flushModeOnSaveRemoveAttribute() { RedisSession session = this.redisRepository.createSession(); session.removeAttribute("remove"); @@ -717,7 +647,7 @@ public class RedisOperationsSessionRepositoryTests { } @Test - public void flushModeOnSaveSetLastAccessedTime() { + void flushModeOnSaveSetLastAccessedTime() { RedisSession session = this.redisRepository.createSession(); session.setLastAccessedTime(Instant.ofEpochMilli(1L)); @@ -725,7 +655,7 @@ public class RedisOperationsSessionRepositoryTests { } @Test - public void flushModeOnSaveSetMaxInactiveIntervalInSeconds() { + void flushModeOnSaveSetMaxInactiveIntervalInSeconds() { RedisSession session = this.redisRepository.createSession(); session.setMaxInactiveInterval(Duration.ofSeconds(1)); @@ -733,13 +663,10 @@ public class RedisOperationsSessionRepositoryTests { } @Test - public void flushModeImmediateCreate() { - given(this.redisOperations.boundHashOps(anyString())) - .willReturn(this.boundHashOperations); - given(this.redisOperations.boundSetOps(anyString())) - .willReturn(this.boundSetOperations); - given(this.redisOperations.boundValueOps(anyString())) - .willReturn(this.boundValueOperations); + void flushModeImmediateCreate() { + given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); + given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations); this.redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE); RedisSession session = this.redisRepository.createSession(); @@ -748,21 +675,17 @@ public class RedisOperationsSessionRepositoryTests { assertThat(delta.size()).isEqualTo(3); Object creationTime = delta.get(RedisSessionMapper.CREATION_TIME_KEY); assertThat(creationTime).isEqualTo(session.getCreationTime().toEpochMilli()); - assertThat(delta.get(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY)).isEqualTo( - (int) Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS) - .getSeconds()); + assertThat(delta.get(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY)) + .isEqualTo((int) Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS).getSeconds()); assertThat(delta.get(RedisSessionMapper.LAST_ACCESSED_TIME_KEY)) .isEqualTo(session.getCreationTime().toEpochMilli()); } @Test // gh-1409 - public void flushModeImmediateCreateWithCustomMaxInactiveInterval() { - given(this.redisOperations.boundHashOps(anyString())) - .willReturn(this.boundHashOperations); - given(this.redisOperations.boundSetOps(anyString())) - .willReturn(this.boundSetOperations); - given(this.redisOperations.boundValueOps(anyString())) - .willReturn(this.boundValueOperations); + void flushModeImmediateCreateWithCustomMaxInactiveInterval() { + given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); + given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations); this.redisRepository.setDefaultMaxInactiveInterval(60); this.redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE); this.redisRepository.createSession(); @@ -772,13 +695,10 @@ public class RedisOperationsSessionRepositoryTests { } @Test - public void flushModeImmediateSetAttribute() { - given(this.redisOperations.boundHashOps(anyString())) - .willReturn(this.boundHashOperations); - given(this.redisOperations.boundSetOps(anyString())) - .willReturn(this.boundSetOperations); - given(this.redisOperations.boundValueOps(anyString())) - .willReturn(this.boundValueOperations); + void flushModeImmediateSetAttribute() { + given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); + given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations); this.redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE); RedisSession session = this.redisRepository.createSession(); @@ -788,18 +708,14 @@ public class RedisOperationsSessionRepositoryTests { Map delta = getDelta(2); assertThat(delta.size()).isEqualTo(1); assertThat(delta).isEqualTo( - map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), - session.getAttribute(attrName))); + map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), session.getAttribute(attrName))); } @Test - public void flushModeImmediateRemoveAttribute() { - given(this.redisOperations.boundHashOps(anyString())) - .willReturn(this.boundHashOperations); - given(this.redisOperations.boundSetOps(anyString())) - .willReturn(this.boundSetOperations); - given(this.redisOperations.boundValueOps(anyString())) - .willReturn(this.boundValueOperations); + void flushModeImmediateRemoveAttribute() { + given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); + given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations); this.redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE); RedisSession session = this.redisRepository.createSession(); @@ -809,18 +725,14 @@ public class RedisOperationsSessionRepositoryTests { Map delta = getDelta(2); assertThat(delta.size()).isEqualTo(1); assertThat(delta).isEqualTo( - map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), - session.getAttribute(attrName))); + map(RedisOperationsSessionRepository.getSessionAttrNameKey(attrName), session.getAttribute(attrName))); } @Test - public void flushModeSetMaxInactiveIntervalInSeconds() { - given(this.redisOperations.boundHashOps(anyString())) - .willReturn(this.boundHashOperations); - given(this.redisOperations.boundSetOps(anyString())) - .willReturn(this.boundSetOperations); - given(this.redisOperations.boundValueOps(anyString())) - .willReturn(this.boundValueOperations); + void flushModeSetMaxInactiveIntervalInSeconds() { + given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); + given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations); this.redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE); RedisSession session = this.redisRepository.createSession(); @@ -833,13 +745,10 @@ public class RedisOperationsSessionRepositoryTests { } @Test - public void flushModeSetLastAccessedTime() { - given(this.redisOperations.boundHashOps(anyString())) - .willReturn(this.boundHashOperations); - given(this.redisOperations.boundSetOps(anyString())) - .willReturn(this.boundSetOperations); - given(this.redisOperations.boundValueOps(anyString())) - .willReturn(this.boundValueOperations); + void flushModeSetLastAccessedTime() { + given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); + given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations); this.redisRepository.setRedisFlushMode(RedisFlushMode.IMMEDIATE); RedisSession session = this.redisRepository.createSession(); @@ -848,53 +757,46 @@ public class RedisOperationsSessionRepositoryTests { Map delta = getDelta(2); assertThat(delta.size()).isEqualTo(1); - assertThat(delta).isEqualTo(map(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, - session.getLastAccessedTime().toEpochMilli())); + assertThat(delta).isEqualTo( + map(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, session.getLastAccessedTime().toEpochMilli())); } @Test - public void setRedisFlushModeNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.redisRepository.setRedisFlushMode(null)) + void setRedisFlushModeNull() { + assertThatIllegalArgumentException().isThrownBy(() -> this.redisRepository.setRedisFlushMode(null)) .withMessage("redisFlushMode cannot be null"); } @Test - public void changeRedisNamespace() { + void changeRedisNamespace() { String namespace = "foo:bar"; this.redisRepository.setRedisKeyNamespace(namespace); RedisSession session = this.redisRepository.new RedisSession(new MapSession()); session.setMaxInactiveInterval(Duration.ZERO); - given(this.redisOperations.boundHashOps(anyString())) - .willReturn(this.boundHashOperations); - given(this.redisOperations.boundSetOps(anyString())) - .willReturn(this.boundSetOperations); + given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations); + given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations); this.redisRepository.save(session); String id = session.getId(); - verify(this.redisOperations, atLeastOnce()) - .delete(namespace + ":sessions:expires:" + id); - verify(this.redisOperations, never()) - .boundValueOps(namespace + ":sessions:expires:" + id); + verify(this.redisOperations, atLeastOnce()).delete(namespace + ":sessions:expires:" + id); + verify(this.redisOperations, never()).boundValueOps(namespace + ":sessions:expires:" + id); } @Test - public void setRedisKeyNamespaceNullNamespace() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.redisRepository.setRedisKeyNamespace(null)) + void setRedisKeyNamespaceNullNamespace() { + assertThatIllegalArgumentException().isThrownBy(() -> this.redisRepository.setRedisKeyNamespace(null)) .withMessage("namespace cannot be null or empty"); } @Test - public void setRedisKeyNamespaceEmptyNamespace() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.redisRepository.setRedisKeyNamespace(" ")) + void setRedisKeyNamespaceEmptyNamespace() { + assertThatIllegalArgumentException().isThrownBy(() -> this.redisRepository.setRedisKeyNamespace(" ")) .withMessage("namespace cannot be null or empty"); } @Test // gh-1120 - public void getAttributeNamesAndRemove() { + void getAttributeNamesAndRemove() { RedisSession session = this.redisRepository.new RedisSession(this.cached); session.setAttribute("attribute1", "value1"); session.setAttribute("attribute2", "value2"); @@ -907,7 +809,7 @@ public class RedisOperationsSessionRepositoryTests { } @Test - public void onMessageCreatedInOtherDatabase() { + void onMessageCreatedInOtherDatabase() { JdkSerializationRedisSerializer serializer = new JdkSerializationRedisSerializer(); this.redisRepository.setApplicationEventPublisher(this.publisher); this.redisRepository.setDefaultSerializer(serializer); @@ -915,8 +817,7 @@ public class RedisOperationsSessionRepositoryTests { MapSession session = this.cached; String channel = "spring:session:event:created:1:" + session.getId(); byte[] body = serializer.serialize(new HashMap()); - DefaultMessage message = new DefaultMessage( - channel.getBytes(StandardCharsets.UTF_8), body); + DefaultMessage message = new DefaultMessage(channel.getBytes(StandardCharsets.UTF_8), body); this.redisRepository.onMessage(message, "".getBytes(StandardCharsets.UTF_8)); @@ -925,7 +826,7 @@ public class RedisOperationsSessionRepositoryTests { } @Test - public void onMessageDeletedInOtherDatabase() { + void onMessageDeletedInOtherDatabase() { JdkSerializationRedisSerializer serializer = new JdkSerializationRedisSerializer(); this.redisRepository.setApplicationEventPublisher(this.publisher); this.redisRepository.setDefaultSerializer(serializer); @@ -933,8 +834,7 @@ public class RedisOperationsSessionRepositoryTests { MapSession session = this.cached; String channel = "__keyevent@1__:del"; String body = "spring:session:sessions:expires:" + session.getId(); - DefaultMessage message = new DefaultMessage( - channel.getBytes(StandardCharsets.UTF_8), + DefaultMessage message = new DefaultMessage(channel.getBytes(StandardCharsets.UTF_8), body.getBytes(StandardCharsets.UTF_8)); this.redisRepository.onMessage(message, "".getBytes(StandardCharsets.UTF_8)); @@ -944,7 +844,7 @@ public class RedisOperationsSessionRepositoryTests { } @Test - public void onMessageExpiredInOtherDatabase() { + void onMessageExpiredInOtherDatabase() { JdkSerializationRedisSerializer serializer = new JdkSerializationRedisSerializer(); this.redisRepository.setApplicationEventPublisher(this.publisher); this.redisRepository.setDefaultSerializer(serializer); @@ -952,8 +852,7 @@ public class RedisOperationsSessionRepositoryTests { MapSession session = this.cached; String channel = "__keyevent@1__:expired"; String body = "spring:session:sessions:expires:" + session.getId(); - DefaultMessage message = new DefaultMessage( - channel.getBytes(StandardCharsets.UTF_8), + DefaultMessage message = new DefaultMessage(channel.getBytes(StandardCharsets.UTF_8), body.getBytes(StandardCharsets.UTF_8)); this.redisRepository.onMessage(message, "".getBytes(StandardCharsets.UTF_8)); @@ -985,4 +884,5 @@ public class RedisOperationsSessionRepositoryTests { verify(this.boundHashOperations, times(times)).putAll(this.delta.capture()); return this.delta.getAllValues().get(times - 1); } + } diff --git a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/RedisSessionExpirationPolicyTests.java b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/RedisSessionExpirationPolicyTests.java index 0b924f70..efbeff8e 100644 --- a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/RedisSessionExpirationPolicyTests.java +++ b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/RedisSessionExpirationPolicyTests.java @@ -39,54 +39,52 @@ import static org.mockito.Mockito.verify; /** * @author Rob Winch */ -public class RedisSessionExpirationPolicyTests { +class RedisSessionExpirationPolicyTests { + // Wed Apr 15 10:28:32 CDT 2015 static final Long NOW = 1429111712346L; // Wed Apr 15 10:27:32 CDT 2015 - static final Long ONE_MINUTE_AGO = 1429111652346L; + private static final Long ONE_MINUTE_AGO = 1429111652346L; @Mock RedisOperations sessionRedisOperations; + @Mock BoundSetOperations setOperations; + @Mock BoundHashOperations hashOperations; + @Mock BoundValueOperations valueOperations; - RedisSessionExpirationPolicy policy; + private RedisSessionExpirationPolicy policy; private MapSession session; @BeforeEach - public void setup() { + void setup() { MockitoAnnotations.initMocks(this); - RedisOperationsSessionRepository repository = new RedisOperationsSessionRepository( - this.sessionRedisOperations); - this.policy = new RedisSessionExpirationPolicy(this.sessionRedisOperations, - repository::getExpirationsKey, repository::getSessionKey); + RedisOperationsSessionRepository repository = new RedisOperationsSessionRepository(this.sessionRedisOperations); + this.policy = new RedisSessionExpirationPolicy(this.sessionRedisOperations, repository::getExpirationsKey, + repository::getSessionKey); this.session = new MapSession(); this.session.setLastAccessedTime(Instant.ofEpochMilli(1429116694675L)); this.session.setId("12345"); - given(this.sessionRedisOperations.boundSetOps(anyString())) - .willReturn(this.setOperations); - given(this.sessionRedisOperations.boundHashOps(anyString())) - .willReturn(this.hashOperations); - given(this.sessionRedisOperations.boundValueOps(anyString())) - .willReturn(this.valueOperations); + given(this.sessionRedisOperations.boundSetOps(anyString())).willReturn(this.setOperations); + given(this.sessionRedisOperations.boundHashOps(anyString())).willReturn(this.hashOperations); + given(this.sessionRedisOperations.boundValueOps(anyString())).willReturn(this.valueOperations); } // gh-169 @Test - public void onExpirationUpdatedRemovesOriginalExpirationTimeRoundedUp() - throws Exception { + void onExpirationUpdatedRemovesOriginalExpirationTimeRoundedUp() throws Exception { long originalExpirationTimeInMs = ONE_MINUTE_AGO; long originalRoundedToNextMinInMs = RedisSessionExpirationPolicy .roundUpToNextMinute(originalExpirationTimeInMs); - String originalExpireKey = this.policy - .getExpirationKey(originalRoundedToNextMinInMs); + String originalExpireKey = this.policy.getExpirationKey(originalRoundedToNextMinInMs); this.policy.onExpirationUpdated(originalExpirationTimeInMs, this.session); @@ -96,14 +94,11 @@ public class RedisSessionExpirationPolicyTests { } @Test - public void onExpirationUpdatedDoNotSendDeleteWhenExpirationTimeDoesNotChange() - throws Exception { - long originalExpirationTimeInMs = RedisSessionExpirationPolicy - .expiresInMillis(this.session) - 10; + void onExpirationUpdatedDoNotSendDeleteWhenExpirationTimeDoesNotChange() throws Exception { + long originalExpirationTimeInMs = RedisSessionExpirationPolicy.expiresInMillis(this.session) - 10; long originalRoundedToNextMinInMs = RedisSessionExpirationPolicy .roundUpToNextMinute(originalExpirationTimeInMs); - String originalExpireKey = this.policy - .getExpirationKey(originalRoundedToNextMinInMs); + String originalExpireKey = this.policy.getExpirationKey(originalRoundedToNextMinInMs); this.policy.onExpirationUpdated(originalExpirationTimeInMs, this.session); @@ -113,36 +108,32 @@ public class RedisSessionExpirationPolicyTests { } @Test - public void onExpirationUpdatedAddsExpirationTimeRoundedUp() throws Exception { - long expirationTimeInMs = RedisSessionExpirationPolicy - .expiresInMillis(this.session); - long expirationRoundedUpInMs = RedisSessionExpirationPolicy - .roundUpToNextMinute(expirationTimeInMs); + void onExpirationUpdatedAddsExpirationTimeRoundedUp() throws Exception { + long expirationTimeInMs = RedisSessionExpirationPolicy.expiresInMillis(this.session); + long expirationRoundedUpInMs = RedisSessionExpirationPolicy.roundUpToNextMinute(expirationTimeInMs); String expectedExpireKey = this.policy.getExpirationKey(expirationRoundedUpInMs); this.policy.onExpirationUpdated(null, this.session); verify(this.sessionRedisOperations).boundSetOps(expectedExpireKey); verify(this.setOperations).add("expires:" + this.session.getId()); - verify(this.setOperations).expire( - this.session.getMaxInactiveInterval().plusMinutes(5).getSeconds(), + verify(this.setOperations).expire(this.session.getMaxInactiveInterval().plusMinutes(5).getSeconds(), TimeUnit.SECONDS); } @Test - public void onExpirationUpdatedSetExpireSession() throws Exception { + void onExpirationUpdatedSetExpireSession() throws Exception { String sessionKey = this.policy.getSessionKey(this.session.getId()); this.policy.onExpirationUpdated(null, this.session); verify(this.sessionRedisOperations).boundHashOps(sessionKey); - verify(this.hashOperations).expire( - this.session.getMaxInactiveInterval().plusMinutes(5).getSeconds(), + verify(this.hashOperations).expire(this.session.getMaxInactiveInterval().plusMinutes(5).getSeconds(), TimeUnit.SECONDS); } @Test - public void onExpirationUpdatedDeleteOnZero() throws Exception { + void onExpirationUpdatedDeleteOnZero() throws Exception { String sessionKey = this.policy.getSessionKey("expires:" + this.session.getId()); long originalExpirationTimeInMs = ONE_MINUTE_AGO; @@ -155,13 +146,12 @@ public class RedisSessionExpirationPolicyTests { verify(this.setOperations).remove("expires:" + this.session.getId()); verify(this.setOperations).add("expires:" + this.session.getId()); verify(this.sessionRedisOperations).delete(sessionKey); - verify(this.setOperations).expire( - this.session.getMaxInactiveInterval().plusMinutes(5).getSeconds(), + verify(this.setOperations).expire(this.session.getMaxInactiveInterval().plusMinutes(5).getSeconds(), TimeUnit.SECONDS); } @Test - public void onExpirationUpdatedPersistOnNegativeExpiration() throws Exception { + void onExpirationUpdatedPersistOnNegativeExpiration() throws Exception { long originalExpirationTimeInMs = ONE_MINUTE_AGO; this.session.setMaxInactiveInterval(Duration.ofSeconds(-1)); @@ -173,4 +163,5 @@ public class RedisSessionExpirationPolicyTests { verify(this.valueOperations).persist(); verify(this.hashOperations).persist(); } + } diff --git a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/RedisSessionMapperTests.java b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/RedisSessionMapperTests.java index 5640c6c3..3e345c59 100644 --- a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/RedisSessionMapperTests.java +++ b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/RedisSessionMapperTests.java @@ -47,8 +47,7 @@ class RedisSessionMapperTests { @Test void constructor_NullId_ShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new RedisSessionMapper(null)) + assertThatIllegalArgumentException().isThrownBy(() -> new RedisSessionMapper(null)) .withMessage("sessionId must not be empty"); } @@ -66,8 +65,7 @@ class RedisSessionMapperTests { @Test void apply_EmptyMap_ShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.mapper.apply(Collections.emptyMap())) + assertThatIllegalArgumentException().isThrownBy(() -> this.mapper.apply(Collections.emptyMap())) .withMessage("map must not be empty"); } @@ -77,8 +75,7 @@ class RedisSessionMapperTests { sessionMap.put(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, 0L); sessionMap.put(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, 1800); assertThatIllegalStateException().isThrownBy(() -> this.mapper.apply(sessionMap)) - .withMessage( - RedisSessionMapper.CREATION_TIME_KEY + " key must not be null"); + .withMessage(RedisSessionMapper.CREATION_TIME_KEY + " key must not be null"); } @Test @@ -87,8 +84,7 @@ class RedisSessionMapperTests { sessionMap.put(RedisSessionMapper.CREATION_TIME_KEY, 0L); sessionMap.put(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, 1800); assertThatIllegalStateException().isThrownBy(() -> this.mapper.apply(sessionMap)) - .withMessage(RedisSessionMapper.LAST_ACCESSED_TIME_KEY - + " key must not be null"); + .withMessage(RedisSessionMapper.LAST_ACCESSED_TIME_KEY + " key must not be null"); } @Test @@ -97,8 +93,7 @@ class RedisSessionMapperTests { sessionMap.put(RedisSessionMapper.CREATION_TIME_KEY, 0L); sessionMap.put(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, 0L); assertThatIllegalStateException().isThrownBy(() -> this.mapper.apply(sessionMap)) - .withMessage(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY - + " key must not be null"); + .withMessage(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY + " key must not be null"); } @Test diff --git a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/SimpleRedisOperationsSessionRepositoryTests.java b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/SimpleRedisOperationsSessionRepositoryTests.java index 52e7b2b9..4720756f 100644 --- a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/SimpleRedisOperationsSessionRepositoryTests.java +++ b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/SimpleRedisOperationsSessionRepositoryTests.java @@ -70,52 +70,45 @@ class SimpleRedisOperationsSessionRepositoryTests { @BeforeEach void setUp() { MockitoAnnotations.initMocks(this); - given(this.sessionRedisOperations.opsForHash()) - .willReturn(this.sessionHashOperations); - this.sessionRepository = new SimpleRedisOperationsSessionRepository( - this.sessionRedisOperations); + given(this.sessionRedisOperations.opsForHash()).willReturn(this.sessionHashOperations); + this.sessionRepository = new SimpleRedisOperationsSessionRepository(this.sessionRedisOperations); } @Test void constructor_NullRedisOperations_ShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new ReactiveRedisOperationsSessionRepository(null)) + assertThatIllegalArgumentException().isThrownBy(() -> new ReactiveRedisOperationsSessionRepository(null)) .withMessageContaining("sessionRedisOperations cannot be null"); } @Test void setDefaultMaxInactiveInterval_ValidInterval_ShouldSetInterval() { this.sessionRepository.setDefaultMaxInactiveInterval(Duration.ofMinutes(10)); - assertThat(ReflectionTestUtils.getField(this.sessionRepository, - "defaultMaxInactiveInterval")).isEqualTo(Duration.ofMinutes(10)); + assertThat(ReflectionTestUtils.getField(this.sessionRepository, "defaultMaxInactiveInterval")) + .isEqualTo(Duration.ofMinutes(10)); } @Test void setDefaultMaxInactiveInterval_NullInterval_ShouldThrowException() { assertThatIllegalArgumentException() - .isThrownBy( - () -> this.sessionRepository.setDefaultMaxInactiveInterval(null)) + .isThrownBy(() -> this.sessionRepository.setDefaultMaxInactiveInterval(null)) .withMessage("defaultMaxInactiveInterval must not be null"); } @Test void setKeyNamespace_ValidNamespace_ShouldSetNamespace() { this.sessionRepository.setKeyNamespace("test:"); - assertThat(ReflectionTestUtils.getField(this.sessionRepository, "keyNamespace")) - .isEqualTo("test:"); + assertThat(ReflectionTestUtils.getField(this.sessionRepository, "keyNamespace")).isEqualTo("test:"); } @Test void setKeyNamespace_NullNamespace_ShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.sessionRepository.setKeyNamespace(null)) + assertThatIllegalArgumentException().isThrownBy(() -> this.sessionRepository.setKeyNamespace(null)) .withMessage("keyNamespace must not be empty"); } @Test void setKeyNamespace_EmptyNamespace_ShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.sessionRepository.setKeyNamespace(" ")) + assertThatIllegalArgumentException().isThrownBy(() -> this.sessionRepository.setKeyNamespace(" ")) .withMessage("keyNamespace must not be empty"); } @@ -128,16 +121,15 @@ class SimpleRedisOperationsSessionRepositoryTests { @Test void setFlushMode_NullFlushMode_ShouldThrowException() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.sessionRepository.setFlushMode(null)) + assertThatIllegalArgumentException().isThrownBy(() -> this.sessionRepository.setFlushMode(null)) .withMessage("flushMode must not be null"); } @Test void createSession_DefaultMaxInactiveInterval_ShouldCreateSession() { RedisSession redisSession = this.sessionRepository.createSession(); - assertThat(redisSession.getMaxInactiveInterval()).isEqualTo( - Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS)); + assertThat(redisSession.getMaxInactiveInterval()) + .isEqualTo(Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS)); verifyNoMoreInteractions(this.sessionRedisOperations); verifyNoMoreInteractions(this.sessionHashOperations); } @@ -146,8 +138,7 @@ class SimpleRedisOperationsSessionRepositoryTests { void createSession_CustomMaxInactiveInterval_ShouldCreateSession() { this.sessionRepository.setDefaultMaxInactiveInterval(Duration.ofMinutes(10)); RedisSession redisSession = this.sessionRepository.createSession(); - assertThat(redisSession.getMaxInactiveInterval()) - .isEqualTo(Duration.ofMinutes(10)); + assertThat(redisSession.getMaxInactiveInterval()).isEqualTo(Duration.ofMinutes(10)); verifyNoMoreInteractions(this.sessionRedisOperations); verifyNoMoreInteractions(this.sessionHashOperations); } @@ -215,10 +206,8 @@ class SimpleRedisOperationsSessionRepositoryTests { this.sessionRepository.save(session); verify(this.sessionRedisOperations).hasKey(eq(TEST_SESSION_KEY)); verify(this.sessionRedisOperations).opsForHash(); - verify(this.sessionRedisOperations).expireAt(eq(TEST_SESSION_KEY), - eq(getExpiry(session))); - verify(this.sessionHashOperations).putAll(eq(TEST_SESSION_KEY), - this.delta.capture()); + verify(this.sessionRedisOperations).expireAt(eq(TEST_SESSION_KEY), eq(getExpiry(session))); + verify(this.sessionHashOperations).putAll(eq(TEST_SESSION_KEY), this.delta.capture()); assertThat(this.delta.getValue()).hasSize(2); verifyNoMoreInteractions(this.sessionRedisOperations); verifyNoMoreInteractions(this.sessionHashOperations); @@ -237,8 +226,7 @@ class SimpleRedisOperationsSessionRepositoryTests { @Test void save_SessionNotExists_ShouldThrowException() { RedisSession session = createTestSession(); - assertThatIllegalStateException() - .isThrownBy(() -> this.sessionRepository.save(session)) + assertThatIllegalStateException().isThrownBy(() -> this.sessionRepository.save(session)) .withMessage("Session was invalidated"); verify(this.sessionRedisOperations).hasKey(eq(TEST_SESSION_KEY)); verifyNoMoreInteractions(this.sessionRedisOperations); @@ -249,20 +237,18 @@ class SimpleRedisOperationsSessionRepositoryTests { @SuppressWarnings("unchecked") void findById_SessionExists_ShouldReturnSession() { Instant now = Instant.now().truncatedTo(ChronoUnit.MILLIS); - given(this.sessionHashOperations.entries(eq(TEST_SESSION_KEY))).willReturn( - mapOf(RedisSessionMapper.CREATION_TIME_KEY, Instant.EPOCH.toEpochMilli(), + given(this.sessionHashOperations.entries(eq(TEST_SESSION_KEY))) + .willReturn(mapOf(RedisSessionMapper.CREATION_TIME_KEY, Instant.EPOCH.toEpochMilli(), RedisSessionMapper.LAST_ACCESSED_TIME_KEY, now.toEpochMilli(), - RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, - MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS, + RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS, RedisSessionMapper.ATTRIBUTE_PREFIX + "attribute1", "value1")); RedisSession session = this.sessionRepository.findById(TEST_SESSION_ID); assertThat(session.getId()).isEqualTo(TEST_SESSION_ID); assertThat(session.getCreationTime()).isEqualTo(Instant.EPOCH); assertThat(session.getLastAccessedTime()).isEqualTo(now); - assertThat(session.getMaxInactiveInterval()).isEqualTo( - Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS)); - assertThat(session.getAttributeNames()) - .isEqualTo(Collections.singleton("attribute1")); + assertThat(session.getMaxInactiveInterval()) + .isEqualTo(Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS)); + assertThat(session.getAttributeNames()).isEqualTo(Collections.singleton("attribute1")); assertThat(session.getAttribute("attribute1")).isEqualTo("value1"); verify(this.sessionRedisOperations).opsForHash(); verify(this.sessionHashOperations).entries(eq(TEST_SESSION_KEY)); @@ -273,12 +259,11 @@ class SimpleRedisOperationsSessionRepositoryTests { @Test @SuppressWarnings("unchecked") void findById_SessionExistsAndIsExpired_ShouldReturnNull() { - given(this.sessionHashOperations.entries(eq(TEST_SESSION_KEY))).willReturn(mapOf( - RedisSessionMapper.CREATION_TIME_KEY, Instant.EPOCH.toEpochMilli(), - RedisSessionMapper.LAST_ACCESSED_TIME_KEY, Instant.EPOCH.toEpochMilli(), - RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, - MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS, - RedisSessionMapper.ATTRIBUTE_PREFIX + "attribute1", "value1")); + given(this.sessionHashOperations.entries(eq(TEST_SESSION_KEY))) + .willReturn(mapOf(RedisSessionMapper.CREATION_TIME_KEY, Instant.EPOCH.toEpochMilli(), + RedisSessionMapper.LAST_ACCESSED_TIME_KEY, Instant.EPOCH.toEpochMilli(), + RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS, + RedisSessionMapper.ATTRIBUTE_PREFIX + "attribute1", "value1")); assertThat(this.sessionRepository.findById(TEST_SESSION_ID)).isNull(); verify(this.sessionRedisOperations).opsForHash(); verify(this.sessionHashOperations).entries(eq(TEST_SESSION_KEY)); @@ -306,8 +291,7 @@ class SimpleRedisOperationsSessionRepositoryTests { @Test void getSessionRedisOperations__ShouldReturnRedisOperations() { - assertThat(this.sessionRepository.getSessionRedisOperations()) - .isEqualTo(this.sessionRedisOperations); + assertThat(this.sessionRepository.getSessionRedisOperations()).isEqualTo(this.sessionRedisOperations); verifyNoMoreInteractions(this.sessionRedisOperations); verifyNoMoreInteractions(this.sessionHashOperations); } @@ -317,9 +301,8 @@ class SimpleRedisOperationsSessionRepositoryTests { } private static Date getExpiry(RedisSession session) { - return Date - .from(Instant.ofEpochMilli(session.getLastAccessedTime().toEpochMilli()) - .plusSeconds(session.getMaxInactiveInterval().getSeconds())); + return Date.from(Instant.ofEpochMilli(session.getLastAccessedTime().toEpochMilli()) + .plusSeconds(session.getMaxInactiveInterval().getSeconds())); } private static Map mapOf(Object... objects) { diff --git a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/EnableRedisKeyspaceNotificationsInitializerTests.java b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/EnableRedisKeyspaceNotificationsInitializerTests.java index 35d3e614..efbd6c5a 100644 --- a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/EnableRedisKeyspaceNotificationsInitializerTests.java +++ b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/EnableRedisKeyspaceNotificationsInitializerTests.java @@ -36,20 +36,23 @@ import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; -public class EnableRedisKeyspaceNotificationsInitializerTests { - static final String CONFIG_NOTIFY_KEYSPACE_EVENTS = "notify-keyspace-events"; +class EnableRedisKeyspaceNotificationsInitializerTests { + + private static final String CONFIG_NOTIFY_KEYSPACE_EVENTS = "notify-keyspace-events"; @Mock RedisConnectionFactory connectionFactory; + @Mock RedisConnection connection; + @Captor ArgumentCaptor options; - RedisHttpSessionConfiguration.EnableRedisKeyspaceNotificationsInitializer initializer; + private RedisHttpSessionConfiguration.EnableRedisKeyspaceNotificationsInitializer initializer; @BeforeEach - public void setup() { + void setup() { MockitoAnnotations.initMocks(this); given(this.connectionFactory.getConnection()).willReturn(this.connection); @@ -58,7 +61,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests { } @Test - public void afterPropertiesSetUnset() throws Exception { + void afterPropertiesSetUnset() throws Exception { setConfigNotification(""); this.initializer.afterPropertiesSet(); @@ -67,7 +70,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests { } @Test - public void afterPropertiesSetA() throws Exception { + void afterPropertiesSetA() throws Exception { setConfigNotification("A"); this.initializer.afterPropertiesSet(); @@ -76,7 +79,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests { } @Test - public void afterPropertiesSetE() throws Exception { + void afterPropertiesSetE() throws Exception { setConfigNotification("E"); this.initializer.afterPropertiesSet(); @@ -85,7 +88,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests { } @Test - public void afterPropertiesSetK() throws Exception { + void afterPropertiesSetK() throws Exception { setConfigNotification("K"); this.initializer.afterPropertiesSet(); @@ -94,7 +97,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests { } @Test - public void afterPropertiesSetAE() throws Exception { + void afterPropertiesSetAE() throws Exception { setConfigNotification("AE"); this.initializer.afterPropertiesSet(); @@ -103,7 +106,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests { } @Test - public void afterPropertiesSetAK() throws Exception { + void afterPropertiesSetAK() throws Exception { setConfigNotification("AK"); this.initializer.afterPropertiesSet(); @@ -112,7 +115,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests { } @Test - public void afterPropertiesSetEK() throws Exception { + void afterPropertiesSetEK() throws Exception { setConfigNotification("EK"); this.initializer.afterPropertiesSet(); @@ -121,7 +124,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests { } @Test - public void afterPropertiesSetEg() throws Exception { + void afterPropertiesSetEg() throws Exception { setConfigNotification("Eg"); this.initializer.afterPropertiesSet(); @@ -130,7 +133,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests { } @Test - public void afterPropertiesSetE$() throws Exception { + void afterPropertiesSetE$() throws Exception { setConfigNotification("E$"); this.initializer.afterPropertiesSet(); @@ -139,7 +142,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests { } @Test - public void afterPropertiesSetKg() throws Exception { + void afterPropertiesSetKg() throws Exception { setConfigNotification("Kg"); this.initializer.afterPropertiesSet(); @@ -148,7 +151,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests { } @Test - public void afterPropertiesSetAEK() throws Exception { + void afterPropertiesSetAEK() throws Exception { setConfigNotification("AEK"); this.initializer.afterPropertiesSet(); @@ -157,8 +160,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests { } private void assertOptionsContains(String... expectedValues) { - verify(this.connection).setConfig(eq(CONFIG_NOTIFY_KEYSPACE_EVENTS), - this.options.capture()); + verify(this.connection).setConfig(eq(CONFIG_NOTIFY_KEYSPACE_EVENTS), this.options.capture()); for (String expectedValue : expectedValues) { assertThat(this.options.getValue()).contains(expectedValue); } @@ -168,7 +170,7 @@ public class EnableRedisKeyspaceNotificationsInitializerTests { private void setConfigNotification(String value) { Properties properties = new Properties(); properties.setProperty(CONFIG_NOTIFY_KEYSPACE_EVENTS, value); - given(this.connection.getConfig(CONFIG_NOTIFY_KEYSPACE_EVENTS)) - .willReturn(properties); + given(this.connection.getConfig(CONFIG_NOTIFY_KEYSPACE_EVENTS)).willReturn(properties); } + } diff --git a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationClassPathXmlApplicationContextTests.java b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationClassPathXmlApplicationContextTests.java index 1985764c..7ab13ace 100644 --- a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationClassPathXmlApplicationContextTests.java +++ b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationClassPathXmlApplicationContextTests.java @@ -41,7 +41,7 @@ public class RedisHttpSessionConfigurationClassPathXmlApplicationContextTests { // gh-318 @Test - public void contextLoads() { + void contextLoads() { } static RedisConnectionFactory connectionFactory() { @@ -52,4 +52,5 @@ public class RedisHttpSessionConfigurationClassPathXmlApplicationContextTests { return factory; } + } diff --git a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationMockTests.java b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationMockTests.java index 5a28cf1d..e5c7af66 100644 --- a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationMockTests.java +++ b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationMockTests.java @@ -32,23 +32,25 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; -public class RedisHttpSessionConfigurationMockTests { +class RedisHttpSessionConfigurationMockTests { + @Mock RedisConnectionFactory factory; + @Mock RedisConnection connection; @BeforeEach - public void setup() { + void setup() { MockitoAnnotations.initMocks(this); given(this.factory.getConnection()).willReturn(this.connection); } @Test - public void enableRedisKeyspaceNotificationsInitializerAfterPropertiesSetWhenNoOpThenNoInteractionWithConnectionFactory() + void enableRedisKeyspaceNotificationsInitializerAfterPropertiesSetWhenNoOpThenNoInteractionWithConnectionFactory() throws Exception { - EnableRedisKeyspaceNotificationsInitializer init = new EnableRedisKeyspaceNotificationsInitializer( - this.factory, ConfigureRedisAction.NO_OP); + EnableRedisKeyspaceNotificationsInitializer init = new EnableRedisKeyspaceNotificationsInitializer(this.factory, + ConfigureRedisAction.NO_OP); init.afterPropertiesSet(); @@ -56,13 +58,13 @@ public class RedisHttpSessionConfigurationMockTests { } @Test - public void enableRedisKeyspaceNotificationsInitializerAfterPropertiesSetWhenExceptionThenCloseConnection() + void enableRedisKeyspaceNotificationsInitializerAfterPropertiesSetWhenExceptionThenCloseConnection() throws Exception { ConfigureRedisAction action = mock(ConfigureRedisAction.class); willThrow(new RuntimeException()).given(action).configure(this.connection); - EnableRedisKeyspaceNotificationsInitializer init = new EnableRedisKeyspaceNotificationsInitializer( - this.factory, action); + EnableRedisKeyspaceNotificationsInitializer init = new EnableRedisKeyspaceNotificationsInitializer(this.factory, + action); try { init.afterPropertiesSet(); @@ -75,15 +77,16 @@ public class RedisHttpSessionConfigurationMockTests { } @Test - public void enableRedisKeyspaceNotificationsInitializerAfterPropertiesSetWhenNoExceptionThenCloseConnection() + void enableRedisKeyspaceNotificationsInitializerAfterPropertiesSetWhenNoExceptionThenCloseConnection() throws Exception { ConfigureRedisAction action = mock(ConfigureRedisAction.class); - EnableRedisKeyspaceNotificationsInitializer init = new EnableRedisKeyspaceNotificationsInitializer( - this.factory, action); + EnableRedisKeyspaceNotificationsInitializer init = new EnableRedisKeyspaceNotificationsInitializer(this.factory, + action); init.afterPropertiesSet(); verify(this.connection).close(); } + } diff --git a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationNoOpConfigureRedisActionTests.java b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationNoOpConfigureRedisActionTests.java index bb4d4aba..60a0ab9c 100644 --- a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationNoOpConfigureRedisActionTests.java +++ b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationNoOpConfigureRedisActionTests.java @@ -35,10 +35,10 @@ import static org.mockito.Mockito.mock; @ExtendWith(SpringExtension.class) @ContextConfiguration @WebAppConfiguration -public class RedisHttpSessionConfigurationNoOpConfigureRedisActionTests { +class RedisHttpSessionConfigurationNoOpConfigureRedisActionTests { @Test - public void redisConnectionFactoryNotUsedSinceNoValidation() { + void redisConnectionFactoryNotUsedSinceNoValidation() { } @EnableRedisHttpSession @@ -54,5 +54,7 @@ public class RedisHttpSessionConfigurationNoOpConfigureRedisActionTests { public RedisConnectionFactory redisConnectionFactory() { return mock(RedisConnectionFactory.class); } + } + } diff --git a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationOverrideDefaultSerializerTests.java b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationOverrideDefaultSerializerTests.java index 16b1baec..bdd2c58d 100644 --- a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationOverrideDefaultSerializerTests.java +++ b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationOverrideDefaultSerializerTests.java @@ -46,7 +46,7 @@ import static org.mockito.Mockito.mock; @ExtendWith(SpringExtension.class) @ContextConfiguration @WebAppConfiguration -public class RedisHttpSessionConfigurationOverrideDefaultSerializerTests { +class RedisHttpSessionConfigurationOverrideDefaultSerializerTests { @SpringSessionRedisOperations RedisTemplate template; @@ -55,14 +55,14 @@ public class RedisHttpSessionConfigurationOverrideDefaultSerializerTests { RedisSerializer defaultRedisSerializer; @Test - public void overrideDefaultRedisTemplate() { - assertThat(this.template.getDefaultSerializer()) - .isSameAs(this.defaultRedisSerializer); + void overrideDefaultRedisTemplate() { + assertThat(this.template.getDefaultSerializer()).isSameAs(this.defaultRedisSerializer); } @EnableRedisHttpSession @Configuration static class Config { + @Bean @SuppressWarnings("unchecked") public RedisSerializer springSessionDefaultRedisSerializer() { @@ -78,5 +78,7 @@ public class RedisHttpSessionConfigurationOverrideDefaultSerializerTests { return factory; } + } + } diff --git a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationOverrideSessionTaskExecutor.java b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationOverrideSessionTaskExecutor.java index db561821..d296fa20 100644 --- a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationOverrideSessionTaskExecutor.java +++ b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationOverrideSessionTaskExecutor.java @@ -47,7 +47,7 @@ import static org.mockito.Mockito.verify; @ExtendWith(SpringExtension.class) @ContextConfiguration @WebAppConfiguration -public class RedisHttpSessionConfigurationOverrideSessionTaskExecutor { +class RedisHttpSessionConfigurationOverrideSessionTaskExecutor { @Autowired RedisMessageListenerContainer redisMessageListenerContainer; @@ -56,14 +56,14 @@ public class RedisHttpSessionConfigurationOverrideSessionTaskExecutor { Executor springSessionRedisTaskExecutor; @Test - public void overrideSessionTaskExecutor() { - verify(this.springSessionRedisTaskExecutor, times(1)) - .execute(any(SchedulingAwareRunnable.class)); + void overrideSessionTaskExecutor() { + verify(this.springSessionRedisTaskExecutor, times(1)).execute(any(SchedulingAwareRunnable.class)); } @EnableRedisHttpSession @Configuration static class Config { + @Bean public Executor springSessionRedisTaskExecutor() { return mock(Executor.class); @@ -78,5 +78,7 @@ public class RedisHttpSessionConfigurationOverrideSessionTaskExecutor { return factory; } + } + } diff --git a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationOverrideSessionTaskExecutors.java b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationOverrideSessionTaskExecutors.java index 9b7a9913..d5f328cb 100644 --- a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationOverrideSessionTaskExecutors.java +++ b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationOverrideSessionTaskExecutors.java @@ -49,7 +49,7 @@ import static org.mockito.Mockito.verify; @ExtendWith(SpringExtension.class) @ContextConfiguration @WebAppConfiguration -public class RedisHttpSessionConfigurationOverrideSessionTaskExecutors { +class RedisHttpSessionConfigurationOverrideSessionTaskExecutors { @Autowired RedisMessageListenerContainer redisMessageListenerContainer; @@ -61,15 +61,15 @@ public class RedisHttpSessionConfigurationOverrideSessionTaskExecutors { Executor springSessionRedisSubscriptionExecutor; @Test - public void overrideSessionTaskExecutors() { - verify(this.springSessionRedisSubscriptionExecutor, times(1)) - .execute(any(SchedulingAwareRunnable.class)); + void overrideSessionTaskExecutors() { + verify(this.springSessionRedisSubscriptionExecutor, times(1)).execute(any(SchedulingAwareRunnable.class)); verify(this.springSessionRedisTaskExecutor, never()).execute(any(Runnable.class)); } @EnableRedisHttpSession @Configuration static class Config { + @Bean public Executor springSessionRedisTaskExecutor() { return mock(Executor.class); @@ -89,5 +89,7 @@ public class RedisHttpSessionConfigurationOverrideSessionTaskExecutors { return factory; } + } + } diff --git a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationTests.java b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationTests.java index ab78e027..5bc7f60c 100644 --- a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationTests.java +++ b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationTests.java @@ -51,156 +51,137 @@ import static org.mockito.Mockito.mock; * @author Mark Paluch * @author Vedran Pavic */ -public class RedisHttpSessionConfigurationTests { +class RedisHttpSessionConfigurationTests { private static final String CLEANUP_CRON_EXPRESSION = "0 0 * * * *"; private AnnotationConfigApplicationContext context; @BeforeEach - public void before() { + void before() { this.context = new AnnotationConfigApplicationContext(); } @AfterEach - public void after() { + void after() { if (this.context != null) { this.context.close(); } } @Test - public void resolveValue() { + void resolveValue() { registerAndRefresh(RedisConfig.class, CustomRedisHttpSessionConfiguration.class); - RedisHttpSessionConfiguration configuration = this.context - .getBean(RedisHttpSessionConfiguration.class); - assertThat(ReflectionTestUtils.getField(configuration, "redisNamespace")) - .isEqualTo("myRedisNamespace"); + RedisHttpSessionConfiguration configuration = this.context.getBean(RedisHttpSessionConfiguration.class); + assertThat(ReflectionTestUtils.getField(configuration, "redisNamespace")).isEqualTo("myRedisNamespace"); } @Test - public void resolveValueByPlaceholder() { - this.context.setEnvironment(new MockEnvironment() - .withProperty("session.redis.namespace", "customRedisNamespace")); + void resolveValueByPlaceholder() { + this.context + .setEnvironment(new MockEnvironment().withProperty("session.redis.namespace", "customRedisNamespace")); registerAndRefresh(RedisConfig.class, PropertySourceConfiguration.class, CustomRedisHttpSessionConfiguration2.class); - RedisHttpSessionConfiguration configuration = this.context - .getBean(RedisHttpSessionConfiguration.class); - assertThat(ReflectionTestUtils.getField(configuration, "redisNamespace")) - .isEqualTo("customRedisNamespace"); + RedisHttpSessionConfiguration configuration = this.context.getBean(RedisHttpSessionConfiguration.class); + assertThat(ReflectionTestUtils.getField(configuration, "redisNamespace")).isEqualTo("customRedisNamespace"); } @Test - public void customCleanupCronAnnotation() { - registerAndRefresh(RedisConfig.class, - CustomCleanupCronExpressionAnnotationConfiguration.class); + void customCleanupCronAnnotation() { + registerAndRefresh(RedisConfig.class, CustomCleanupCronExpressionAnnotationConfiguration.class); - RedisHttpSessionConfiguration configuration = this.context - .getBean(RedisHttpSessionConfiguration.class); + RedisHttpSessionConfiguration configuration = this.context.getBean(RedisHttpSessionConfiguration.class); assertThat(configuration).isNotNull(); - assertThat(ReflectionTestUtils.getField(configuration, "cleanupCron")) - .isEqualTo(CLEANUP_CRON_EXPRESSION); + assertThat(ReflectionTestUtils.getField(configuration, "cleanupCron")).isEqualTo(CLEANUP_CRON_EXPRESSION); } @Test - public void customCleanupCronSetter() { - registerAndRefresh(RedisConfig.class, - CustomCleanupCronExpressionSetterConfiguration.class); + void customCleanupCronSetter() { + registerAndRefresh(RedisConfig.class, CustomCleanupCronExpressionSetterConfiguration.class); - RedisHttpSessionConfiguration configuration = this.context - .getBean(RedisHttpSessionConfiguration.class); + RedisHttpSessionConfiguration configuration = this.context.getBean(RedisHttpSessionConfiguration.class); assertThat(configuration).isNotNull(); - assertThat(ReflectionTestUtils.getField(configuration, "cleanupCron")) - .isEqualTo(CLEANUP_CRON_EXPRESSION); + assertThat(ReflectionTestUtils.getField(configuration, "cleanupCron")).isEqualTo(CLEANUP_CRON_EXPRESSION); } @Test - public void qualifiedConnectionFactoryRedisConfig() { - registerAndRefresh(RedisConfig.class, - QualifiedConnectionFactoryRedisConfig.class); + void qualifiedConnectionFactoryRedisConfig() { + registerAndRefresh(RedisConfig.class, QualifiedConnectionFactoryRedisConfig.class); - RedisOperationsSessionRepository repository = this.context - .getBean(RedisOperationsSessionRepository.class); - RedisConnectionFactory redisConnectionFactory = this.context - .getBean("qualifiedRedisConnectionFactory", RedisConnectionFactory.class); + RedisOperationsSessionRepository repository = this.context.getBean(RedisOperationsSessionRepository.class); + RedisConnectionFactory redisConnectionFactory = this.context.getBean("qualifiedRedisConnectionFactory", + RedisConnectionFactory.class); assertThat(repository).isNotNull(); assertThat(redisConnectionFactory).isNotNull(); - RedisOperations redisOperations = (RedisOperations) ReflectionTestUtils - .getField(repository, "sessionRedisOperations"); + RedisOperations redisOperations = (RedisOperations) ReflectionTestUtils.getField(repository, + "sessionRedisOperations"); assertThat(redisOperations).isNotNull(); assertThat(ReflectionTestUtils.getField(redisOperations, "connectionFactory")) .isEqualTo(redisConnectionFactory); } @Test - public void primaryConnectionFactoryRedisConfig() { + void primaryConnectionFactoryRedisConfig() { registerAndRefresh(RedisConfig.class, PrimaryConnectionFactoryRedisConfig.class); - RedisOperationsSessionRepository repository = this.context - .getBean(RedisOperationsSessionRepository.class); - RedisConnectionFactory redisConnectionFactory = this.context - .getBean("primaryRedisConnectionFactory", RedisConnectionFactory.class); + RedisOperationsSessionRepository repository = this.context.getBean(RedisOperationsSessionRepository.class); + RedisConnectionFactory redisConnectionFactory = this.context.getBean("primaryRedisConnectionFactory", + RedisConnectionFactory.class); assertThat(repository).isNotNull(); assertThat(redisConnectionFactory).isNotNull(); - RedisOperations redisOperations = (RedisOperations) ReflectionTestUtils - .getField(repository, "sessionRedisOperations"); + RedisOperations redisOperations = (RedisOperations) ReflectionTestUtils.getField(repository, + "sessionRedisOperations"); assertThat(redisOperations).isNotNull(); assertThat(ReflectionTestUtils.getField(redisOperations, "connectionFactory")) .isEqualTo(redisConnectionFactory); } @Test - public void qualifiedAndPrimaryConnectionFactoryRedisConfig() { - registerAndRefresh(RedisConfig.class, - QualifiedAndPrimaryConnectionFactoryRedisConfig.class); + void qualifiedAndPrimaryConnectionFactoryRedisConfig() { + registerAndRefresh(RedisConfig.class, QualifiedAndPrimaryConnectionFactoryRedisConfig.class); - RedisOperationsSessionRepository repository = this.context - .getBean(RedisOperationsSessionRepository.class); - RedisConnectionFactory redisConnectionFactory = this.context - .getBean("qualifiedRedisConnectionFactory", RedisConnectionFactory.class); + RedisOperationsSessionRepository repository = this.context.getBean(RedisOperationsSessionRepository.class); + RedisConnectionFactory redisConnectionFactory = this.context.getBean("qualifiedRedisConnectionFactory", + RedisConnectionFactory.class); assertThat(repository).isNotNull(); assertThat(redisConnectionFactory).isNotNull(); - RedisOperations redisOperations = (RedisOperations) ReflectionTestUtils - .getField(repository, "sessionRedisOperations"); + RedisOperations redisOperations = (RedisOperations) ReflectionTestUtils.getField(repository, + "sessionRedisOperations"); assertThat(redisOperations).isNotNull(); assertThat(ReflectionTestUtils.getField(redisOperations, "connectionFactory")) .isEqualTo(redisConnectionFactory); } @Test - public void namedConnectionFactoryRedisConfig() { + void namedConnectionFactoryRedisConfig() { registerAndRefresh(RedisConfig.class, NamedConnectionFactoryRedisConfig.class); - RedisOperationsSessionRepository repository = this.context - .getBean(RedisOperationsSessionRepository.class); - RedisConnectionFactory redisConnectionFactory = this.context - .getBean("redisConnectionFactory", RedisConnectionFactory.class); + RedisOperationsSessionRepository repository = this.context.getBean(RedisOperationsSessionRepository.class); + RedisConnectionFactory redisConnectionFactory = this.context.getBean("redisConnectionFactory", + RedisConnectionFactory.class); assertThat(repository).isNotNull(); assertThat(redisConnectionFactory).isNotNull(); - RedisOperations redisOperations = (RedisOperations) ReflectionTestUtils - .getField(repository, "sessionRedisOperations"); + RedisOperations redisOperations = (RedisOperations) ReflectionTestUtils.getField(repository, + "sessionRedisOperations"); assertThat(redisOperations).isNotNull(); assertThat(ReflectionTestUtils.getField(redisOperations, "connectionFactory")) .isEqualTo(redisConnectionFactory); } @Test - public void multipleConnectionFactoryRedisConfig() { + void multipleConnectionFactoryRedisConfig() { assertThatExceptionOfType(BeanCreationException.class) - .isThrownBy(() -> registerAndRefresh(RedisConfig.class, - MultipleConnectionFactoryRedisConfig.class)) + .isThrownBy(() -> registerAndRefresh(RedisConfig.class, MultipleConnectionFactoryRedisConfig.class)) .withMessageContaining("expected single matching bean but found 2"); } @Test // gh-1252 - public void customRedisMessageListenerContainerConfig() { - registerAndRefresh(RedisConfig.class, - CustomRedisMessageListenerContainerConfig.class); + void customRedisMessageListenerContainerConfig() { + registerAndRefresh(RedisConfig.class, CustomRedisMessageListenerContainerConfig.class); Map beans = this.context .getBeansOfType(RedisMessageListenerContainer.class); assertThat(beans).hasSize(2); - assertThat(beans).containsKeys("springSessionRedisMessageListenerContainer", - "redisMessageListenerContainer"); + assertThat(beans).containsKeys("springSessionRedisMessageListenerContainer", "redisMessageListenerContainer"); } private void registerAndRefresh(Class... annotatedClasses) { @@ -242,8 +223,7 @@ public class RedisHttpSessionConfigurationTests { } @Configuration - static class CustomCleanupCronExpressionSetterConfiguration - extends RedisHttpSessionConfiguration { + static class CustomCleanupCronExpressionSetterConfiguration extends RedisHttpSessionConfiguration { CustomCleanupCronExpressionSetterConfiguration() { setCleanupCron(CLEANUP_CRON_EXPRESSION); diff --git a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationXmlCustomExpireTests.java b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationXmlCustomExpireTests.java index fd118247..0f408e02 100644 --- a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationXmlCustomExpireTests.java +++ b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationXmlCustomExpireTests.java @@ -37,7 +37,7 @@ import static org.mockito.Mockito.mock; public class RedisHttpSessionConfigurationXmlCustomExpireTests { @Test - public void contextLoads() { + void contextLoads() { } static RedisConnectionFactory connectionFactory() { @@ -48,4 +48,5 @@ public class RedisHttpSessionConfigurationXmlCustomExpireTests { return factory; } + } diff --git a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationXmlTests.java b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationXmlTests.java index bc81be91..5f7a00c9 100644 --- a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationXmlTests.java +++ b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfigurationXmlTests.java @@ -37,7 +37,7 @@ import static org.mockito.Mockito.mock; public class RedisHttpSessionConfigurationXmlTests { @Test - public void contextLoads() { + void contextLoads() { } static RedisConnectionFactory connectionFactory() { @@ -48,4 +48,5 @@ public class RedisHttpSessionConfigurationXmlTests { return factory; } + } diff --git a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/gh109/Gh109Tests.java b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/gh109/Gh109Tests.java index a1384b5c..12e007db 100644 --- a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/gh109/Gh109Tests.java +++ b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/http/gh109/Gh109Tests.java @@ -47,10 +47,10 @@ import static org.mockito.Mockito.mock; @ExtendWith(SpringExtension.class) @ContextConfiguration @WebAppConfiguration -public class Gh109Tests { +class Gh109Tests { @Test - public void loads() { + void loads() { } @@ -63,8 +63,7 @@ public class Gh109Tests { * override sessionRepository construction to set the custom session-timeout */ @Bean - public RedisOperationsSessionRepository sessionRepository( - RedisOperations sessionRedisTemplate, + public RedisOperationsSessionRepository sessionRepository(RedisOperations sessionRedisTemplate, ApplicationEventPublisher applicationEventPublisher) { RedisOperationsSessionRepository sessionRepository = new RedisOperationsSessionRepository( sessionRedisTemplate); @@ -80,5 +79,7 @@ public class Gh109Tests { given(connection.getConfig(anyString())).willReturn(new Properties()); return factory; } + } + } diff --git a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/server/RedisWebSessionConfigurationTests.java b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/server/RedisWebSessionConfigurationTests.java index 2ab4a264..a55b2596 100644 --- a/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/server/RedisWebSessionConfigurationTests.java +++ b/spring-session-data-redis/src/test/java/org/springframework/session/data/redis/config/annotation/web/server/RedisWebSessionConfigurationTests.java @@ -44,7 +44,7 @@ import static org.mockito.Mockito.mock; * * @author Vedran Pavic */ -public class RedisWebSessionConfigurationTests { +class RedisWebSessionConfigurationTests { private static final String REDIS_NAMESPACE = "testNamespace"; @@ -53,19 +53,19 @@ public class RedisWebSessionConfigurationTests { private AnnotationConfigApplicationContext context; @BeforeEach - public void before() { + void before() { this.context = new AnnotationConfigApplicationContext(); } @AfterEach - public void after() { + void after() { if (this.context != null) { this.context.close(); } } @Test - public void defaultConfiguration() { + void defaultConfiguration() { registerAndRefresh(RedisConfig.class, DefaultConfig.class); ReactiveRedisOperationsSessionRepository repository = this.context @@ -74,34 +74,31 @@ public class RedisWebSessionConfigurationTests { } @Test - public void springSessionRedisOperationsResolvingConfiguration() { - registerAndRefresh(RedisConfig.class, - SpringSessionRedisOperationsResolvingConfig.class); + void springSessionRedisOperationsResolvingConfiguration() { + registerAndRefresh(RedisConfig.class, SpringSessionRedisOperationsResolvingConfig.class); ReactiveRedisOperationsSessionRepository repository = this.context .getBean(ReactiveRedisOperationsSessionRepository.class); assertThat(repository).isNotNull(); ReactiveRedisOperations springSessionRedisOperations = this.context - .getBean(SpringSessionRedisOperationsResolvingConfig.class) - .getSpringSessionRedisOperations(); + .getBean(SpringSessionRedisOperationsResolvingConfig.class).getSpringSessionRedisOperations(); assertThat(springSessionRedisOperations).isNotNull(); - assertThat((ReactiveRedisOperations) ReflectionTestUtils.getField(repository, - "sessionRedisOperations")).isEqualTo(springSessionRedisOperations); + assertThat((ReactiveRedisOperations) ReflectionTestUtils.getField(repository, "sessionRedisOperations")) + .isEqualTo(springSessionRedisOperations); } @Test - public void customNamespace() { + void customNamespace() { registerAndRefresh(RedisConfig.class, CustomNamespaceConfig.class); ReactiveRedisOperationsSessionRepository repository = this.context .getBean(ReactiveRedisOperationsSessionRepository.class); assertThat(repository).isNotNull(); - assertThat(ReflectionTestUtils.getField(repository, "namespace")) - .isEqualTo(REDIS_NAMESPACE + ":"); + assertThat(ReflectionTestUtils.getField(repository, "namespace")).isEqualTo(REDIS_NAMESPACE + ":"); } @Test - public void customMaxInactiveInterval() { + void customMaxInactiveInterval() { registerAndRefresh(RedisConfig.class, CustomMaxInactiveIntervalConfig.class); ReactiveRedisOperationsSessionRepository repository = this.context @@ -112,121 +109,112 @@ public class RedisWebSessionConfigurationTests { } @Test - public void customFlushMode() { + void customFlushMode() { registerAndRefresh(RedisConfig.class, CustomFlushModeConfig.class); ReactiveRedisOperationsSessionRepository repository = this.context .getBean(ReactiveRedisOperationsSessionRepository.class); assertThat(repository).isNotNull(); - assertThat(ReflectionTestUtils.getField(repository, "redisFlushMode")) - .isEqualTo(RedisFlushMode.IMMEDIATE); + assertThat(ReflectionTestUtils.getField(repository, "redisFlushMode")).isEqualTo(RedisFlushMode.IMMEDIATE); } @Test - public void qualifiedConnectionFactoryRedisConfig() { - registerAndRefresh(RedisConfig.class, - QualifiedConnectionFactoryRedisConfig.class); + void qualifiedConnectionFactoryRedisConfig() { + registerAndRefresh(RedisConfig.class, QualifiedConnectionFactoryRedisConfig.class); ReactiveRedisOperationsSessionRepository repository = this.context .getBean(ReactiveRedisOperationsSessionRepository.class); - ReactiveRedisConnectionFactory redisConnectionFactory = this.context.getBean( - "qualifiedRedisConnectionFactory", ReactiveRedisConnectionFactory.class); + ReactiveRedisConnectionFactory redisConnectionFactory = this.context.getBean("qualifiedRedisConnectionFactory", + ReactiveRedisConnectionFactory.class); assertThat(repository).isNotNull(); assertThat(redisConnectionFactory).isNotNull(); - ReactiveRedisOperations redisOperations = (ReactiveRedisOperations) ReflectionTestUtils - .getField(repository, "sessionRedisOperations"); + ReactiveRedisOperations redisOperations = (ReactiveRedisOperations) ReflectionTestUtils.getField(repository, + "sessionRedisOperations"); assertThat(redisOperations).isNotNull(); assertThat(ReflectionTestUtils.getField(redisOperations, "connectionFactory")) .isEqualTo(redisConnectionFactory); } @Test - public void primaryConnectionFactoryRedisConfig() { + void primaryConnectionFactoryRedisConfig() { registerAndRefresh(RedisConfig.class, PrimaryConnectionFactoryRedisConfig.class); ReactiveRedisOperationsSessionRepository repository = this.context .getBean(ReactiveRedisOperationsSessionRepository.class); - ReactiveRedisConnectionFactory redisConnectionFactory = this.context.getBean( - "primaryRedisConnectionFactory", ReactiveRedisConnectionFactory.class); + ReactiveRedisConnectionFactory redisConnectionFactory = this.context.getBean("primaryRedisConnectionFactory", + ReactiveRedisConnectionFactory.class); assertThat(repository).isNotNull(); assertThat(redisConnectionFactory).isNotNull(); - ReactiveRedisOperations redisOperations = (ReactiveRedisOperations) ReflectionTestUtils - .getField(repository, "sessionRedisOperations"); + ReactiveRedisOperations redisOperations = (ReactiveRedisOperations) ReflectionTestUtils.getField(repository, + "sessionRedisOperations"); assertThat(redisOperations).isNotNull(); assertThat(ReflectionTestUtils.getField(redisOperations, "connectionFactory")) .isEqualTo(redisConnectionFactory); } @Test - public void qualifiedAndPrimaryConnectionFactoryRedisConfig() { - registerAndRefresh(RedisConfig.class, - QualifiedAndPrimaryConnectionFactoryRedisConfig.class); + void qualifiedAndPrimaryConnectionFactoryRedisConfig() { + registerAndRefresh(RedisConfig.class, QualifiedAndPrimaryConnectionFactoryRedisConfig.class); ReactiveRedisOperationsSessionRepository repository = this.context .getBean(ReactiveRedisOperationsSessionRepository.class); - ReactiveRedisConnectionFactory redisConnectionFactory = this.context.getBean( - "qualifiedRedisConnectionFactory", ReactiveRedisConnectionFactory.class); + ReactiveRedisConnectionFactory redisConnectionFactory = this.context.getBean("qualifiedRedisConnectionFactory", + ReactiveRedisConnectionFactory.class); assertThat(repository).isNotNull(); assertThat(redisConnectionFactory).isNotNull(); - ReactiveRedisOperations redisOperations = (ReactiveRedisOperations) ReflectionTestUtils - .getField(repository, "sessionRedisOperations"); + ReactiveRedisOperations redisOperations = (ReactiveRedisOperations) ReflectionTestUtils.getField(repository, + "sessionRedisOperations"); assertThat(redisOperations).isNotNull(); assertThat(ReflectionTestUtils.getField(redisOperations, "connectionFactory")) .isEqualTo(redisConnectionFactory); } @Test - public void namedConnectionFactoryRedisConfig() { + void namedConnectionFactoryRedisConfig() { registerAndRefresh(RedisConfig.class, NamedConnectionFactoryRedisConfig.class); ReactiveRedisOperationsSessionRepository repository = this.context .getBean(ReactiveRedisOperationsSessionRepository.class); - ReactiveRedisConnectionFactory redisConnectionFactory = this.context - .getBean("redisConnectionFactory", ReactiveRedisConnectionFactory.class); + ReactiveRedisConnectionFactory redisConnectionFactory = this.context.getBean("redisConnectionFactory", + ReactiveRedisConnectionFactory.class); assertThat(repository).isNotNull(); assertThat(redisConnectionFactory).isNotNull(); - ReactiveRedisOperations redisOperations = (ReactiveRedisOperations) ReflectionTestUtils - .getField(repository, "sessionRedisOperations"); + ReactiveRedisOperations redisOperations = (ReactiveRedisOperations) ReflectionTestUtils.getField(repository, + "sessionRedisOperations"); assertThat(redisOperations).isNotNull(); assertThat(ReflectionTestUtils.getField(redisOperations, "connectionFactory")) .isEqualTo(redisConnectionFactory); } @Test - public void multipleConnectionFactoryRedisConfig() { + void multipleConnectionFactoryRedisConfig() { assertThatExceptionOfType(BeanCreationException.class) - .isThrownBy(() -> registerAndRefresh(RedisConfig.class, - MultipleConnectionFactoryRedisConfig.class)) + .isThrownBy(() -> registerAndRefresh(RedisConfig.class, MultipleConnectionFactoryRedisConfig.class)) .withMessageContaining("expected single matching bean but found 2"); } @Test @SuppressWarnings("unchecked") - public void customRedisSerializerConfig() { + void customRedisSerializerConfig() { registerAndRefresh(RedisConfig.class, CustomRedisSerializerConfig.class); ReactiveRedisOperationsSessionRepository repository = this.context .getBean(ReactiveRedisOperationsSessionRepository.class); - RedisSerializer redisSerializer = this.context - .getBean("springSessionDefaultRedisSerializer", RedisSerializer.class); + RedisSerializer redisSerializer = this.context.getBean("springSessionDefaultRedisSerializer", + RedisSerializer.class); assertThat(repository).isNotNull(); assertThat(redisSerializer).isNotNull(); - ReactiveRedisOperations redisOperations = (ReactiveRedisOperations) ReflectionTestUtils - .getField(repository, "sessionRedisOperations"); + ReactiveRedisOperations redisOperations = (ReactiveRedisOperations) ReflectionTestUtils.getField(repository, + "sessionRedisOperations"); assertThat(redisOperations).isNotNull(); - RedisSerializationContext serializationContext = redisOperations - .getSerializationContext(); - assertThat(ReflectionTestUtils.getField( - serializationContext.getValueSerializationPair().getReader(), + RedisSerializationContext serializationContext = redisOperations.getSerializationContext(); + assertThat(ReflectionTestUtils.getField(serializationContext.getValueSerializationPair().getReader(), "serializer")).isEqualTo(redisSerializer); - assertThat(ReflectionTestUtils.getField( - serializationContext.getValueSerializationPair().getWriter(), + assertThat(ReflectionTestUtils.getField(serializationContext.getValueSerializationPair().getWriter(), "serializer")).isEqualTo(redisSerializer); - assertThat(ReflectionTestUtils.getField( - serializationContext.getHashValueSerializationPair().getReader(), + assertThat(ReflectionTestUtils.getField(serializationContext.getHashValueSerializationPair().getReader(), "serializer")).isEqualTo(redisSerializer); - assertThat(ReflectionTestUtils.getField( - serializationContext.getHashValueSerializationPair().getWriter(), + assertThat(ReflectionTestUtils.getField(serializationContext.getHashValueSerializationPair().getWriter(), "serializer")).isEqualTo(redisSerializer); } @@ -256,7 +244,7 @@ public class RedisWebSessionConfigurationTests { @SpringSessionRedisOperations private ReactiveRedisOperations springSessionRedisOperations; - public ReactiveRedisOperations getSpringSessionRedisOperations() { + ReactiveRedisOperations getSpringSessionRedisOperations() { return this.springSessionRedisOperations; } diff --git a/spring-session-docs/src/main/java/docs/Docs.java b/spring-session-docs/src/main/java/docs/Docs.java index 70f4c42f..3d4f665f 100644 --- a/spring-session-docs/src/main/java/docs/Docs.java +++ b/spring-session-docs/src/main/java/docs/Docs.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,4 +17,5 @@ package docs; public class Docs { + } diff --git a/spring-session-docs/src/test/java/docs/FindByIndexNameSessionRepositoryTests.java b/spring-session-docs/src/test/java/docs/FindByIndexNameSessionRepositoryTests.java index 9d6ea283..9514987d 100644 --- a/spring-session-docs/src/test/java/docs/FindByIndexNameSessionRepositoryTests.java +++ b/spring-session-docs/src/test/java/docs/FindByIndexNameSessionRepositoryTests.java @@ -30,9 +30,11 @@ import org.springframework.session.Session; * @author Rob Winch * */ -public class FindByIndexNameSessionRepositoryTests { +class FindByIndexNameSessionRepositoryTests { + @Mock FindByIndexNameSessionRepository sessionRepository; + @Mock Session session; @@ -42,21 +44,20 @@ public class FindByIndexNameSessionRepositoryTests { } @Test - public void setUsername() { + void setUsername() { // tag::set-username[] String username = "username"; - this.session.setAttribute( - FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username); + this.session.setAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username); // end::set-username[] } @Test @SuppressWarnings("unused") - public void findByUsername() { + void findByUsername() { // tag::findby-username[] String username = "username"; - Map sessionIdToSession = this.sessionRepository - .findByPrincipalName(username); + Map sessionIdToSession = this.sessionRepository.findByPrincipalName(username); // end::findby-username[] } + } diff --git a/spring-session-docs/src/test/java/docs/HttpSessionConfigurationNoOpConfigureRedisActionXmlTests.java b/spring-session-docs/src/test/java/docs/HttpSessionConfigurationNoOpConfigureRedisActionXmlTests.java index 9d09145a..f3e3d25d 100644 --- a/spring-session-docs/src/test/java/docs/HttpSessionConfigurationNoOpConfigureRedisActionXmlTests.java +++ b/spring-session-docs/src/test/java/docs/HttpSessionConfigurationNoOpConfigureRedisActionXmlTests.java @@ -37,15 +37,17 @@ import static org.mockito.Mockito.mock; @ContextConfiguration @WebAppConfiguration public class HttpSessionConfigurationNoOpConfigureRedisActionXmlTests { + @Autowired SessionRepositoryFilter filter; @Test - public void redisConnectionFactoryNotUsedSinceNoValidation() { + void redisConnectionFactoryNotUsedSinceNoValidation() { assertThat(this.filter).isNotNull(); } static RedisConnectionFactory connectionFactory() { return mock(RedisConnectionFactory.class); } + } diff --git a/spring-session-docs/src/test/java/docs/IndexDocTests.java b/spring-session-docs/src/test/java/docs/IndexDocTests.java index cfbcc866..3471535d 100644 --- a/spring-session-docs/src/test/java/docs/IndexDocTests.java +++ b/spring-session-docs/src/test/java/docs/IndexDocTests.java @@ -51,11 +51,12 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Rob Winch * @author Vedran Pavic */ -public class IndexDocTests { - static final String ATTR_USER = "user"; +class IndexDocTests { + + private static final String ATTR_USER = "user"; @Test - public void repositoryDemo() { + void repositoryDemo() { RepositoryDemo demo = new RepositoryDemo<>(); demo.repository = new MapSessionRepository(new ConcurrentHashMap<>()); @@ -64,6 +65,7 @@ public class IndexDocTests { // tag::repository-demo[] public class RepositoryDemo { + private SessionRepository repository; // <1> public void demo() { @@ -83,11 +85,12 @@ public class IndexDocTests { } // ... setter methods ... + } // end::repository-demo[] @Test - public void expireRepositoryDemo() { + void expireRepositoryDemo() { ExpiringRepositoryDemo demo = new ExpiringRepositoryDemo<>(); demo.repository = new MapSessionRepository(new ConcurrentHashMap<>()); @@ -96,6 +99,7 @@ public class IndexDocTests { // tag::expire-repository-demo[] public class ExpiringRepositoryDemo { + private SessionRepository repository; // <1> public void demo() { @@ -110,54 +114,51 @@ public class IndexDocTests { } // ... setter methods ... + } // end::expire-repository-demo[] @Test @SuppressWarnings("unused") - public void newRedisOperationsSessionRepository() { + void newRedisOperationsSessionRepository() { // tag::new-redisoperationssessionrepository[] RedisTemplate redisTemplate = new RedisTemplate<>(); // ... configure redisTemplate ... - SessionRepository repository = - new RedisOperationsSessionRepository(redisTemplate); + SessionRepository repository = new RedisOperationsSessionRepository(redisTemplate); // end::new-redisoperationssessionrepository[] } @Test @SuppressWarnings("unused") - public void newReactiveRedisOperationsSessionRepository() { + void newReactiveRedisOperationsSessionRepository() { LettuceConnectionFactory connectionFactory = new LettuceConnectionFactory(); RedisSerializationContext serializationContext = RedisSerializationContext - .newSerializationContext( - new JdkSerializationRedisSerializer()) - .build(); + .newSerializationContext(new JdkSerializationRedisSerializer()).build(); // tag::new-reactiveredisoperationssessionrepository[] // ... create and configure connectionFactory and serializationContext ... - ReactiveRedisTemplate redisTemplate = new ReactiveRedisTemplate<>( - connectionFactory, serializationContext); + ReactiveRedisTemplate redisTemplate = new ReactiveRedisTemplate<>(connectionFactory, + serializationContext); - ReactiveSessionRepository repository = - new ReactiveRedisOperationsSessionRepository(redisTemplate); + ReactiveSessionRepository repository = new ReactiveRedisOperationsSessionRepository( + redisTemplate); // end::new-reactiveredisoperationssessionrepository[] } @Test @SuppressWarnings("unused") - public void mapRepository() { + void mapRepository() { // tag::new-mapsessionrepository[] - SessionRepository repository = new MapSessionRepository( - new ConcurrentHashMap<>()); + SessionRepository repository = new MapSessionRepository(new ConcurrentHashMap<>()); // end::new-mapsessionrepository[] } @Test @SuppressWarnings("unused") - public void newJdbcOperationsSessionRepository() { + void newJdbcOperationsSessionRepository() { // tag::new-jdbcoperationssessionrepository[] JdbcTemplate jdbcTemplate = new JdbcTemplate(); @@ -167,14 +168,14 @@ public class IndexDocTests { // ... configure transactionManager ... - SessionRepository repository = - new JdbcOperationsSessionRepository(jdbcTemplate, transactionManager); + SessionRepository repository = new JdbcOperationsSessionRepository(jdbcTemplate, + transactionManager); // end::new-jdbcoperationssessionrepository[] } @Test @SuppressWarnings("unused") - public void newHazelcastSessionRepository() { + void newHazelcastSessionRepository() { // tag::new-hazelcastsessionrepository[] Config config = new Config(); @@ -183,13 +184,12 @@ public class IndexDocTests { HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance(config); - HazelcastSessionRepository repository = - new HazelcastSessionRepository(hazelcastInstance); + HazelcastSessionRepository repository = new HazelcastSessionRepository(hazelcastInstance); // end::new-hazelcastsessionrepository[] } @Test - public void runSpringHttpSessionConfig() { + void runSpringHttpSessionConfig() { AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); context.register(SpringHttpSessionConfig.class); context.setServletContext(new MockServletContext()); @@ -204,7 +204,10 @@ public class IndexDocTests { } private static final class User { + private User(String username) { } + } + } diff --git a/spring-session-docs/src/test/java/docs/RedisHttpSessionConfigurationNoOpConfigureRedisActionTests.java b/spring-session-docs/src/test/java/docs/RedisHttpSessionConfigurationNoOpConfigureRedisActionTests.java index e6a143bf..0a6afcfd 100644 --- a/spring-session-docs/src/test/java/docs/RedisHttpSessionConfigurationNoOpConfigureRedisActionTests.java +++ b/spring-session-docs/src/test/java/docs/RedisHttpSessionConfigurationNoOpConfigureRedisActionTests.java @@ -36,10 +36,10 @@ import static org.mockito.Mockito.mock; @ExtendWith(SpringExtension.class) @ContextConfiguration @WebAppConfiguration -public class RedisHttpSessionConfigurationNoOpConfigureRedisActionTests { +class RedisHttpSessionConfigurationNoOpConfigureRedisActionTests { @Test - public void redisConnectionFactoryNotUsedSinceNoValidation() { + void redisConnectionFactoryNotUsedSinceNoValidation() { } @EnableRedisHttpSession @@ -57,5 +57,7 @@ public class RedisHttpSessionConfigurationNoOpConfigureRedisActionTests { public RedisConnectionFactory redisConnectionFactory() { return mock(RedisConnectionFactory.class); } + } + } diff --git a/spring-session-docs/src/test/java/docs/SpringHttpSessionConfig.java b/spring-session-docs/src/test/java/docs/SpringHttpSessionConfig.java index eda4724c..f257503b 100644 --- a/spring-session-docs/src/test/java/docs/SpringHttpSessionConfig.java +++ b/spring-session-docs/src/test/java/docs/SpringHttpSessionConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,9 +27,11 @@ import org.springframework.session.config.annotation.web.http.EnableSpringHttpSe @EnableSpringHttpSession @Configuration public class SpringHttpSessionConfig { + @Bean public MapSessionRepository sessionRepository() { return new MapSessionRepository(new ConcurrentHashMap<>()); } + } // end::class[] diff --git a/spring-session-docs/src/test/java/docs/SpringWebSessionConfig.java b/spring-session-docs/src/test/java/docs/SpringWebSessionConfig.java index 85188954..69e22fca 100644 --- a/spring-session-docs/src/test/java/docs/SpringWebSessionConfig.java +++ b/spring-session-docs/src/test/java/docs/SpringWebSessionConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,9 +26,11 @@ import org.springframework.session.config.annotation.web.server.EnableSpringWebS // tag::class[] @EnableSpringWebSession public class SpringWebSessionConfig { + @Bean public ReactiveSessionRepository reactiveSessionRepository() { return new ReactiveMapSessionRepository(new ConcurrentHashMap<>()); } + } // end::class[] diff --git a/spring-session-docs/src/test/java/docs/http/AbstractHttpSessionListenerTests.java b/spring-session-docs/src/test/java/docs/http/AbstractHttpSessionListenerTests.java index 6eb5aa3b..4b5047f8 100644 --- a/spring-session-docs/src/test/java/docs/http/AbstractHttpSessionListenerTests.java +++ b/spring-session-docs/src/test/java/docs/http/AbstractHttpSessionListenerTests.java @@ -45,6 +45,7 @@ import static org.mockito.Mockito.mock; @ExtendWith(SpringExtension.class) @WebAppConfiguration public abstract class AbstractHttpSessionListenerTests { + @Autowired ApplicationEventPublisher publisher; @@ -52,12 +53,10 @@ public abstract class AbstractHttpSessionListenerTests { SecuritySessionDestroyedListener listener; @Test - public void springSessionDestroyedTranslatedToSpringSecurityDestroyed() { + void springSessionDestroyedTranslatedToSpringSecurityDestroyed() { Session session = new MapSession(); - this.publisher.publishEvent( - new org.springframework.session.events.SessionDestroyedEvent(this, - session)); + this.publisher.publishEvent(new org.springframework.session.events.SessionDestroyedEvent(this, session)); assertThat(this.listener.getEvent().getId()).isEqualTo(session.getId()); } @@ -71,8 +70,7 @@ public abstract class AbstractHttpSessionListenerTests { return factory; } - static class SecuritySessionDestroyedListener - implements ApplicationListener { + static class SecuritySessionDestroyedListener implements ApplicationListener { private SessionDestroyedEvent event; @@ -87,8 +85,10 @@ public abstract class AbstractHttpSessionListenerTests { this.event = event; } - public SessionDestroyedEvent getEvent() { + SessionDestroyedEvent getEvent() { return this.event; } + } + } diff --git a/spring-session-docs/src/test/java/docs/http/HazelcastHttpSessionConfig.java b/spring-session-docs/src/test/java/docs/http/HazelcastHttpSessionConfig.java index 159b1b1a..249d7071 100644 --- a/spring-session-docs/src/test/java/docs/http/HazelcastHttpSessionConfig.java +++ b/spring-session-docs/src/test/java/docs/http/HazelcastHttpSessionConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,8 +43,7 @@ public class HazelcastHttpSessionConfig { config.getMapConfig(HazelcastSessionRepository.DEFAULT_SESSION_MAP_NAME) // <2> .addMapAttributeConfig(attributeConfig) - .addMapIndexConfig(new MapIndexConfig( - HazelcastSessionRepository.PRINCIPAL_NAME_ATTRIBUTE, false)); + .addMapIndexConfig(new MapIndexConfig(HazelcastSessionRepository.PRINCIPAL_NAME_ATTRIBUTE, false)); return Hazelcast.newHazelcastInstance(config); // <3> } diff --git a/spring-session-docs/src/test/java/docs/http/HttpSessionListenerJavaConfigTests.java b/spring-session-docs/src/test/java/docs/http/HttpSessionListenerJavaConfigTests.java index 43ca7709..8029d1cd 100644 --- a/spring-session-docs/src/test/java/docs/http/HttpSessionListenerJavaConfigTests.java +++ b/spring-session-docs/src/test/java/docs/http/HttpSessionListenerJavaConfigTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,9 +25,8 @@ import org.springframework.test.context.ContextConfiguration; * @author Rob Winch * */ -@ContextConfiguration(classes = { HttpSessionListenerJavaConfigTests.MockConfig.class, - RedisHttpSessionConfig.class }) -public class HttpSessionListenerJavaConfigTests extends AbstractHttpSessionListenerTests { +@ContextConfiguration(classes = { HttpSessionListenerJavaConfigTests.MockConfig.class, RedisHttpSessionConfig.class }) +class HttpSessionListenerJavaConfigTests extends AbstractHttpSessionListenerTests { @Configuration static class MockConfig { @@ -41,5 +40,7 @@ public class HttpSessionListenerJavaConfigTests extends AbstractHttpSessionListe public SecuritySessionDestroyedListener securitySessionDestroyedListener() { return new SecuritySessionDestroyedListener(); } + } + } diff --git a/spring-session-docs/src/test/java/docs/http/HttpSessionListenerXmlTests.java b/spring-session-docs/src/test/java/docs/http/HttpSessionListenerXmlTests.java index 50e55678..c6c89d67 100644 --- a/spring-session-docs/src/test/java/docs/http/HttpSessionListenerXmlTests.java +++ b/spring-session-docs/src/test/java/docs/http/HttpSessionListenerXmlTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +23,6 @@ import org.springframework.test.context.ContextConfiguration; * */ @ContextConfiguration -public class HttpSessionListenerXmlTests extends AbstractHttpSessionListenerTests { +class HttpSessionListenerXmlTests extends AbstractHttpSessionListenerTests { } diff --git a/spring-session-docs/src/test/java/docs/http/RedisHttpSessionConfig.java b/spring-session-docs/src/test/java/docs/http/RedisHttpSessionConfig.java index fa071425..85caeb48 100644 --- a/spring-session-docs/src/test/java/docs/http/RedisHttpSessionConfig.java +++ b/spring-session-docs/src/test/java/docs/http/RedisHttpSessionConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,5 +32,6 @@ public class RedisHttpSessionConfig { } // ... + } // end::config[] diff --git a/spring-session-docs/src/test/java/docs/security/RememberMeSecurityConfiguration.java b/spring-session-docs/src/test/java/docs/security/RememberMeSecurityConfiguration.java index e99d286c..b120d26e 100644 --- a/spring-session-docs/src/test/java/docs/security/RememberMeSecurityConfiguration.java +++ b/spring-session-docs/src/test/java/docs/security/RememberMeSecurityConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,13 +66,14 @@ public class RememberMeSecurityConfiguration extends WebSecurityConfigurerAdapte @Override @Bean public InMemoryUserDetailsManager userDetailsService() { - return new InMemoryUserDetailsManager(User.withUsername("user") - .password("{noop}password").roles("USER").build()); + return new InMemoryUserDetailsManager( + User.withUsername("user").password("{noop}password").roles("USER").build()); } @Bean MapSessionRepository sessionRepository() { return new MapSessionRepository(new ConcurrentHashMap<>()); } + } // end::class[] diff --git a/spring-session-docs/src/test/java/docs/security/RememberMeSecurityConfigurationTests.java b/spring-session-docs/src/test/java/docs/security/RememberMeSecurityConfigurationTests.java index 502fdebf..3fb66778 100644 --- a/spring-session-docs/src/test/java/docs/security/RememberMeSecurityConfigurationTests.java +++ b/spring-session-docs/src/test/java/docs/security/RememberMeSecurityConfigurationTests.java @@ -49,18 +49,21 @@ import static org.springframework.security.test.web.servlet.setup.SecurityMockMv @ContextConfiguration(classes = RememberMeSecurityConfiguration.class) @WebAppConfiguration @SuppressWarnings("rawtypes") -public class RememberMeSecurityConfigurationTests { +class RememberMeSecurityConfigurationTests { + @Autowired WebApplicationContext context; + @Autowired SessionRepositoryFilter springSessionRepositoryFilter; + @Autowired SessionRepository sessions; - MockMvc mockMvc; + private MockMvc mockMvc; @BeforeEach - public void setup() { + void setup() { // @formatter:off this.mockMvc = MockMvcBuilders .webAppContextSetup(this.context) @@ -71,8 +74,7 @@ public class RememberMeSecurityConfigurationTests { } @Test - public void authenticateWhenSpringSessionRememberMeEnabledThenCookieMaxAgeAndSessionExpirationSet() - throws Exception { + void authenticateWhenSpringSessionRememberMeEnabledThenCookieMaxAgeAndSessionExpirationSet() throws Exception { // @formatter:off MvcResult result = this.mockMvc .perform(formLogin()) @@ -81,10 +83,8 @@ public class RememberMeSecurityConfigurationTests { Cookie cookie = result.getResponse().getCookie("SESSION"); assertThat(cookie.getMaxAge()).isEqualTo(Integer.MAX_VALUE); - T session = this.sessions - .findById(new String(Base64.getDecoder().decode(cookie.getValue()))); - assertThat(session.getMaxInactiveInterval()) - .isEqualTo(Duration.ofDays(30)); + T session = this.sessions.findById(new String(Base64.getDecoder().decode(cookie.getValue()))); + assertThat(session.getMaxInactiveInterval()).isEqualTo(Duration.ofDays(30)); } diff --git a/spring-session-docs/src/test/java/docs/security/RememberMeSecurityConfigurationXmlTests.java b/spring-session-docs/src/test/java/docs/security/RememberMeSecurityConfigurationXmlTests.java index 250684f0..91c99651 100644 --- a/spring-session-docs/src/test/java/docs/security/RememberMeSecurityConfigurationXmlTests.java +++ b/spring-session-docs/src/test/java/docs/security/RememberMeSecurityConfigurationXmlTests.java @@ -49,18 +49,21 @@ import static org.springframework.security.test.web.servlet.setup.SecurityMockMv @ContextConfiguration @WebAppConfiguration @SuppressWarnings("rawtypes") -public class RememberMeSecurityConfigurationXmlTests { +class RememberMeSecurityConfigurationXmlTests { + @Autowired WebApplicationContext context; + @Autowired SessionRepositoryFilter springSessionRepositoryFilter; + @Autowired SessionRepository sessions; - MockMvc mockMvc; + private MockMvc mockMvc; @BeforeEach - public void setup() { + void setup() { // @formatter:off this.mockMvc = MockMvcBuilders .webAppContextSetup(this.context) @@ -71,8 +74,7 @@ public class RememberMeSecurityConfigurationXmlTests { } @Test - public void authenticateWhenSpringSessionRememberMeEnabledThenCookieMaxAgeAndSessionExpirationSet() - throws Exception { + void authenticateWhenSpringSessionRememberMeEnabledThenCookieMaxAgeAndSessionExpirationSet() throws Exception { // @formatter:off MvcResult result = this.mockMvc .perform(formLogin()) @@ -81,10 +83,8 @@ public class RememberMeSecurityConfigurationXmlTests { Cookie cookie = result.getResponse().getCookie("SESSION"); assertThat(cookie.getMaxAge()).isEqualTo(Integer.MAX_VALUE); - T session = this.sessions - .findById(new String(Base64.getDecoder().decode(cookie.getValue()))); - assertThat(session.getMaxInactiveInterval()) - .isEqualTo(Duration.ofDays(30)); + T session = this.sessions.findById(new String(Base64.getDecoder().decode(cookie.getValue()))); + assertThat(session.getMaxInactiveInterval()).isEqualTo(Duration.ofDays(30)); } diff --git a/spring-session-docs/src/test/java/docs/security/SecurityConfiguration.java b/spring-session-docs/src/test/java/docs/security/SecurityConfiguration.java index e62505b2..f59f6698 100644 --- a/spring-session-docs/src/test/java/docs/security/SecurityConfiguration.java +++ b/spring-session-docs/src/test/java/docs/security/SecurityConfiguration.java @@ -30,8 +30,7 @@ import org.springframework.session.security.SpringSessionBackedSessionRegistry; */ // tag::class[] @Configuration -public class SecurityConfiguration - extends WebSecurityConfigurerAdapter { +public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired private FindByIndexNameSessionRepository sessionRepository; @@ -51,5 +50,6 @@ public class SecurityConfiguration public SpringSessionBackedSessionRegistry sessionRegistry() { return new SpringSessionBackedSessionRegistry<>(this.sessionRepository); } + } // end::class[] diff --git a/spring-session-docs/src/test/java/docs/websocket/WebSocketConfig.java b/spring-session-docs/src/test/java/docs/websocket/WebSocketConfig.java index 8301a393..92e07ef5 100644 --- a/spring-session-docs/src/test/java/docs/websocket/WebSocketConfig.java +++ b/spring-session-docs/src/test/java/docs/websocket/WebSocketConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,5 +42,6 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { registry.enableSimpleBroker("/queue/", "/topic/"); registry.setApplicationDestinationPrefixes("/app"); } + } // end::class[] diff --git a/spring-session-hazelcast/src/integration-test/java/org/springframework/session/hazelcast/AbstractHazelcastRepositoryITests.java b/spring-session-hazelcast/src/integration-test/java/org/springframework/session/hazelcast/AbstractHazelcastRepositoryITests.java index 4d21d402..e95c77e2 100644 --- a/spring-session-hazelcast/src/integration-test/java/org/springframework/session/hazelcast/AbstractHazelcastRepositoryITests.java +++ b/spring-session-hazelcast/src/integration-test/java/org/springframework/session/hazelcast/AbstractHazelcastRepositoryITests.java @@ -40,7 +40,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Tommy Ludwig * @author Vedran Pavic */ -public abstract class AbstractHazelcastRepositoryITests { +abstract class AbstractHazelcastRepositoryITests { private static final String SPRING_SECURITY_CONTEXT = "SPRING_SECURITY_CONTEXT"; @@ -51,7 +51,7 @@ public abstract class AbstractHazelcastRepositoryITests { private HazelcastSessionRepository repository; @Test - public void createAndDestroySession() { + void createAndDestroySession() { HazelcastSession sessionToSave = this.repository.createSession(); String sessionId = sessionToSave.getId(); @@ -71,7 +71,7 @@ public abstract class AbstractHazelcastRepositoryITests { } @Test - public void changeSessionIdWhenOnlyChangeId() { + void changeSessionIdWhenOnlyChangeId() { String attrName = "changeSessionId"; String attrValue = "changeSessionId-value"; HazelcastSession toSave = this.repository.createSession(); @@ -90,17 +90,15 @@ public abstract class AbstractHazelcastRepositoryITests { assertThat(this.repository.findById(originalFindById)).isNull(); - HazelcastSession findByChangeSessionId = this.repository - .findById(changeSessionId); + HazelcastSession findByChangeSessionId = this.repository.findById(changeSessionId); - assertThat(findByChangeSessionId.getAttribute(attrName)) - .isEqualTo(attrValue); + assertThat(findByChangeSessionId.getAttribute(attrName)).isEqualTo(attrValue); this.repository.deleteById(changeSessionId); } @Test - public void changeSessionIdWhenChangeTwice() { + void changeSessionIdWhenChangeTwice() { HazelcastSession toSave = this.repository.createSession(); this.repository.save(toSave); @@ -119,7 +117,7 @@ public abstract class AbstractHazelcastRepositoryITests { } @Test - public void changeSessionIdWhenSetAttributeOnChangedSession() { + void changeSessionIdWhenSetAttributeOnChangedSession() { String attrName = "changeSessionId"; String attrValue = "changeSessionId-value"; @@ -138,17 +136,15 @@ public abstract class AbstractHazelcastRepositoryITests { assertThat(this.repository.findById(originalFindById)).isNull(); - HazelcastSession findByChangeSessionId = this.repository - .findById(changeSessionId); + HazelcastSession findByChangeSessionId = this.repository.findById(changeSessionId); - assertThat(findByChangeSessionId.getAttribute(attrName)) - .isEqualTo(attrValue); + assertThat(findByChangeSessionId.getAttribute(attrName)).isEqualTo(attrValue); this.repository.deleteById(changeSessionId); } @Test - public void changeSessionIdWhenHasNotSaved() { + void changeSessionIdWhenHasNotSaved() { HazelcastSession toSave = this.repository.createSession(); String originalId = toSave.getId(); toSave.changeSessionId(); @@ -162,7 +158,7 @@ public abstract class AbstractHazelcastRepositoryITests { } @Test // gh-1076 - public void attemptToUpdateSessionAfterDelete() { + void attemptToUpdateSessionAfterDelete() { HazelcastSession session = this.repository.createSession(); String sessionId = session.getId(); this.repository.save(session); @@ -175,7 +171,7 @@ public abstract class AbstractHazelcastRepositoryITests { } @Test - public void createAndUpdateSession() { + void createAndUpdateSession() { HazelcastSession session = this.repository.createSession(); String sessionId = session.getId(); @@ -190,13 +186,12 @@ public abstract class AbstractHazelcastRepositoryITests { } @Test - public void createSessionWithSecurityContextAndFindById() { + void createSessionWithSecurityContextAndFindById() { HazelcastSession session = this.repository.createSession(); String sessionId = session.getId(); - Authentication authentication = new UsernamePasswordAuthenticationToken( - "saves-" + System.currentTimeMillis(), "password", - AuthorityUtils.createAuthorityList("ROLE_USER")); + Authentication authentication = new UsernamePasswordAuthenticationToken("saves-" + System.currentTimeMillis(), + "password", AuthorityUtils.createAuthorityList("ROLE_USER")); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(authentication); session.setAttribute(SPRING_SECURITY_CONTEXT, securityContext); @@ -207,23 +202,23 @@ public abstract class AbstractHazelcastRepositoryITests { } @Test - public void createSessionWithSecurityContextAndFindByPrincipal() { + void createSessionWithSecurityContextAndFindByPrincipal() { Assumptions.assumeTrue(this.hazelcastInstance instanceof HazelcastInstanceProxy, "Hazelcast runs in embedded server topology"); HazelcastSession session = this.repository.createSession(); String username = "saves-" + System.currentTimeMillis(); - Authentication authentication = new UsernamePasswordAuthenticationToken(username, - "password", AuthorityUtils.createAuthorityList("ROLE_USER")); + Authentication authentication = new UsernamePasswordAuthenticationToken(username, "password", + AuthorityUtils.createAuthorityList("ROLE_USER")); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(authentication); session.setAttribute(SPRING_SECURITY_CONTEXT, securityContext); this.repository.save(session); - assertThat(this.repository.findByIndexNameAndIndexValue( - FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username)) + assertThat(this.repository + .findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username)) .hasSize(1); } diff --git a/spring-session-hazelcast/src/integration-test/java/org/springframework/session/hazelcast/HazelcastClientRepositoryITests.java b/spring-session-hazelcast/src/integration-test/java/org/springframework/session/hazelcast/HazelcastClientRepositoryITests.java index c618eb9c..d45b5212 100644 --- a/spring-session-hazelcast/src/integration-test/java/org/springframework/session/hazelcast/HazelcastClientRepositoryITests.java +++ b/spring-session-hazelcast/src/integration-test/java/org/springframework/session/hazelcast/HazelcastClientRepositoryITests.java @@ -45,24 +45,20 @@ import org.springframework.test.context.web.WebAppConfiguration; @ExtendWith(SpringExtension.class) @ContextConfiguration @WebAppConfiguration -public class HazelcastClientRepositoryITests extends AbstractHazelcastRepositoryITests { +class HazelcastClientRepositoryITests extends AbstractHazelcastRepositoryITests { - private static GenericContainer container = new GenericContainer<>( - "hazelcast/hazelcast:3.12.1") - .withExposedPorts(5701) - .withEnv("JAVA_OPTS", - "-Dhazelcast.config=/opt/hazelcast/config_ext/hazelcast.xml") - .withClasspathResourceMapping("/hazelcast-server.xml", - "/opt/hazelcast/config_ext/hazelcast.xml", - BindMode.READ_ONLY); + private static GenericContainer container = new GenericContainer<>("hazelcast/hazelcast:3.12.1") + .withExposedPorts(5701).withEnv("JAVA_OPTS", "-Dhazelcast.config=/opt/hazelcast/config_ext/hazelcast.xml") + .withClasspathResourceMapping("/hazelcast-server.xml", "/opt/hazelcast/config_ext/hazelcast.xml", + BindMode.READ_ONLY); @BeforeAll - public static void setUpClass() { + static void setUpClass() { container.start(); } @AfterAll - public static void tearDownClass() { + static void tearDownClass() { container.stop(); } @@ -73,11 +69,10 @@ public class HazelcastClientRepositoryITests extends AbstractHazelcastRepository @Bean public HazelcastInstance hazelcastInstance() { ClientConfig clientConfig = new ClientConfig(); - clientConfig.getNetworkConfig().addAddress(container.getContainerIpAddress() - + ":" + container.getFirstMappedPort()); - clientConfig.getUserCodeDeploymentConfig().setEnabled(true) - .addClass(Session.class).addClass(MapSession.class) - .addClass(SessionUpdateEntryProcessor.class); + clientConfig.getNetworkConfig() + .addAddress(container.getContainerIpAddress() + ":" + container.getFirstMappedPort()); + clientConfig.getUserCodeDeploymentConfig().setEnabled(true).addClass(Session.class) + .addClass(MapSession.class).addClass(SessionUpdateEntryProcessor.class); return HazelcastClient.newHazelcastClient(clientConfig); } diff --git a/spring-session-hazelcast/src/integration-test/java/org/springframework/session/hazelcast/HazelcastITestUtils.java b/spring-session-hazelcast/src/integration-test/java/org/springframework/session/hazelcast/HazelcastITestUtils.java index 75272e26..0f51a556 100644 --- a/spring-session-hazelcast/src/integration-test/java/org/springframework/session/hazelcast/HazelcastITestUtils.java +++ b/spring-session-hazelcast/src/integration-test/java/org/springframework/session/hazelcast/HazelcastITestUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,13 +51,10 @@ public final class HazelcastITestUtils { networkConfig.setPort(port); - networkConfig.getJoin() - .getMulticastConfig().setEnabled(false); + networkConfig.getJoin().getMulticastConfig().setEnabled(false); - config.getMapConfig(HazelcastSessionRepository.DEFAULT_SESSION_MAP_NAME) - .addMapAttributeConfig(attributeConfig) - .addMapIndexConfig(new MapIndexConfig( - HazelcastSessionRepository.PRINCIPAL_NAME_ATTRIBUTE, false)); + config.getMapConfig(HazelcastSessionRepository.DEFAULT_SESSION_MAP_NAME).addMapAttributeConfig(attributeConfig) + .addMapIndexConfig(new MapIndexConfig(HazelcastSessionRepository.PRINCIPAL_NAME_ATTRIBUTE, false)); return Hazelcast.newHazelcastInstance(config); } diff --git a/spring-session-hazelcast/src/integration-test/java/org/springframework/session/hazelcast/HazelcastServerRepositoryITests.java b/spring-session-hazelcast/src/integration-test/java/org/springframework/session/hazelcast/HazelcastServerRepositoryITests.java index 1f20667c..542becaf 100644 --- a/spring-session-hazelcast/src/integration-test/java/org/springframework/session/hazelcast/HazelcastServerRepositoryITests.java +++ b/spring-session-hazelcast/src/integration-test/java/org/springframework/session/hazelcast/HazelcastServerRepositoryITests.java @@ -36,7 +36,7 @@ import org.springframework.test.context.web.WebAppConfiguration; @ExtendWith(SpringExtension.class) @ContextConfiguration @WebAppConfiguration -public class HazelcastServerRepositoryITests extends AbstractHazelcastRepositoryITests { +class HazelcastServerRepositoryITests extends AbstractHazelcastRepositoryITests { @EnableHazelcastHttpSession @Configuration diff --git a/spring-session-hazelcast/src/integration-test/java/org/springframework/session/hazelcast/SessionEventRegistry.java b/spring-session-hazelcast/src/integration-test/java/org/springframework/session/hazelcast/SessionEventRegistry.java index 9eb419d9..d649b049 100644 --- a/spring-session-hazelcast/src/integration-test/java/org/springframework/session/hazelcast/SessionEventRegistry.java +++ b/spring-session-hazelcast/src/integration-test/java/org/springframework/session/hazelcast/SessionEventRegistry.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,9 @@ import org.springframework.context.ApplicationListener; import org.springframework.session.events.AbstractSessionEvent; public class SessionEventRegistry implements ApplicationListener { + private Map events = new HashMap<>(); + private ConcurrentMap locks = new ConcurrentHashMap<>(); @Override @@ -48,14 +50,12 @@ public class SessionEventRegistry implements ApplicationListener E getEvent(String sessionId) - throws InterruptedException { + public E getEvent(String sessionId) throws InterruptedException { return (E) waitForEvent(sessionId); } @SuppressWarnings("unchecked") - private E waitForEvent(String sessionId) - throws InterruptedException { + private E waitForEvent(String sessionId) throws InterruptedException { Object lock = getLock(sessionId); synchronized (lock) { if (!this.events.containsKey(sessionId)) { @@ -68,4 +68,5 @@ public class SessionEventRegistry implements ApplicationListener new Object()); } + } diff --git a/spring-session-hazelcast/src/integration-test/java/org/springframework/session/hazelcast/config/annotation/web/http/EnableHazelcastHttpSessionEventsTests.java b/spring-session-hazelcast/src/integration-test/java/org/springframework/session/hazelcast/config/annotation/web/http/EnableHazelcastHttpSessionEventsTests.java index 6563abfd..a70f9362 100644 --- a/spring-session-hazelcast/src/integration-test/java/org/springframework/session/hazelcast/config/annotation/web/http/EnableHazelcastHttpSessionEventsTests.java +++ b/spring-session-hazelcast/src/integration-test/java/org/springframework/session/hazelcast/config/annotation/web/http/EnableHazelcastHttpSessionEventsTests.java @@ -57,7 +57,7 @@ import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(SpringExtension.class) @ContextConfiguration @WebAppConfiguration -public class EnableHazelcastHttpSessionEventsTests { +class EnableHazelcastHttpSessionEventsTests { private static final int MAX_INACTIVE_INTERVAL_IN_SECONDS = 1; @@ -68,12 +68,12 @@ public class EnableHazelcastHttpSessionEventsTests { private SessionEventRegistry registry; @BeforeEach - public void setup() { + void setup() { this.registry.clear(); } @Test - public void saveSessionTest() throws InterruptedException { + void saveSessionTest() throws InterruptedException { String username = "saves-" + System.currentTimeMillis(); S sessionToSave = this.repository.createSession(); @@ -81,13 +81,12 @@ public class EnableHazelcastHttpSessionEventsTests { String expectedAttributeName = "a"; String expectedAttributeValue = "b"; sessionToSave.setAttribute(expectedAttributeName, expectedAttributeValue); - Authentication toSaveToken = new UsernamePasswordAuthenticationToken(username, - "password", AuthorityUtils.createAuthorityList("ROLE_USER")); + Authentication toSaveToken = new UsernamePasswordAuthenticationToken(username, "password", + AuthorityUtils.createAuthorityList("ROLE_USER")); SecurityContext toSaveContext = SecurityContextHolder.createEmptyContext(); toSaveContext.setAuthentication(toSaveToken); sessionToSave.setAttribute("SPRING_SECURITY_CONTEXT", toSaveContext); - sessionToSave.setAttribute( - FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username); + sessionToSave.setAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username); this.repository.save(sessionToSave); @@ -98,14 +97,13 @@ public class EnableHazelcastHttpSessionEventsTests { Session session = this.repository.findById(sessionToSave.getId()); assertThat(session.getId()).isEqualTo(sessionToSave.getId()); - assertThat(session.getAttributeNames()) - .isEqualTo(sessionToSave.getAttributeNames()); + assertThat(session.getAttributeNames()).isEqualTo(sessionToSave.getAttributeNames()); assertThat(session.getAttribute(expectedAttributeName)) .isEqualTo(sessionToSave.getAttribute(expectedAttributeName)); } @Test - public void expiredSessionTest() throws InterruptedException { + void expiredSessionTest() throws InterruptedException { S sessionToSave = this.repository.createSession(); this.repository.save(sessionToSave); @@ -126,7 +124,7 @@ public class EnableHazelcastHttpSessionEventsTests { } @Test - public void deletedSessionTest() throws InterruptedException { + void deletedSessionTest() throws InterruptedException { S sessionToSave = this.repository.createSession(); this.repository.save(sessionToSave); @@ -146,7 +144,7 @@ public class EnableHazelcastHttpSessionEventsTests { } @Test - public void saveUpdatesTimeToLiveTest() throws InterruptedException { + void saveUpdatesTimeToLiveTest() throws InterruptedException { S sessionToSave = this.repository.createSession(); sessionToSave.setMaxInactiveInterval(Duration.ofSeconds(3)); this.repository.save(sessionToSave); @@ -164,7 +162,7 @@ public class EnableHazelcastHttpSessionEventsTests { } @Test // gh-1077 - public void changeSessionIdNoEventTest() throws InterruptedException { + void changeSessionIdNoEventTest() throws InterruptedException { S sessionToSave = this.repository.createSession(); sessionToSave.setMaxInactiveInterval(Duration.ofMinutes(30)); @@ -182,7 +180,7 @@ public class EnableHazelcastHttpSessionEventsTests { } @Test // gh-1300 - public void updateMaxInactiveIntervalTest() throws InterruptedException { + void updateMaxInactiveIntervalTest() throws InterruptedException { S sessionToSave = this.repository.createSession(); sessionToSave.setMaxInactiveInterval(Duration.ofMinutes(30)); this.repository.save(sessionToSave); diff --git a/spring-session-hazelcast/src/integration-test/java/org/springframework/session/hazelcast/config/annotation/web/http/HazelcastHttpSessionConfigurationXmlTests.java b/spring-session-hazelcast/src/integration-test/java/org/springframework/session/hazelcast/config/annotation/web/http/HazelcastHttpSessionConfigurationXmlTests.java index f4e2182c..0f8a7c2c 100644 --- a/spring-session-hazelcast/src/integration-test/java/org/springframework/session/hazelcast/config/annotation/web/http/HazelcastHttpSessionConfigurationXmlTests.java +++ b/spring-session-hazelcast/src/integration-test/java/org/springframework/session/hazelcast/config/annotation/web/http/HazelcastHttpSessionConfigurationXmlTests.java @@ -49,13 +49,13 @@ public class HazelcastHttpSessionConfigurationXmlTests { @ExtendWith(SpringExtension.class) @ContextConfiguration @WebAppConfiguration - public static class CustomXmlMapNameTest { + static class CustomXmlMapNameTest { @Autowired private SessionRepository repository; @Test - public void saveSessionTest() throws InterruptedException { + void saveSessionTest() throws InterruptedException { S sessionToSave = this.repository.createSession(); @@ -64,8 +64,7 @@ public class HazelcastHttpSessionConfigurationXmlTests { S session = this.repository.findById(sessionToSave.getId()); assertThat(session.getId()).isEqualTo(sessionToSave.getId()); - assertThat(session.getMaxInactiveInterval()) - .isEqualTo(Duration.ofMinutes(30)); + assertThat(session.getMaxInactiveInterval()).isEqualTo(Duration.ofMinutes(30)); } @Configuration @@ -81,19 +80,21 @@ public class HazelcastHttpSessionConfigurationXmlTests { hazelcastConfig.setNetworkConfig(netConfig); return Hazelcast.newHazelcastInstance(hazelcastConfig); } + } + } @ExtendWith(SpringExtension.class) @ContextConfiguration @WebAppConfiguration - public static class CustomXmlMapNameAndIdleTest { + static class CustomXmlMapNameAndIdleTest { @Autowired private SessionRepository repository; @Test - public void saveSessionTest() throws InterruptedException { + void saveSessionTest() throws InterruptedException { S sessionToSave = this.repository.createSession(); @@ -102,8 +103,7 @@ public class HazelcastHttpSessionConfigurationXmlTests { S session = this.repository.findById(sessionToSave.getId()); assertThat(session.getId()).isEqualTo(sessionToSave.getId()); - assertThat(session.getMaxInactiveInterval()) - .isEqualTo(Duration.ofMinutes(20)); + assertThat(session.getMaxInactiveInterval()).isEqualTo(Duration.ofMinutes(20)); } @Configuration @@ -119,7 +119,9 @@ public class HazelcastHttpSessionConfigurationXmlTests { hazelcastConfig.setNetworkConfig(netConfig); return Hazelcast.newHazelcastInstance(hazelcastConfig); } + } + } } diff --git a/spring-session-hazelcast/src/main/java/org/springframework/session/hazelcast/HazelcastSessionRepository.java b/spring-session-hazelcast/src/main/java/org/springframework/session/hazelcast/HazelcastSessionRepository.java index 15455246..498c1903 100644 --- a/spring-session-hazelcast/src/main/java/org/springframework/session/hazelcast/HazelcastSessionRepository.java +++ b/spring-session-hazelcast/src/main/java/org/springframework/session/hazelcast/HazelcastSessionRepository.java @@ -108,8 +108,8 @@ import org.springframework.util.ClassUtils; * @author Aleksandar Stojsavljevic * @since 1.3.0 */ -public class HazelcastSessionRepository implements - FindByIndexNameSessionRepository, +public class HazelcastSessionRepository + implements FindByIndexNameSessionRepository, EntryAddedListener, EntryEvictedListener, EntryRemovedListener { @@ -125,8 +125,7 @@ public class HazelcastSessionRepository implements private static final String SPRING_SECURITY_CONTEXT = "SPRING_SECURITY_CONTEXT"; - private static final boolean SUPPORTS_SET_TTL = ClassUtils - .hasAtLeastOneMethodWithName(IMap.class, "setTtl"); + private static final boolean SUPPORTS_SET_TTL = ClassUtils.hasAtLeastOneMethodWithName(IMap.class, "setTtl"); private static final Log logger = LogFactory.getLog(HazelcastSessionRepository.class); @@ -180,14 +179,11 @@ public class HazelcastSessionRepository implements * Sets the {@link ApplicationEventPublisher} that is used to publish * {@link AbstractSessionEvent session events}. The default is to not publish session * events. - * * @param applicationEventPublisher the {@link ApplicationEventPublisher} that is used * to publish session events. Cannot be null. */ - public void setApplicationEventPublisher( - ApplicationEventPublisher applicationEventPublisher) { - Assert.notNull(applicationEventPublisher, - "ApplicationEventPublisher cannot be null"); + public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { + Assert.notNull(applicationEventPublisher, "ApplicationEventPublisher cannot be null"); this.eventPublisher = applicationEventPublisher; } @@ -224,8 +220,7 @@ public class HazelcastSessionRepository implements public HazelcastSession createSession() { HazelcastSession result = new HazelcastSession(); if (this.defaultMaxInactiveInterval != null) { - result.setMaxInactiveInterval( - Duration.ofSeconds(this.defaultMaxInactiveInterval)); + result.setMaxInactiveInterval(Duration.ofSeconds(this.defaultMaxInactiveInterval)); } return result; } @@ -233,14 +228,14 @@ public class HazelcastSessionRepository implements @Override public void save(HazelcastSession session) { if (session.isNew) { - this.sessions.set(session.getId(), session.getDelegate(), - session.getMaxInactiveInterval().getSeconds(), TimeUnit.SECONDS); + this.sessions.set(session.getId(), session.getDelegate(), session.getMaxInactiveInterval().getSeconds(), + TimeUnit.SECONDS); } else if (session.sessionIdChanged) { this.sessions.delete(session.originalId); session.originalId = session.getId(); - this.sessions.set(session.getId(), session.getDelegate(), - session.getMaxInactiveInterval().getSeconds(), TimeUnit.SECONDS); + this.sessions.set(session.getId(), session.getDelegate(), session.getMaxInactiveInterval().getSeconds(), + TimeUnit.SECONDS); } else if (session.hasChanges()) { SessionUpdateEntryProcessor entryProcessor = new SessionUpdateEntryProcessor(); @@ -262,8 +257,7 @@ public class HazelcastSessionRepository implements } private void updateTtl(HazelcastSession session) { - this.sessions.setTtl(session.getId(), - session.getMaxInactiveInterval().getSeconds(), TimeUnit.SECONDS); + this.sessions.setTtl(session.getId(), session.getMaxInactiveInterval().getSeconds(), TimeUnit.SECONDS); } @Override @@ -285,13 +279,11 @@ public class HazelcastSessionRepository implements } @Override - public Map findByIndexNameAndIndexValue(String indexName, - String indexValue) { + public Map findByIndexNameAndIndexValue(String indexName, String indexValue) { if (!PRINCIPAL_NAME_INDEX_NAME.equals(indexName)) { return Collections.emptyMap(); } - Collection sessions = this.sessions - .values(Predicates.equal(PRINCIPAL_NAME_ATTRIBUTE, indexValue)); + Collection sessions = this.sessions.values(Predicates.equal(PRINCIPAL_NAME_ATTRIBUTE, indexValue)); Map sessionMap = new HashMap<>(sessions.size()); for (MapSession session : sessions) { sessionMap.put(session.getId(), new HazelcastSession(session)); @@ -315,8 +307,7 @@ public class HazelcastSessionRepository implements if (logger.isDebugEnabled()) { logger.debug("Session expired with id: " + event.getOldValue().getId()); } - this.eventPublisher - .publishEvent(new SessionExpiredEvent(this, event.getOldValue())); + this.eventPublisher.publishEvent(new SessionExpiredEvent(this, event.getOldValue())); } @Override @@ -434,9 +425,7 @@ public class HazelcastSessionRepository implements this.delegate.setAttribute(attributeName, attributeValue); this.delta.put(attributeName, attributeValue); if (SPRING_SECURITY_CONTEXT.equals(attributeName)) { - String principal = (attributeValue != null) - ? principalNameResolver.resolvePrincipal(this) - : null; + String principal = (attributeValue != null) ? principalNameResolver.resolvePrincipal(this) : null; this.delegate.setAttribute(PRINCIPAL_NAME_INDEX_NAME, principal); } flushImmediateIfNecessary(); @@ -452,8 +441,7 @@ public class HazelcastSessionRepository implements } boolean hasChanges() { - return (this.lastAccessedTimeChanged || this.maxInactiveIntervalChanged - || !this.delta.isEmpty()); + return (this.lastAccessedTimeChanged || this.maxInactiveIntervalChanged || !this.delta.isEmpty()); } void clearChangeFlags() { @@ -486,8 +474,7 @@ public class HazelcastSessionRepository implements } Object authentication = session.getAttribute(SPRING_SECURITY_CONTEXT); if (authentication != null) { - Expression expression = this.parser - .parseExpression("authentication?.name"); + Expression expression = this.parser.parseExpression("authentication?.name"); return expression.getValue(authentication, String.class); } return null; diff --git a/spring-session-hazelcast/src/main/java/org/springframework/session/hazelcast/PrincipalNameExtractor.java b/spring-session-hazelcast/src/main/java/org/springframework/session/hazelcast/PrincipalNameExtractor.java index c1d31309..6de56c6c 100644 --- a/spring-session-hazelcast/src/main/java/org/springframework/session/hazelcast/PrincipalNameExtractor.java +++ b/spring-session-hazelcast/src/main/java/org/springframework/session/hazelcast/PrincipalNameExtractor.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,8 +34,7 @@ public class PrincipalNameExtractor extends ValueExtractor { @Override @SuppressWarnings("unchecked") public void extract(MapSession target, String argument, ValueCollector collector) { - String principalName = target - .getAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME); + String principalName = target.getAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME); if (principalName != null) { collector.addObject(principalName); } diff --git a/spring-session-hazelcast/src/main/java/org/springframework/session/hazelcast/SessionUpdateEntryProcessor.java b/spring-session-hazelcast/src/main/java/org/springframework/session/hazelcast/SessionUpdateEntryProcessor.java index 31eddb82..48edaeca 100644 --- a/spring-session-hazelcast/src/main/java/org/springframework/session/hazelcast/SessionUpdateEntryProcessor.java +++ b/spring-session-hazelcast/src/main/java/org/springframework/session/hazelcast/SessionUpdateEntryProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,7 @@ import org.springframework.session.MapSession; * @since 1.3.4 * @see HazelcastSessionRepository#save(HazelcastSessionRepository.HazelcastSession) */ -public class SessionUpdateEntryProcessor - extends AbstractEntryProcessor implements Offloadable { +public class SessionUpdateEntryProcessor extends AbstractEntryProcessor implements Offloadable { private Instant lastAccessedTime; diff --git a/spring-session-hazelcast/src/main/java/org/springframework/session/hazelcast/config/annotation/SpringSessionHazelcastInstance.java b/spring-session-hazelcast/src/main/java/org/springframework/session/hazelcast/config/annotation/SpringSessionHazelcastInstance.java index 94420426..e5e70ff4 100644 --- a/spring-session-hazelcast/src/main/java/org/springframework/session/hazelcast/config/annotation/SpringSessionHazelcastInstance.java +++ b/spring-session-hazelcast/src/main/java/org/springframework/session/hazelcast/config/annotation/SpringSessionHazelcastInstance.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,8 +34,7 @@ import org.springframework.session.hazelcast.HazelcastSessionRepository; * @author Vedran Pavic * @since 2.0.0 */ -@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, - ElementType.ANNOTATION_TYPE }) +@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented @Qualifier diff --git a/spring-session-hazelcast/src/main/java/org/springframework/session/hazelcast/config/annotation/web/http/EnableHazelcastHttpSession.java b/spring-session-hazelcast/src/main/java/org/springframework/session/hazelcast/config/annotation/web/http/EnableHazelcastHttpSession.java index bed87742..faeb63bb 100644 --- a/spring-session-hazelcast/src/main/java/org/springframework/session/hazelcast/config/annotation/web/http/EnableHazelcastHttpSession.java +++ b/spring-session-hazelcast/src/main/java/org/springframework/session/hazelcast/config/annotation/web/http/EnableHazelcastHttpSession.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -79,8 +79,7 @@ public @interface EnableHazelcastHttpSession { /** * This is the name of the Map that will be used in Hazelcast to store the session - * data. Default is - * {@link HazelcastSessionRepository#DEFAULT_SESSION_MAP_NAME}. + * data. Default is {@link HazelcastSessionRepository#DEFAULT_SESSION_MAP_NAME}. * @return the name of the Map to store the sessions in Hazelcast */ String sessionMapName() default HazelcastSessionRepository.DEFAULT_SESSION_MAP_NAME; diff --git a/spring-session-hazelcast/src/main/java/org/springframework/session/hazelcast/config/annotation/web/http/HazelcastHttpSessionConfiguration.java b/spring-session-hazelcast/src/main/java/org/springframework/session/hazelcast/config/annotation/web/http/HazelcastHttpSessionConfiguration.java index 74142f4d..a8eb9b74 100644 --- a/spring-session-hazelcast/src/main/java/org/springframework/session/hazelcast/config/annotation/web/http/HazelcastHttpSessionConfiguration.java +++ b/spring-session-hazelcast/src/main/java/org/springframework/session/hazelcast/config/annotation/web/http/HazelcastHttpSessionConfiguration.java @@ -47,8 +47,7 @@ import org.springframework.util.StringUtils; * @see EnableHazelcastHttpSession */ @Configuration(proxyBeanMethods = false) -public class HazelcastHttpSessionConfiguration extends SpringHttpSessionConfiguration - implements ImportAware { +public class HazelcastHttpSessionConfiguration extends SpringHttpSessionConfiguration implements ImportAware { private Integer maxInactiveIntervalInSeconds = MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS; @@ -62,14 +61,12 @@ public class HazelcastHttpSessionConfiguration extends SpringHttpSessionConfigur @Bean public HazelcastSessionRepository sessionRepository() { - HazelcastSessionRepository sessionRepository = new HazelcastSessionRepository( - this.hazelcastInstance); + HazelcastSessionRepository sessionRepository = new HazelcastSessionRepository(this.hazelcastInstance); sessionRepository.setApplicationEventPublisher(this.applicationEventPublisher); if (StringUtils.hasText(this.sessionMapName)) { sessionRepository.setSessionMapName(this.sessionMapName); } - sessionRepository - .setDefaultMaxInactiveInterval(this.maxInactiveIntervalInSeconds); + sessionRepository.setDefaultMaxInactiveInterval(this.maxInactiveIntervalInSeconds); sessionRepository.setHazelcastFlushMode(this.hazelcastFlushMode); return sessionRepository; } @@ -90,8 +87,7 @@ public class HazelcastHttpSessionConfiguration extends SpringHttpSessionConfigur public void setHazelcastInstance( @SpringSessionHazelcastInstance ObjectProvider springSessionHazelcastInstance, ObjectProvider hazelcastInstance) { - HazelcastInstance hazelcastInstanceToUse = springSessionHazelcastInstance - .getIfAvailable(); + HazelcastInstance hazelcastInstanceToUse = springSessionHazelcastInstance.getIfAvailable(); if (hazelcastInstanceToUse == null) { hazelcastInstanceToUse = hazelcastInstance.getObject(); } @@ -99,8 +95,7 @@ public class HazelcastHttpSessionConfiguration extends SpringHttpSessionConfigur } @Autowired - public void setApplicationEventPublisher( - ApplicationEventPublisher applicationEventPublisher) { + public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.applicationEventPublisher = applicationEventPublisher; } @@ -109,8 +104,7 @@ public class HazelcastHttpSessionConfiguration extends SpringHttpSessionConfigur Map attributeMap = importMetadata .getAnnotationAttributes(EnableHazelcastHttpSession.class.getName()); AnnotationAttributes attributes = AnnotationAttributes.fromMap(attributeMap); - this.maxInactiveIntervalInSeconds = - attributes.getNumber("maxInactiveIntervalInSeconds"); + this.maxInactiveIntervalInSeconds = attributes.getNumber("maxInactiveIntervalInSeconds"); String sessionMapNameValue = attributes.getString("sessionMapName"); if (StringUtils.hasText(sessionMapNameValue)) { this.sessionMapName = sessionMapNameValue; diff --git a/spring-session-hazelcast/src/test/java/org/springframework/session/hazelcast/HazelcastSessionRepositoryTests.java b/spring-session-hazelcast/src/test/java/org/springframework/session/hazelcast/HazelcastSessionRepositoryTests.java index c3c90f2c..ade6efa9 100644 --- a/spring-session-hazelcast/src/test/java/org/springframework/session/hazelcast/HazelcastSessionRepositoryTests.java +++ b/spring-session-hazelcast/src/test/java/org/springframework/session/hazelcast/HazelcastSessionRepositoryTests.java @@ -58,7 +58,7 @@ import static org.mockito.Mockito.verifyZeroInteractions; * @author Vedran Pavic * @author Aleksandar Stojsavljevic */ -public class HazelcastSessionRepositoryTests { +class HazelcastSessionRepositoryTests { private static final String SPRING_SECURITY_CONTEXT = "SPRING_SECURITY_CONTEXT"; @@ -70,241 +70,218 @@ public class HazelcastSessionRepositoryTests { private HazelcastSessionRepository repository; @BeforeEach - public void setUp() { - given(this.hazelcastInstance.getMap(anyString())) - .willReturn(this.sessions); + void setUp() { + given(this.hazelcastInstance.getMap(anyString())).willReturn(this.sessions); this.repository = new HazelcastSessionRepository(this.hazelcastInstance); this.repository.init(); } @Test - public void constructorNullHazelcastInstance() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new HazelcastSessionRepository(null)) + void constructorNullHazelcastInstance() { + assertThatIllegalArgumentException().isThrownBy(() -> new HazelcastSessionRepository(null)) .withMessage("HazelcastInstance must not be null"); } @Test - public void createSessionDefaultMaxInactiveInterval() { - verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), - anyBoolean()); + void createSessionDefaultMaxInactiveInterval() { + verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), anyBoolean()); HazelcastSession session = this.repository.createSession(); - assertThat(session.getMaxInactiveInterval()) - .isEqualTo(new MapSession().getMaxInactiveInterval()); + assertThat(session.getMaxInactiveInterval()).isEqualTo(new MapSession().getMaxInactiveInterval()); verifyZeroInteractions(this.sessions); } @Test - public void createSessionCustomMaxInactiveInterval() { - verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), - anyBoolean()); + void createSessionCustomMaxInactiveInterval() { + verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), anyBoolean()); int interval = 1; this.repository.setDefaultMaxInactiveInterval(interval); HazelcastSession session = this.repository.createSession(); - assertThat(session.getMaxInactiveInterval()) - .isEqualTo(Duration.ofSeconds(interval)); + assertThat(session.getMaxInactiveInterval()).isEqualTo(Duration.ofSeconds(interval)); verifyZeroInteractions(this.sessions); } @Test - public void saveNewFlushModeOnSave() { - verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), - anyBoolean()); + void saveNewFlushModeOnSave() { + verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), anyBoolean()); HazelcastSession session = this.repository.createSession(); verifyZeroInteractions(this.sessions); this.repository.save(session); - verify(this.sessions, times(1)).set(eq(session.getId()), - eq(session.getDelegate()), isA(Long.class), eq(TimeUnit.SECONDS)); + verify(this.sessions, times(1)).set(eq(session.getId()), eq(session.getDelegate()), isA(Long.class), + eq(TimeUnit.SECONDS)); verifyZeroInteractions(this.sessions); } @Test - public void saveNewFlushModeImmediate() { - verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), - anyBoolean()); + void saveNewFlushModeImmediate() { + verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), anyBoolean()); this.repository.setHazelcastFlushMode(HazelcastFlushMode.IMMEDIATE); HazelcastSession session = this.repository.createSession(); - verify(this.sessions, times(1)).set(eq(session.getId()), - eq(session.getDelegate()), isA(Long.class), eq(TimeUnit.SECONDS)); + verify(this.sessions, times(1)).set(eq(session.getId()), eq(session.getDelegate()), isA(Long.class), + eq(TimeUnit.SECONDS)); verifyZeroInteractions(this.sessions); } @Test - public void saveUpdatedAttributeFlushModeOnSave() { - verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), - anyBoolean()); + void saveUpdatedAttributeFlushModeOnSave() { + verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), anyBoolean()); HazelcastSession session = this.repository.createSession(); session.setAttribute("testName", "testValue"); verifyZeroInteractions(this.sessions); this.repository.save(session); - verify(this.sessions, times(1)).set(eq(session.getId()), - eq(session.getDelegate()), isA(Long.class), eq(TimeUnit.SECONDS)); + verify(this.sessions, times(1)).set(eq(session.getId()), eq(session.getDelegate()), isA(Long.class), + eq(TimeUnit.SECONDS)); verifyZeroInteractions(this.sessions); } @Test - public void saveUpdatedAttributeFlushModeImmediate() { - verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), - anyBoolean()); + void saveUpdatedAttributeFlushModeImmediate() { + verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), anyBoolean()); this.repository.setHazelcastFlushMode(HazelcastFlushMode.IMMEDIATE); HazelcastSession session = this.repository.createSession(); session.setAttribute("testName", "testValue"); - verify(this.sessions, times(1)).set(eq(session.getId()), - eq(session.getDelegate()), isA(Long.class), eq(TimeUnit.SECONDS)); - verify(this.sessions, times(1)).executeOnKey(eq(session.getId()), - any(EntryProcessor.class)); + verify(this.sessions, times(1)).set(eq(session.getId()), eq(session.getDelegate()), isA(Long.class), + eq(TimeUnit.SECONDS)); + verify(this.sessions, times(1)).executeOnKey(eq(session.getId()), any(EntryProcessor.class)); this.repository.save(session); verifyZeroInteractions(this.sessions); } @Test - public void removeAttributeFlushModeOnSave() { - verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), - anyBoolean()); + void removeAttributeFlushModeOnSave() { + verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), anyBoolean()); HazelcastSession session = this.repository.createSession(); session.removeAttribute("testName"); verifyZeroInteractions(this.sessions); this.repository.save(session); - verify(this.sessions, times(1)).set(eq(session.getId()), - eq(session.getDelegate()), isA(Long.class), eq(TimeUnit.SECONDS)); + verify(this.sessions, times(1)).set(eq(session.getId()), eq(session.getDelegate()), isA(Long.class), + eq(TimeUnit.SECONDS)); verifyZeroInteractions(this.sessions); } @Test - public void removeAttributeFlushModeImmediate() { - verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), - anyBoolean()); + void removeAttributeFlushModeImmediate() { + verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), anyBoolean()); this.repository.setHazelcastFlushMode(HazelcastFlushMode.IMMEDIATE); HazelcastSession session = this.repository.createSession(); session.removeAttribute("testName"); - verify(this.sessions, times(1)).set(eq(session.getId()), - eq(session.getDelegate()), isA(Long.class), eq(TimeUnit.SECONDS)); - verify(this.sessions, times(1)).executeOnKey(eq(session.getId()), - any(EntryProcessor.class)); + verify(this.sessions, times(1)).set(eq(session.getId()), eq(session.getDelegate()), isA(Long.class), + eq(TimeUnit.SECONDS)); + verify(this.sessions, times(1)).executeOnKey(eq(session.getId()), any(EntryProcessor.class)); this.repository.save(session); verifyZeroInteractions(this.sessions); } @Test - public void saveUpdatedLastAccessedTimeFlushModeOnSave() { - verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), - anyBoolean()); + void saveUpdatedLastAccessedTimeFlushModeOnSave() { + verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), anyBoolean()); HazelcastSession session = this.repository.createSession(); session.setLastAccessedTime(Instant.now()); verifyZeroInteractions(this.sessions); this.repository.save(session); - verify(this.sessions, times(1)).set(eq(session.getId()), - eq(session.getDelegate()), isA(Long.class), eq(TimeUnit.SECONDS)); + verify(this.sessions, times(1)).set(eq(session.getId()), eq(session.getDelegate()), isA(Long.class), + eq(TimeUnit.SECONDS)); verifyZeroInteractions(this.sessions); } @Test - public void saveUpdatedLastAccessedTimeFlushModeImmediate() { - verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), - anyBoolean()); + void saveUpdatedLastAccessedTimeFlushModeImmediate() { + verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), anyBoolean()); this.repository.setHazelcastFlushMode(HazelcastFlushMode.IMMEDIATE); HazelcastSession session = this.repository.createSession(); session.setLastAccessedTime(Instant.now()); - verify(this.sessions, times(1)).set(eq(session.getId()), - eq(session.getDelegate()), isA(Long.class), eq(TimeUnit.SECONDS)); - verify(this.sessions, times(1)).executeOnKey(eq(session.getId()), - any(EntryProcessor.class)); + verify(this.sessions, times(1)).set(eq(session.getId()), eq(session.getDelegate()), isA(Long.class), + eq(TimeUnit.SECONDS)); + verify(this.sessions, times(1)).executeOnKey(eq(session.getId()), any(EntryProcessor.class)); this.repository.save(session); verifyZeroInteractions(this.sessions); } @Test - public void saveUpdatedMaxInactiveIntervalInSecondsFlushModeOnSave() { - verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), - anyBoolean()); + void saveUpdatedMaxInactiveIntervalInSecondsFlushModeOnSave() { + verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), anyBoolean()); HazelcastSession session = this.repository.createSession(); session.setMaxInactiveInterval(Duration.ofSeconds(1)); verifyZeroInteractions(this.sessions); this.repository.save(session); - verify(this.sessions, times(1)).set(eq(session.getId()), - eq(session.getDelegate()), isA(Long.class), eq(TimeUnit.SECONDS)); + verify(this.sessions, times(1)).set(eq(session.getId()), eq(session.getDelegate()), isA(Long.class), + eq(TimeUnit.SECONDS)); verifyZeroInteractions(this.sessions); } @Test - public void saveUpdatedMaxInactiveIntervalInSecondsFlushModeImmediate() { - verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), - anyBoolean()); + void saveUpdatedMaxInactiveIntervalInSecondsFlushModeImmediate() { + verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), anyBoolean()); this.repository.setHazelcastFlushMode(HazelcastFlushMode.IMMEDIATE); HazelcastSession session = this.repository.createSession(); String sessionId = session.getId(); session.setMaxInactiveInterval(Duration.ofSeconds(1)); - verify(this.sessions, times(1)).set(eq(sessionId), eq(session.getDelegate()), - isA(Long.class), eq(TimeUnit.SECONDS)); + verify(this.sessions, times(1)).set(eq(sessionId), eq(session.getDelegate()), isA(Long.class), + eq(TimeUnit.SECONDS)); verify(this.sessions).setTtl(eq(sessionId), anyLong(), any()); - verify(this.sessions, times(1)).executeOnKey(eq(sessionId), - any(EntryProcessor.class)); + verify(this.sessions, times(1)).executeOnKey(eq(sessionId), any(EntryProcessor.class)); this.repository.save(session); verifyZeroInteractions(this.sessions); } @Test - public void saveUnchangedFlushModeOnSave() { - verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), - anyBoolean()); + void saveUnchangedFlushModeOnSave() { + verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), anyBoolean()); HazelcastSession session = this.repository.createSession(); this.repository.save(session); - verify(this.sessions, times(1)).set(eq(session.getId()), - eq(session.getDelegate()), isA(Long.class), eq(TimeUnit.SECONDS)); + verify(this.sessions, times(1)).set(eq(session.getId()), eq(session.getDelegate()), isA(Long.class), + eq(TimeUnit.SECONDS)); this.repository.save(session); verifyZeroInteractions(this.sessions); } @Test - public void saveUnchangedFlushModeImmediate() { - verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), - anyBoolean()); + void saveUnchangedFlushModeImmediate() { + verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), anyBoolean()); this.repository.setHazelcastFlushMode(HazelcastFlushMode.IMMEDIATE); HazelcastSession session = this.repository.createSession(); - verify(this.sessions, times(1)).set(eq(session.getId()), - eq(session.getDelegate()), isA(Long.class), eq(TimeUnit.SECONDS)); + verify(this.sessions, times(1)).set(eq(session.getId()), eq(session.getDelegate()), isA(Long.class), + eq(TimeUnit.SECONDS)); this.repository.save(session); verifyZeroInteractions(this.sessions); } @Test - public void getSessionNotFound() { - verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), - anyBoolean()); + void getSessionNotFound() { + verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), anyBoolean()); String sessionId = "testSessionId"; @@ -316,13 +293,11 @@ public class HazelcastSessionRepositoryTests { } @Test - public void getSessionExpired() { - verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), - anyBoolean()); + void getSessionExpired() { + verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), anyBoolean()); MapSession expired = new MapSession(); - expired.setLastAccessedTime(Instant.now() - .minusSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS + 1)); + expired.setLastAccessedTime(Instant.now().minusSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS + 1)); given(this.sessions.get(eq(expired.getId()))).willReturn(expired); HazelcastSession session = this.repository.findById(expired.getId()); @@ -334,9 +309,8 @@ public class HazelcastSessionRepositoryTests { } @Test - public void getSessionFound() { - verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), - anyBoolean()); + void getSessionFound() { + verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), anyBoolean()); MapSession saved = new MapSession(); saved.setAttribute("savedName", "savedValue"); @@ -351,9 +325,8 @@ public class HazelcastSessionRepositoryTests { } @Test - public void delete() { - verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), - anyBoolean()); + void delete() { + verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), anyBoolean()); String sessionId = "testSessionId"; @@ -364,30 +337,26 @@ public class HazelcastSessionRepositoryTests { } @Test - public void findByIndexNameAndIndexValueUnknownIndexName() { - verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), - anyBoolean()); + void findByIndexNameAndIndexValueUnknownIndexName() { + verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), anyBoolean()); String indexValue = "testIndexValue"; - Map sessions = this.repository - .findByIndexNameAndIndexValue("testIndexName", indexValue); + Map sessions = this.repository.findByIndexNameAndIndexValue("testIndexName", + indexValue); assertThat(sessions).isEmpty(); verifyZeroInteractions(this.sessions); } @Test - public void findByIndexNameAndIndexValuePrincipalIndexNameNotFound() { - verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), - anyBoolean()); + void findByIndexNameAndIndexValuePrincipalIndexNameNotFound() { + verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), anyBoolean()); String principal = "username"; Map sessions = this.repository - .findByIndexNameAndIndexValue( - FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, - principal); + .findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, principal); assertThat(sessions).isEmpty(); verify(this.sessions, times(1)).values(isA(EqualPredicate.class)); @@ -395,13 +364,12 @@ public class HazelcastSessionRepositoryTests { } @Test - public void findByIndexNameAndIndexValuePrincipalIndexNameFound() { - verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), - anyBoolean()); + void findByIndexNameAndIndexValuePrincipalIndexNameFound() { + verify(this.sessions, times(1)).addEntryListener(any(MapListener.class), anyBoolean()); String principal = "username"; - Authentication authentication = new UsernamePasswordAuthenticationToken(principal, - "notused", AuthorityUtils.createAuthorityList("ROLE_USER")); + Authentication authentication = new UsernamePasswordAuthenticationToken(principal, "notused", + AuthorityUtils.createAuthorityList("ROLE_USER")); List saved = new ArrayList<>(2); MapSession saved1 = new MapSession(); saved1.setAttribute(SPRING_SECURITY_CONTEXT, authentication); @@ -412,9 +380,7 @@ public class HazelcastSessionRepositoryTests { given(this.sessions.values(isA(EqualPredicate.class))).willReturn(saved); Map sessions = this.repository - .findByIndexNameAndIndexValue( - FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, - principal); + .findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, principal); assertThat(sessions).hasSize(2); verify(this.sessions, times(1)).values(isA(EqualPredicate.class)); @@ -422,7 +388,7 @@ public class HazelcastSessionRepositoryTests { } @Test // gh-1120 - public void getAttributeNamesAndRemove() { + void getAttributeNamesAndRemove() { HazelcastSession session = this.repository.createSession(); session.setAttribute("attribute1", "value1"); session.setAttribute("attribute2", "value2"); diff --git a/spring-session-hazelcast/src/test/java/org/springframework/session/hazelcast/config/annotation/web/http/HazelcastHttpSessionConfigurationTests.java b/spring-session-hazelcast/src/test/java/org/springframework/session/hazelcast/config/annotation/web/http/HazelcastHttpSessionConfigurationTests.java index 3113c945..ac4459cb 100644 --- a/spring-session-hazelcast/src/test/java/org/springframework/session/hazelcast/config/annotation/web/http/HazelcastHttpSessionConfigurationTests.java +++ b/spring-session-hazelcast/src/test/java/org/springframework/session/hazelcast/config/annotation/web/http/HazelcastHttpSessionConfigurationTests.java @@ -43,7 +43,7 @@ import static org.mockito.Mockito.mock; * @author Vedran Pavic * @author Aleksandar Stojsavljevic */ -public class HazelcastHttpSessionConfigurationTests { +class HazelcastHttpSessionConfigurationTests { private static final String MAP_NAME = "spring:test:sessions"; @@ -54,150 +54,130 @@ public class HazelcastHttpSessionConfigurationTests { private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); @AfterEach - public void closeContext() { + void closeContext() { if (this.context != null) { this.context.close(); } } @Test - public void noHazelcastInstanceConfiguration() { + void noHazelcastInstanceConfiguration() { assertThatExceptionOfType(BeanCreationException.class) - .isThrownBy( - () -> registerAndRefresh(NoHazelcastInstanceConfiguration.class)) + .isThrownBy(() -> registerAndRefresh(NoHazelcastInstanceConfiguration.class)) .withMessageContaining("HazelcastInstance"); } @Test - public void defaultConfiguration() { + void defaultConfiguration() { registerAndRefresh(DefaultConfiguration.class); assertThat(this.context.getBean(HazelcastSessionRepository.class)).isNotNull(); } @Test - public void customTableName() { + void customTableName() { registerAndRefresh(CustomSessionMapNameConfiguration.class); - HazelcastSessionRepository repository = this.context - .getBean(HazelcastSessionRepository.class); - HazelcastHttpSessionConfiguration configuration = this.context - .getBean(HazelcastHttpSessionConfiguration.class); + HazelcastSessionRepository repository = this.context.getBean(HazelcastSessionRepository.class); + HazelcastHttpSessionConfiguration configuration = this.context.getBean(HazelcastHttpSessionConfiguration.class); assertThat(repository).isNotNull(); - assertThat(ReflectionTestUtils.getField(configuration, "sessionMapName")) - .isEqualTo(MAP_NAME); + assertThat(ReflectionTestUtils.getField(configuration, "sessionMapName")).isEqualTo(MAP_NAME); } @Test - public void setCustomSessionMapName() { - registerAndRefresh(BaseConfiguration.class, - CustomSessionMapNameSetConfiguration.class); + void setCustomSessionMapName() { + registerAndRefresh(BaseConfiguration.class, CustomSessionMapNameSetConfiguration.class); - HazelcastSessionRepository repository = this.context - .getBean(HazelcastSessionRepository.class); - HazelcastHttpSessionConfiguration configuration = this.context - .getBean(HazelcastHttpSessionConfiguration.class); + HazelcastSessionRepository repository = this.context.getBean(HazelcastSessionRepository.class); + HazelcastHttpSessionConfiguration configuration = this.context.getBean(HazelcastHttpSessionConfiguration.class); assertThat(repository).isNotNull(); - assertThat(ReflectionTestUtils.getField(configuration, "sessionMapName")) - .isEqualTo(MAP_NAME); + assertThat(ReflectionTestUtils.getField(configuration, "sessionMapName")).isEqualTo(MAP_NAME); } @Test - public void setCustomMaxInactiveIntervalInSeconds() { - registerAndRefresh(BaseConfiguration.class, - CustomMaxInactiveIntervalInSecondsSetConfiguration.class); + void setCustomMaxInactiveIntervalInSeconds() { + registerAndRefresh(BaseConfiguration.class, CustomMaxInactiveIntervalInSecondsSetConfiguration.class); - HazelcastSessionRepository repository = this.context - .getBean(HazelcastSessionRepository.class); + HazelcastSessionRepository repository = this.context.getBean(HazelcastSessionRepository.class); assertThat(repository).isNotNull(); assertThat(ReflectionTestUtils.getField(repository, "defaultMaxInactiveInterval")) .isEqualTo(MAX_INACTIVE_INTERVAL_IN_SECONDS); } @Test - public void customMaxInactiveIntervalInSeconds() { + void customMaxInactiveIntervalInSeconds() { registerAndRefresh(CustomMaxInactiveIntervalInSecondsConfiguration.class); - HazelcastSessionRepository repository = this.context - .getBean(HazelcastSessionRepository.class); + HazelcastSessionRepository repository = this.context.getBean(HazelcastSessionRepository.class); assertThat(repository).isNotNull(); assertThat(ReflectionTestUtils.getField(repository, "defaultMaxInactiveInterval")) .isEqualTo(MAX_INACTIVE_INTERVAL_IN_SECONDS); } @Test - public void customFlushImmediately() { + void customFlushImmediately() { registerAndRefresh(CustomFlushImmediatelyConfiguration.class); - HazelcastSessionRepository repository = this.context - .getBean(HazelcastSessionRepository.class); + HazelcastSessionRepository repository = this.context.getBean(HazelcastSessionRepository.class); assertThat(repository).isNotNull(); assertThat(ReflectionTestUtils.getField(repository, "hazelcastFlushMode")) .isEqualTo(HazelcastFlushMode.IMMEDIATE); } @Test - public void setCustomFlushImmediately() { - registerAndRefresh(BaseConfiguration.class, - CustomFlushImmediatelySetConfiguration.class); + void setCustomFlushImmediately() { + registerAndRefresh(BaseConfiguration.class, CustomFlushImmediatelySetConfiguration.class); - HazelcastSessionRepository repository = this.context - .getBean(HazelcastSessionRepository.class); + HazelcastSessionRepository repository = this.context.getBean(HazelcastSessionRepository.class); assertThat(repository).isNotNull(); assertThat(ReflectionTestUtils.getField(repository, "hazelcastFlushMode")) .isEqualTo(HazelcastFlushMode.IMMEDIATE); } @Test - public void qualifiedHazelcastInstanceConfiguration() { + void qualifiedHazelcastInstanceConfiguration() { registerAndRefresh(QualifiedHazelcastInstanceConfiguration.class); - HazelcastSessionRepository repository = this.context - .getBean(HazelcastSessionRepository.class); - HazelcastInstance hazelcastInstance = this.context - .getBean("qualifiedHazelcastInstance", HazelcastInstance.class); + HazelcastSessionRepository repository = this.context.getBean(HazelcastSessionRepository.class); + HazelcastInstance hazelcastInstance = this.context.getBean("qualifiedHazelcastInstance", + HazelcastInstance.class); assertThat(repository).isNotNull(); assertThat(hazelcastInstance).isNotNull(); - assertThat(ReflectionTestUtils.getField(repository, "sessions")).isEqualTo( - QualifiedHazelcastInstanceConfiguration.qualifiedHazelcastInstanceSessions); + assertThat(ReflectionTestUtils.getField(repository, "sessions")) + .isEqualTo(QualifiedHazelcastInstanceConfiguration.qualifiedHazelcastInstanceSessions); } @Test - public void primaryHazelcastInstanceConfiguration() { + void primaryHazelcastInstanceConfiguration() { registerAndRefresh(PrimaryHazelcastInstanceConfiguration.class); - HazelcastSessionRepository repository = this.context - .getBean(HazelcastSessionRepository.class); - HazelcastInstance hazelcastInstance = this.context - .getBean("primaryHazelcastInstance", HazelcastInstance.class); + HazelcastSessionRepository repository = this.context.getBean(HazelcastSessionRepository.class); + HazelcastInstance hazelcastInstance = this.context.getBean("primaryHazelcastInstance", HazelcastInstance.class); assertThat(repository).isNotNull(); assertThat(hazelcastInstance).isNotNull(); - assertThat(ReflectionTestUtils.getField(repository, "sessions")).isEqualTo( - PrimaryHazelcastInstanceConfiguration.primaryHazelcastInstanceSessions); + assertThat(ReflectionTestUtils.getField(repository, "sessions")) + .isEqualTo(PrimaryHazelcastInstanceConfiguration.primaryHazelcastInstanceSessions); } @Test - public void qualifiedAndPrimaryHazelcastInstanceConfiguration() { + void qualifiedAndPrimaryHazelcastInstanceConfiguration() { registerAndRefresh(QualifiedAndPrimaryHazelcastInstanceConfiguration.class); - HazelcastSessionRepository repository = this.context - .getBean(HazelcastSessionRepository.class); - HazelcastInstance hazelcastInstance = this.context - .getBean("qualifiedHazelcastInstance", HazelcastInstance.class); + HazelcastSessionRepository repository = this.context.getBean(HazelcastSessionRepository.class); + HazelcastInstance hazelcastInstance = this.context.getBean("qualifiedHazelcastInstance", + HazelcastInstance.class); assertThat(repository).isNotNull(); assertThat(hazelcastInstance).isNotNull(); - assertThat(ReflectionTestUtils.getField(repository, "sessions")).isEqualTo( - QualifiedAndPrimaryHazelcastInstanceConfiguration.qualifiedHazelcastInstanceSessions); + assertThat(ReflectionTestUtils.getField(repository, "sessions")) + .isEqualTo(QualifiedAndPrimaryHazelcastInstanceConfiguration.qualifiedHazelcastInstanceSessions); } @Test - public void namedHazelcastInstanceConfiguration() { + void namedHazelcastInstanceConfiguration() { registerAndRefresh(NamedHazelcastInstanceConfiguration.class); - HazelcastSessionRepository repository = this.context - .getBean(HazelcastSessionRepository.class); - HazelcastInstance hazelcastInstance = this.context.getBean("hazelcastInstance", - HazelcastInstance.class); + HazelcastSessionRepository repository = this.context.getBean(HazelcastSessionRepository.class); + HazelcastInstance hazelcastInstance = this.context.getBean("hazelcastInstance", HazelcastInstance.class); assertThat(repository).isNotNull(); assertThat(hazelcastInstance).isNotNull(); assertThat(ReflectionTestUtils.getField(repository, "sessions")) @@ -205,9 +185,9 @@ public class HazelcastHttpSessionConfigurationTests { } @Test - public void multipleHazelcastInstanceConfiguration() { - assertThatExceptionOfType(BeanCreationException.class).isThrownBy( - () -> registerAndRefresh(MultipleHazelcastInstanceConfiguration.class)) + void multipleHazelcastInstanceConfiguration() { + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> registerAndRefresh(MultipleHazelcastInstanceConfiguration.class)) .withMessageContaining("expected single matching bean but found 2"); } @@ -219,6 +199,7 @@ public class HazelcastHttpSessionConfigurationTests { @Configuration @EnableHazelcastHttpSession static class NoHazelcastInstanceConfiguration { + } static class BaseConfiguration { @@ -229,8 +210,7 @@ public class HazelcastHttpSessionConfigurationTests { @Bean public HazelcastInstance defaultHazelcastInstance() { HazelcastInstance hazelcastInstance = mock(HazelcastInstance.class); - given(hazelcastInstance.getMap(anyString())) - .willReturn(defaultHazelcastInstanceSessions); + given(hazelcastInstance.getMap(anyString())).willReturn(defaultHazelcastInstanceSessions); return hazelcastInstance; } @@ -239,16 +219,17 @@ public class HazelcastHttpSessionConfigurationTests { @Configuration @EnableHazelcastHttpSession static class DefaultConfiguration extends BaseConfiguration { + } @Configuration @EnableHazelcastHttpSession(sessionMapName = MAP_NAME) static class CustomSessionMapNameConfiguration extends BaseConfiguration { + } @Configuration - static class CustomSessionMapNameSetConfiguration - extends HazelcastHttpSessionConfiguration { + static class CustomSessionMapNameSetConfiguration extends HazelcastHttpSessionConfiguration { CustomSessionMapNameSetConfiguration() { setSessionMapName(MAP_NAME); @@ -257,8 +238,7 @@ public class HazelcastHttpSessionConfigurationTests { } @Configuration - static class CustomMaxInactiveIntervalInSecondsSetConfiguration - extends HazelcastHttpSessionConfiguration { + static class CustomMaxInactiveIntervalInSecondsSetConfiguration extends HazelcastHttpSessionConfiguration { CustomMaxInactiveIntervalInSecondsSetConfiguration() { setMaxInactiveIntervalInSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS); @@ -268,13 +248,12 @@ public class HazelcastHttpSessionConfigurationTests { @Configuration @EnableHazelcastHttpSession(maxInactiveIntervalInSeconds = MAX_INACTIVE_INTERVAL_IN_SECONDS) - static class CustomMaxInactiveIntervalInSecondsConfiguration - extends BaseConfiguration { + static class CustomMaxInactiveIntervalInSecondsConfiguration extends BaseConfiguration { + } @Configuration - static class CustomFlushImmediatelySetConfiguration - extends HazelcastHttpSessionConfiguration { + static class CustomFlushImmediatelySetConfiguration extends HazelcastHttpSessionConfiguration { CustomFlushImmediatelySetConfiguration() { setHazelcastFlushMode(HAZELCAST_FLUSH_MODE); @@ -285,6 +264,7 @@ public class HazelcastHttpSessionConfigurationTests { @Configuration @EnableHazelcastHttpSession(hazelcastFlushMode = HazelcastFlushMode.IMMEDIATE) static class CustomFlushImmediatelyConfiguration extends BaseConfiguration { + } @Configuration @@ -298,8 +278,7 @@ public class HazelcastHttpSessionConfigurationTests { @SpringSessionHazelcastInstance public HazelcastInstance qualifiedHazelcastInstance() { HazelcastInstance hazelcastInstance = mock(HazelcastInstance.class); - given(hazelcastInstance.getMap(anyString())) - .willReturn(qualifiedHazelcastInstanceSessions); + given(hazelcastInstance.getMap(anyString())).willReturn(qualifiedHazelcastInstanceSessions); return hazelcastInstance; } @@ -316,8 +295,7 @@ public class HazelcastHttpSessionConfigurationTests { @Primary public HazelcastInstance primaryHazelcastInstance() { HazelcastInstance hazelcastInstance = mock(HazelcastInstance.class); - given(hazelcastInstance.getMap(anyString())) - .willReturn(primaryHazelcastInstanceSessions); + given(hazelcastInstance.getMap(anyString())).willReturn(primaryHazelcastInstanceSessions); return hazelcastInstance; } @@ -325,8 +303,7 @@ public class HazelcastHttpSessionConfigurationTests { @Configuration @EnableHazelcastHttpSession - static class QualifiedAndPrimaryHazelcastInstanceConfiguration - extends BaseConfiguration { + static class QualifiedAndPrimaryHazelcastInstanceConfiguration extends BaseConfiguration { @SuppressWarnings("unchecked") static IMap qualifiedHazelcastInstanceSessions = mock(IMap.class); @@ -338,8 +315,7 @@ public class HazelcastHttpSessionConfigurationTests { @SpringSessionHazelcastInstance public HazelcastInstance qualifiedHazelcastInstance() { HazelcastInstance hazelcastInstance = mock(HazelcastInstance.class); - given(hazelcastInstance.getMap(anyString())) - .willReturn(qualifiedHazelcastInstanceSessions); + given(hazelcastInstance.getMap(anyString())).willReturn(qualifiedHazelcastInstanceSessions); return hazelcastInstance; } @@ -347,8 +323,7 @@ public class HazelcastHttpSessionConfigurationTests { @Primary public HazelcastInstance primaryHazelcastInstance() { HazelcastInstance hazelcastInstance = mock(HazelcastInstance.class); - given(hazelcastInstance.getMap(anyString())) - .willReturn(primaryHazelcastInstanceSessions); + given(hazelcastInstance.getMap(anyString())).willReturn(primaryHazelcastInstanceSessions); return hazelcastInstance; } @@ -364,8 +339,7 @@ public class HazelcastHttpSessionConfigurationTests { @Bean public HazelcastInstance hazelcastInstance() { HazelcastInstance hazelcastInstance = mock(HazelcastInstance.class); - given(hazelcastInstance.getMap(anyString())) - .willReturn(hazelcastInstanceSessions); + given(hazelcastInstance.getMap(anyString())).willReturn(hazelcastInstanceSessions); return hazelcastInstance; } @@ -381,8 +355,7 @@ public class HazelcastHttpSessionConfigurationTests { @Bean public HazelcastInstance secondaryHazelcastInstance() { HazelcastInstance hazelcastInstance = mock(HazelcastInstance.class); - given(hazelcastInstance.getMap(anyString())) - .willReturn(secondaryHazelcastInstanceSessions); + given(hazelcastInstance.getMap(anyString())).willReturn(secondaryHazelcastInstanceSessions); return hazelcastInstance; } diff --git a/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/AbstractContainerJdbcOperationsSessionRepositoryITests.java b/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/AbstractContainerJdbcOperationsSessionRepositoryITests.java index 474b882f..dd534b02 100644 --- a/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/AbstractContainerJdbcOperationsSessionRepositoryITests.java +++ b/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/AbstractContainerJdbcOperationsSessionRepositoryITests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,7 +31,7 @@ import org.springframework.jdbc.datasource.init.DatabasePopulator; * * @author Vedran Pavic */ -public abstract class AbstractContainerJdbcOperationsSessionRepositoryITests +abstract class AbstractContainerJdbcOperationsSessionRepositoryITests extends AbstractJdbcOperationsSessionRepositoryITests { static class BaseContainerConfig extends BaseConfig { @@ -46,8 +46,7 @@ public abstract class AbstractContainerJdbcOperationsSessionRepositoryITests } @Bean - public DataSourceInitializer dataSourceInitializer(DataSource dataSource, - DatabasePopulator databasePopulator) { + public DataSourceInitializer dataSourceInitializer(DataSource dataSource, DatabasePopulator databasePopulator) { DataSourceInitializer initializer = new DataSourceInitializer(); initializer.setDataSource(dataSource); initializer.setDatabasePopulator(databasePopulator); diff --git a/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/AbstractJdbcOperationsSessionRepositoryITests.java b/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/AbstractJdbcOperationsSessionRepositoryITests.java index 2a0a1c68..793fb34b 100644 --- a/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/AbstractJdbcOperationsSessionRepositoryITests.java +++ b/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/AbstractJdbcOperationsSessionRepositoryITests.java @@ -50,7 +50,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Vedran Pavic */ -public abstract class AbstractJdbcOperationsSessionRepositoryITests { +abstract class AbstractJdbcOperationsSessionRepositoryITests { private static final String SPRING_SECURITY_CONTEXT = "SPRING_SECURITY_CONTEXT"; @@ -64,26 +64,22 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { private SecurityContext changedContext; @BeforeEach - public void setUp() { + void setUp() { this.context = SecurityContextHolder.createEmptyContext(); - this.context.setAuthentication( - new UsernamePasswordAuthenticationToken("username-" + UUID.randomUUID(), - "na", AuthorityUtils.createAuthorityList("ROLE_USER"))); + this.context.setAuthentication(new UsernamePasswordAuthenticationToken("username-" + UUID.randomUUID(), "na", + AuthorityUtils.createAuthorityList("ROLE_USER"))); this.changedContext = SecurityContextHolder.createEmptyContext(); this.changedContext.setAuthentication(new UsernamePasswordAuthenticationToken( - "changedContext-" + UUID.randomUUID(), "na", - AuthorityUtils.createAuthorityList("ROLE_USER"))); + "changedContext-" + UUID.randomUUID(), "na", AuthorityUtils.createAuthorityList("ROLE_USER"))); } @Test - public void saveWhenNoAttributesThenCanBeFound() { - JdbcOperationsSessionRepository.JdbcSession toSave = this.repository - .createSession(); + void saveWhenNoAttributesThenCanBeFound() { + JdbcOperationsSessionRepository.JdbcSession toSave = this.repository.createSession(); this.repository.save(toSave); - JdbcOperationsSessionRepository.JdbcSession session = this.repository - .findById(toSave.getId()); + JdbcOperationsSessionRepository.JdbcSession session = this.repository.findById(toSave.getId()); assertThat(session).isNotNull(); assertThat(session.isChanged()).isFalse(); @@ -91,16 +87,15 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { } @Test - public void saves() { + void saves() { String username = "saves-" + System.currentTimeMillis(); - JdbcOperationsSessionRepository.JdbcSession toSave = this.repository - .createSession(); + JdbcOperationsSessionRepository.JdbcSession toSave = this.repository.createSession(); String expectedAttributeName = "a"; String expectedAttributeValue = "b"; toSave.setAttribute(expectedAttributeName, expectedAttributeValue); - Authentication toSaveToken = new UsernamePasswordAuthenticationToken(username, - "password", AuthorityUtils.createAuthorityList("ROLE_USER")); + Authentication toSaveToken = new UsernamePasswordAuthenticationToken(username, "password", + AuthorityUtils.createAuthorityList("ROLE_USER")); SecurityContext toSaveContext = SecurityContextHolder.createEmptyContext(); toSaveContext.setAuthentication(toSaveToken); toSave.setAttribute(SPRING_SECURITY_CONTEXT, toSaveContext); @@ -108,8 +103,7 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { this.repository.save(toSave); - JdbcOperationsSessionRepository.JdbcSession session = this.repository - .findById(toSave.getId()); + JdbcOperationsSessionRepository.JdbcSession session = this.repository.findById(toSave.getId()); assertThat(session.getId()).isEqualTo(toSave.getId()); assertThat(session.isChanged()).isFalse(); @@ -125,17 +119,15 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { @Test @Transactional(readOnly = true) - public void savesInReadOnlyTransaction() { - JdbcOperationsSessionRepository.JdbcSession toSave = this.repository - .createSession(); + void savesInReadOnlyTransaction() { + JdbcOperationsSessionRepository.JdbcSession toSave = this.repository.createSession(); this.repository.save(toSave); } @Test - public void putAllOnSingleAttrDoesNotRemoveOld() { - JdbcOperationsSessionRepository.JdbcSession toSave = this.repository - .createSession(); + void putAllOnSingleAttrDoesNotRemoveOld() { + JdbcOperationsSessionRepository.JdbcSession toSave = this.repository.createSession(); toSave.setAttribute("a", "b"); this.repository.save(toSave); @@ -146,8 +138,7 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { this.repository.save(toSave); toSave = this.repository.findById(toSave.getId()); - JdbcOperationsSessionRepository.JdbcSession session = this.repository - .findById(toSave.getId()); + JdbcOperationsSessionRepository.JdbcSession session = this.repository.findById(toSave.getId()); assertThat(session.isChanged()).isFalse(); assertThat(session.getDelta()).isEmpty(); assertThat(session.getAttributeNames().size()).isEqualTo(2); @@ -158,11 +149,9 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { } @Test - public void updateLastAccessedTime() { - JdbcOperationsSessionRepository.JdbcSession toSave = this.repository - .createSession(); - toSave.setLastAccessedTime(Instant.now() - .minusSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS + 1)); + void updateLastAccessedTime() { + JdbcOperationsSessionRepository.JdbcSession toSave = this.repository.createSession(); + toSave.setLastAccessedTime(Instant.now().minusSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS + 1)); this.repository.save(toSave); @@ -170,8 +159,7 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { toSave.setLastAccessedTime(lastAccessedTime); this.repository.save(toSave); - JdbcOperationsSessionRepository.JdbcSession session = this.repository - .findById(toSave.getId()); + JdbcOperationsSessionRepository.JdbcSession session = this.repository.findById(toSave.getId()); assertThat(session).isNotNull(); assertThat(session.isChanged()).isFalse(); @@ -182,10 +170,9 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { } @Test - public void findByPrincipalName() { + void findByPrincipalName() { String principalName = "findByPrincipalName" + UUID.randomUUID(); - JdbcOperationsSessionRepository.JdbcSession toSave = this.repository - .createSession(); + JdbcOperationsSessionRepository.JdbcSession toSave = this.repository.createSession(); toSave.setAttribute(INDEX_NAME, principalName); this.repository.save(toSave); @@ -198,22 +185,18 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { this.repository.deleteById(toSave.getId()); - findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, - principalName); + findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, principalName); assertThat(findByPrincipalName).hasSize(0); assertThat(findByPrincipalName.keySet()).doesNotContain(toSave.getId()); } @Test - public void findByPrincipalNameExpireRemovesIndex() { - String principalName = "findByPrincipalNameExpireRemovesIndex" - + UUID.randomUUID(); - JdbcOperationsSessionRepository.JdbcSession toSave = this.repository - .createSession(); + void findByPrincipalNameExpireRemovesIndex() { + String principalName = "findByPrincipalNameExpireRemovesIndex" + UUID.randomUUID(); + JdbcOperationsSessionRepository.JdbcSession toSave = this.repository.createSession(); toSave.setAttribute(INDEX_NAME, principalName); - toSave.setLastAccessedTime(Instant.now() - .minusSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS + 1)); + toSave.setLastAccessedTime(Instant.now().minusSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS + 1)); this.repository.save(toSave); this.repository.cleanUpExpiredSessions(); @@ -226,11 +209,9 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { } @Test - public void findByPrincipalNameNoPrincipalNameChange() { - String principalName = "findByPrincipalNameNoPrincipalNameChange" - + UUID.randomUUID(); - JdbcOperationsSessionRepository.JdbcSession toSave = this.repository - .createSession(); + void findByPrincipalNameNoPrincipalNameChange() { + String principalName = "findByPrincipalNameNoPrincipalNameChange" + UUID.randomUUID(); + JdbcOperationsSessionRepository.JdbcSession toSave = this.repository.createSession(); toSave.setAttribute(INDEX_NAME, principalName); this.repository.save(toSave); @@ -250,11 +231,9 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { } @Test - public void findByPrincipalNameNoPrincipalNameChangeReload() { - String principalName = "findByPrincipalNameNoPrincipalNameChangeReload" - + UUID.randomUUID(); - JdbcOperationsSessionRepository.JdbcSession toSave = this.repository - .createSession(); + void findByPrincipalNameNoPrincipalNameChangeReload() { + String principalName = "findByPrincipalNameNoPrincipalNameChangeReload" + UUID.randomUUID(); + JdbcOperationsSessionRepository.JdbcSession toSave = this.repository.createSession(); toSave.setAttribute(INDEX_NAME, principalName); this.repository.save(toSave); @@ -276,10 +255,9 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { } @Test - public void findByDeletedPrincipalName() { + void findByDeletedPrincipalName() { String principalName = "findByDeletedPrincipalName" + UUID.randomUUID(); - JdbcOperationsSessionRepository.JdbcSession toSave = this.repository - .createSession(); + JdbcOperationsSessionRepository.JdbcSession toSave = this.repository.createSession(); toSave.setAttribute(INDEX_NAME, principalName); this.repository.save(toSave); @@ -294,11 +272,10 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { } @Test - public void findByChangedPrincipalName() { + void findByChangedPrincipalName() { String principalName = "findByChangedPrincipalName" + UUID.randomUUID(); String principalNameChanged = "findByChangedPrincipalName" + UUID.randomUUID(); - JdbcOperationsSessionRepository.JdbcSession toSave = this.repository - .createSession(); + JdbcOperationsSessionRepository.JdbcSession toSave = this.repository.createSession(); toSave.setAttribute(INDEX_NAME, principalName); this.repository.save(toSave); @@ -310,8 +287,7 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { .findByIndexNameAndIndexValue(INDEX_NAME, principalName); assertThat(findByPrincipalName).isEmpty(); - findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, - principalNameChanged); + findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, principalNameChanged); assertThat(findByPrincipalName).hasSize(1); assertThat(findByPrincipalName.keySet()).containsOnly(toSave.getId()); @@ -322,16 +298,14 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { } @Test - public void findByDeletedPrincipalNameReload() { + void findByDeletedPrincipalNameReload() { String principalName = "findByDeletedPrincipalName" + UUID.randomUUID(); - JdbcOperationsSessionRepository.JdbcSession toSave = this.repository - .createSession(); + JdbcOperationsSessionRepository.JdbcSession toSave = this.repository.createSession(); toSave.setAttribute(INDEX_NAME, principalName); this.repository.save(toSave); - JdbcOperationsSessionRepository.JdbcSession getSession = this.repository - .findById(toSave.getId()); + JdbcOperationsSessionRepository.JdbcSession getSession = this.repository.findById(toSave.getId()); getSession.setAttribute(INDEX_NAME, null); this.repository.save(getSession); @@ -342,17 +316,15 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { } @Test - public void findByChangedPrincipalNameReload() { + void findByChangedPrincipalNameReload() { String principalName = "findByChangedPrincipalName" + UUID.randomUUID(); String principalNameChanged = "findByChangedPrincipalName" + UUID.randomUUID(); - JdbcOperationsSessionRepository.JdbcSession toSave = this.repository - .createSession(); + JdbcOperationsSessionRepository.JdbcSession toSave = this.repository.createSession(); toSave.setAttribute(INDEX_NAME, principalName); this.repository.save(toSave); - JdbcOperationsSessionRepository.JdbcSession getSession = this.repository - .findById(toSave.getId()); + JdbcOperationsSessionRepository.JdbcSession getSession = this.repository.findById(toSave.getId()); getSession.setAttribute(INDEX_NAME, principalNameChanged); this.repository.save(getSession); @@ -361,8 +333,7 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { .findByIndexNameAndIndexValue(INDEX_NAME, principalName); assertThat(findByPrincipalName).isEmpty(); - findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, - principalNameChanged); + findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, principalNameChanged); assertThat(findByPrincipalName).hasSize(1); assertThat(findByPrincipalName.keySet()).containsOnly(toSave.getId()); @@ -373,9 +344,8 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { } @Test - public void findBySecurityPrincipalName() { - JdbcOperationsSessionRepository.JdbcSession toSave = this.repository - .createSession(); + void findBySecurityPrincipalName() { + JdbcOperationsSessionRepository.JdbcSession toSave = this.repository.createSession(); toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.context); this.repository.save(toSave); @@ -388,20 +358,17 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { this.repository.deleteById(toSave.getId()); - findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, - getSecurityName()); + findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, getSecurityName()); assertThat(findByPrincipalName).hasSize(0); assertThat(findByPrincipalName.keySet()).doesNotContain(toSave.getId()); } @Test - public void findBySecurityPrincipalNameExpireRemovesIndex() { - JdbcOperationsSessionRepository.JdbcSession toSave = this.repository - .createSession(); + void findBySecurityPrincipalNameExpireRemovesIndex() { + JdbcOperationsSessionRepository.JdbcSession toSave = this.repository.createSession(); toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.context); - toSave.setLastAccessedTime(Instant.now() - .minusSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS + 1)); + toSave.setLastAccessedTime(Instant.now().minusSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS + 1)); this.repository.save(toSave); this.repository.cleanUpExpiredSessions(); @@ -414,9 +381,8 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { } @Test - public void findByPrincipalNameNoSecurityPrincipalNameChange() { - JdbcOperationsSessionRepository.JdbcSession toSave = this.repository - .createSession(); + void findByPrincipalNameNoSecurityPrincipalNameChange() { + JdbcOperationsSessionRepository.JdbcSession toSave = this.repository.createSession(); toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.context); this.repository.save(toSave); @@ -436,9 +402,8 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { } @Test - public void findByPrincipalNameNoSecurityPrincipalNameChangeReload() { - JdbcOperationsSessionRepository.JdbcSession toSave = this.repository - .createSession(); + void findByPrincipalNameNoSecurityPrincipalNameChangeReload() { + JdbcOperationsSessionRepository.JdbcSession toSave = this.repository.createSession(); toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.context); this.repository.save(toSave); @@ -460,9 +425,8 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { } @Test - public void findByDeletedSecurityPrincipalName() { - JdbcOperationsSessionRepository.JdbcSession toSave = this.repository - .createSession(); + void findByDeletedSecurityPrincipalName() { + JdbcOperationsSessionRepository.JdbcSession toSave = this.repository.createSession(); toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.context); this.repository.save(toSave); @@ -477,9 +441,8 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { } @Test - public void findByChangedSecurityPrincipalName() { - JdbcOperationsSessionRepository.JdbcSession toSave = this.repository - .createSession(); + void findByChangedSecurityPrincipalName() { + JdbcOperationsSessionRepository.JdbcSession toSave = this.repository.createSession(); toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.context); this.repository.save(toSave); @@ -491,8 +454,7 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { .findByIndexNameAndIndexValue(INDEX_NAME, getSecurityName()); assertThat(findByPrincipalName).isEmpty(); - findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, - getChangedSecurityName()); + findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, getChangedSecurityName()); assertThat(findByPrincipalName).hasSize(1); assertThat(findByPrincipalName.keySet()).containsOnly(toSave.getId()); @@ -503,15 +465,13 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { } @Test - public void findByDeletedSecurityPrincipalNameReload() { - JdbcOperationsSessionRepository.JdbcSession toSave = this.repository - .createSession(); + void findByDeletedSecurityPrincipalNameReload() { + JdbcOperationsSessionRepository.JdbcSession toSave = this.repository.createSession(); toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.context); this.repository.save(toSave); - JdbcOperationsSessionRepository.JdbcSession getSession = this.repository - .findById(toSave.getId()); + JdbcOperationsSessionRepository.JdbcSession getSession = this.repository.findById(toSave.getId()); getSession.setAttribute(INDEX_NAME, null); this.repository.save(getSession); @@ -522,15 +482,13 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { } @Test - public void findByChangedSecurityPrincipalNameReload() { - JdbcOperationsSessionRepository.JdbcSession toSave = this.repository - .createSession(); + void findByChangedSecurityPrincipalNameReload() { + JdbcOperationsSessionRepository.JdbcSession toSave = this.repository.createSession(); toSave.setAttribute(SPRING_SECURITY_CONTEXT, this.context); this.repository.save(toSave); - JdbcOperationsSessionRepository.JdbcSession getSession = this.repository - .findById(toSave.getId()); + JdbcOperationsSessionRepository.JdbcSession getSession = this.repository.findById(toSave.getId()); getSession.setAttribute(SPRING_SECURITY_CONTEXT, this.changedContext); this.repository.save(getSession); @@ -539,8 +497,7 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { .findByIndexNameAndIndexValue(INDEX_NAME, getSecurityName()); assertThat(findByPrincipalName).isEmpty(); - findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, - getChangedSecurityName()); + findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME, getChangedSecurityName()); assertThat(findByPrincipalName).hasSize(1); assertThat(findByPrincipalName.keySet()).containsOnly(toSave.getId()); @@ -551,9 +508,8 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { } @Test - public void cleanupInactiveSessionsUsingRepositoryDefinedInterval() { - JdbcOperationsSessionRepository.JdbcSession session = this.repository - .createSession(); + void cleanupInactiveSessionsUsingRepositoryDefinedInterval() { + JdbcOperationsSessionRepository.JdbcSession session = this.repository.createSession(); this.repository.save(session); @@ -580,9 +536,8 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { // gh-580 @Test - public void cleanupInactiveSessionsUsingSessionDefinedInterval() { - JdbcOperationsSessionRepository.JdbcSession session = this.repository - .createSession(); + void cleanupInactiveSessionsUsingSessionDefinedInterval() { + JdbcOperationsSessionRepository.JdbcSession session = this.repository.createSession(); session.setMaxInactiveInterval(Duration.ofMinutes(45)); this.repository.save(session); @@ -609,17 +564,15 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { } @Test - public void changeSessionIdWhenOnlyChangeId() { + void changeSessionIdWhenOnlyChangeId() { String attrName = "changeSessionId"; String attrValue = "changeSessionId-value"; - JdbcOperationsSessionRepository.JdbcSession toSave = this.repository - .createSession(); + JdbcOperationsSessionRepository.JdbcSession toSave = this.repository.createSession(); toSave.setAttribute(attrName, attrValue); this.repository.save(toSave); - JdbcOperationsSessionRepository.JdbcSession findById = this.repository - .findById(toSave.getId()); + JdbcOperationsSessionRepository.JdbcSession findById = this.repository.findById(toSave.getId()); assertThat(findById.getAttribute(attrName)).isEqualTo(attrValue); @@ -630,19 +583,16 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { assertThat(this.repository.findById(originalFindById)).isNull(); - JdbcOperationsSessionRepository.JdbcSession findByChangeSessionId = this.repository - .findById(changeSessionId); + JdbcOperationsSessionRepository.JdbcSession findByChangeSessionId = this.repository.findById(changeSessionId); assertThat(findByChangeSessionId.isChanged()).isFalse(); assertThat(findByChangeSessionId.getDelta()).isEmpty(); - assertThat(findByChangeSessionId.getAttribute(attrName)) - .isEqualTo(attrValue); + assertThat(findByChangeSessionId.getAttribute(attrName)).isEqualTo(attrValue); } @Test - public void changeSessionIdWhenChangeTwice() { - JdbcOperationsSessionRepository.JdbcSession toSave = this.repository - .createSession(); + void changeSessionIdWhenChangeTwice() { + JdbcOperationsSessionRepository.JdbcSession toSave = this.repository.createSession(); this.repository.save(toSave); @@ -658,17 +608,15 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { } @Test - public void changeSessionIdWhenSetAttributeOnChangedSession() { + void changeSessionIdWhenSetAttributeOnChangedSession() { String attrName = "changeSessionId"; String attrValue = "changeSessionId-value"; - JdbcOperationsSessionRepository.JdbcSession toSave = this.repository - .createSession(); + JdbcOperationsSessionRepository.JdbcSession toSave = this.repository.createSession(); this.repository.save(toSave); - JdbcOperationsSessionRepository.JdbcSession findById = this.repository - .findById(toSave.getId()); + JdbcOperationsSessionRepository.JdbcSession findById = this.repository.findById(toSave.getId()); findById.setAttribute(attrName, attrValue); @@ -679,19 +627,16 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { assertThat(this.repository.findById(originalFindById)).isNull(); - JdbcOperationsSessionRepository.JdbcSession findByChangeSessionId = this.repository - .findById(changeSessionId); + JdbcOperationsSessionRepository.JdbcSession findByChangeSessionId = this.repository.findById(changeSessionId); assertThat(findByChangeSessionId.isChanged()).isFalse(); assertThat(findByChangeSessionId.getDelta()).isEmpty(); - assertThat(findByChangeSessionId.getAttribute(attrName)) - .isEqualTo(attrValue); + assertThat(findByChangeSessionId.getAttribute(attrName)).isEqualTo(attrValue); } @Test - public void changeSessionIdWhenHasNotSaved() { - JdbcOperationsSessionRepository.JdbcSession toSave = this.repository - .createSession(); + void changeSessionIdWhenHasNotSaved() { + JdbcOperationsSessionRepository.JdbcSession toSave = this.repository.createSession(); String originalId = toSave.getId(); toSave.changeSessionId(); @@ -702,9 +647,8 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { } @Test // gh-1070 - public void saveUpdatedAddAndModifyAttribute() { - JdbcOperationsSessionRepository.JdbcSession session = this.repository - .createSession(); + void saveUpdatedAddAndModifyAttribute() { + JdbcOperationsSessionRepository.JdbcSession session = this.repository.createSession(); this.repository.save(session); session = this.repository.findById(session.getId()); session.setAttribute("testName", "testValue1"); @@ -716,9 +660,8 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { } @Test // gh-1070 - public void saveUpdatedAddAndRemoveAttribute() { - JdbcOperationsSessionRepository.JdbcSession session = this.repository - .createSession(); + void saveUpdatedAddAndRemoveAttribute() { + JdbcOperationsSessionRepository.JdbcSession session = this.repository.createSession(); this.repository.save(session); session = this.repository.findById(session.getId()); session.setAttribute("testName", "testValue"); @@ -730,9 +673,8 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { } @Test // gh-1070 - public void saveUpdatedModifyAndRemoveAttribute() { - JdbcOperationsSessionRepository.JdbcSession session = this.repository - .createSession(); + void saveUpdatedModifyAndRemoveAttribute() { + JdbcOperationsSessionRepository.JdbcSession session = this.repository.createSession(); session.setAttribute("testName", "testValue1"); this.repository.save(session); session = this.repository.findById(session.getId()); @@ -745,9 +687,8 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { } @Test // gh-1070 - public void saveUpdatedRemoveAndAddAttribute() { - JdbcOperationsSessionRepository.JdbcSession session = this.repository - .createSession(); + void saveUpdatedRemoveAndAddAttribute() { + JdbcOperationsSessionRepository.JdbcSession session = this.repository.createSession(); session.setAttribute("testName", "testValue1"); this.repository.save(session); session = this.repository.findById(session.getId()); @@ -760,9 +701,8 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { } @Test // gh-1031 - public void saveDeleted() { - JdbcOperationsSessionRepository.JdbcSession session = this.repository - .createSession(); + void saveDeleted() { + JdbcOperationsSessionRepository.JdbcSession session = this.repository.createSession(); this.repository.save(session); session = this.repository.findById(session.getId()); this.repository.deleteById(session.getId()); @@ -773,9 +713,8 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { } @Test // gh-1031 - public void saveDeletedAddAttribute() { - JdbcOperationsSessionRepository.JdbcSession session = this.repository - .createSession(); + void saveDeletedAddAttribute() { + JdbcOperationsSessionRepository.JdbcSession session = this.repository.createSession(); this.repository.save(session); session = this.repository.findById(session.getId()); this.repository.deleteById(session.getId()); @@ -787,15 +726,13 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { } @Test // gh-1133 - public void sessionFromStoreResolvesAttributesLazily() { - JdbcOperationsSessionRepository.JdbcSession session = this.repository - .createSession(); + void sessionFromStoreResolvesAttributesLazily() { + JdbcOperationsSessionRepository.JdbcSession session = this.repository.createSession(); session.setAttribute("attribute1", "value1"); session.setAttribute("attribute2", "value2"); this.repository.save(session); session = this.repository.findById(session.getId()); - MapSession delegate = (MapSession) ReflectionTestUtils.getField(session, - "delegate"); + MapSession delegate = (MapSession) ReflectionTestUtils.getField(session, "delegate"); Supplier attribute1 = delegate.getAttribute("attribute1"); assertThat(ReflectionTestUtils.getField(attribute1, "value")).isNull(); @@ -808,12 +745,11 @@ public abstract class AbstractJdbcOperationsSessionRepositoryITests { } @Test // gh-1203 - public void saveWithLargeAttribute() { + void saveWithLargeAttribute() { String attributeName = "largeAttribute"; int arraySize = 4000; - JdbcOperationsSessionRepository.JdbcSession session = this.repository - .createSession(); + JdbcOperationsSessionRepository.JdbcSession session = this.repository.createSession(); session.setAttribute(attributeName, new byte[arraySize]); this.repository.save(session); session = this.repository.findById(session.getId()); diff --git a/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/DatabaseContainers.java b/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/DatabaseContainers.java index 5c9f3a09..f7abdb44 100644 --- a/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/DatabaseContainers.java +++ b/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/DatabaseContainers.java @@ -78,9 +78,8 @@ final class DatabaseContainers { @Override protected void configure() { super.configure(); - setCommand("mysqld", "--character-set-server=utf8mb4", - "--collation-server=utf8mb4_unicode_ci", "--innodb_large_prefix", - "--innodb_file_format=barracuda", "--innodb-file-per-table"); + setCommand("mysqld", "--character-set-server=utf8mb4", "--collation-server=utf8mb4_unicode_ci", + "--innodb_large_prefix", "--innodb_file_format=barracuda", "--innodb-file-per-table"); } } @@ -94,8 +93,7 @@ final class DatabaseContainers { @Override protected void configure() { super.configure(); - setCommand("mysqld", "--character-set-server=utf8mb4", - "--collation-server=utf8mb4_unicode_ci"); + setCommand("mysqld", "--character-set-server=utf8mb4", "--collation-server=utf8mb4_unicode_ci"); } } @@ -109,8 +107,7 @@ final class DatabaseContainers { @Override protected void configure() { super.configure(); - setCommand("mysqld", "--character-set-server=utf8mb4", - "--collation-server=utf8mb4_unicode_ci"); + setCommand("mysqld", "--character-set-server=utf8mb4", "--collation-server=utf8mb4_unicode_ci"); } @Override @@ -139,8 +136,7 @@ final class DatabaseContainers { } - private static class PostgreSql9Container - extends PostgreSQLContainer { + private static class PostgreSql9Container extends PostgreSQLContainer { PostgreSql9Container() { super("postgres:9.6.13"); @@ -148,8 +144,7 @@ final class DatabaseContainers { } - private static class PostgreSql10Container - extends PostgreSQLContainer { + private static class PostgreSql10Container extends PostgreSQLContainer { PostgreSql10Container() { super("postgres:10.8"); @@ -157,8 +152,7 @@ final class DatabaseContainers { } - private static class PostgreSql11Container - extends PostgreSQLContainer { + private static class PostgreSql11Container extends PostgreSQLContainer { PostgreSql11Container() { super("postgres:11.3"); @@ -166,8 +160,7 @@ final class DatabaseContainers { } - private static class SqlServer2017Container - extends MSSQLServerContainer { + private static class SqlServer2017Container extends MSSQLServerContainer { SqlServer2017Container() { super("mcr.microsoft.com/mssql/server:2017-CU15"); diff --git a/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/DatabasePopulators.java b/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/DatabasePopulators.java index 88740df6..1cd2cdb8 100644 --- a/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/DatabasePopulators.java +++ b/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/DatabasePopulators.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,23 +31,23 @@ final class DatabasePopulators { } static ResourceDatabasePopulator mySql() { - return new ResourceDatabasePopulator(new ClassPathResource( - "org/springframework/session/jdbc/schema-mysql.sql")); + return new ResourceDatabasePopulator( + new ClassPathResource("org/springframework/session/jdbc/schema-mysql.sql")); } static ResourceDatabasePopulator oracle() { - return new ResourceDatabasePopulator(new ClassPathResource( - "org/springframework/session/jdbc/schema-oracle.sql")); + return new ResourceDatabasePopulator( + new ClassPathResource("org/springframework/session/jdbc/schema-oracle.sql")); } static ResourceDatabasePopulator postgreSql() { - return new ResourceDatabasePopulator(new ClassPathResource( - "org/springframework/session/jdbc/schema-postgresql.sql")); + return new ResourceDatabasePopulator( + new ClassPathResource("org/springframework/session/jdbc/schema-postgresql.sql")); } static ResourceDatabasePopulator sqlServer() { - return new ResourceDatabasePopulator(new ClassPathResource( - "org/springframework/session/jdbc/schema-sqlserver.sql")); + return new ResourceDatabasePopulator( + new ClassPathResource("org/springframework/session/jdbc/schema-sqlserver.sql")); } } diff --git a/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/DerbyJdbcOperationsSessionRepositoryITests.java b/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/DerbyJdbcOperationsSessionRepositoryITests.java index 9864cb30..32cde2a7 100644 --- a/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/DerbyJdbcOperationsSessionRepositoryITests.java +++ b/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/DerbyJdbcOperationsSessionRepositoryITests.java @@ -35,18 +35,15 @@ import org.springframework.test.context.web.WebAppConfiguration; @ExtendWith(SpringExtension.class) @WebAppConfiguration @ContextConfiguration -public class DerbyJdbcOperationsSessionRepositoryITests - extends AbstractJdbcOperationsSessionRepositoryITests { +class DerbyJdbcOperationsSessionRepositoryITests extends AbstractJdbcOperationsSessionRepositoryITests { @Configuration static class Config extends BaseConfig { @Bean public EmbeddedDatabase dataSource() { - return new EmbeddedDatabaseBuilder() - .setType(EmbeddedDatabaseType.DERBY) - .addScript("org/springframework/session/jdbc/schema-derby.sql") - .build(); + return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.DERBY) + .addScript("org/springframework/session/jdbc/schema-derby.sql").build(); } } diff --git a/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/H2JdbcOperationsSessionRepositoryITests.java b/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/H2JdbcOperationsSessionRepositoryITests.java index 1735f1fa..9c1e9a4a 100644 --- a/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/H2JdbcOperationsSessionRepositoryITests.java +++ b/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/H2JdbcOperationsSessionRepositoryITests.java @@ -35,18 +35,15 @@ import org.springframework.test.context.web.WebAppConfiguration; @ExtendWith(SpringExtension.class) @WebAppConfiguration @ContextConfiguration -public class H2JdbcOperationsSessionRepositoryITests - extends AbstractJdbcOperationsSessionRepositoryITests { +class H2JdbcOperationsSessionRepositoryITests extends AbstractJdbcOperationsSessionRepositoryITests { @Configuration static class Config extends BaseConfig { @Bean public EmbeddedDatabase dataSource() { - return new EmbeddedDatabaseBuilder() - .setType(EmbeddedDatabaseType.H2) - .addScript("org/springframework/session/jdbc/schema-h2.sql") - .build(); + return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2) + .addScript("org/springframework/session/jdbc/schema-h2.sql").build(); } } diff --git a/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/HsqldbJdbcOperationsSessionRepositoryITests.java b/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/HsqldbJdbcOperationsSessionRepositoryITests.java index 8ed33dcc..1462d997 100644 --- a/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/HsqldbJdbcOperationsSessionRepositoryITests.java +++ b/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/HsqldbJdbcOperationsSessionRepositoryITests.java @@ -35,18 +35,15 @@ import org.springframework.test.context.web.WebAppConfiguration; @ExtendWith(SpringExtension.class) @WebAppConfiguration @ContextConfiguration -public class HsqldbJdbcOperationsSessionRepositoryITests - extends AbstractJdbcOperationsSessionRepositoryITests { +class HsqldbJdbcOperationsSessionRepositoryITests extends AbstractJdbcOperationsSessionRepositoryITests { @Configuration static class Config extends BaseConfig { @Bean public EmbeddedDatabase dataSource() { - return new EmbeddedDatabaseBuilder() - .setType(EmbeddedDatabaseType.HSQL) - .addScript("org/springframework/session/jdbc/schema-hsqldb.sql") - .build(); + return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL) + .addScript("org/springframework/session/jdbc/schema-hsqldb.sql").build(); } } diff --git a/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/MariaDb10JdbcOperationsSessionRepositoryITests.java b/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/MariaDb10JdbcOperationsSessionRepositoryITests.java index ffa0d947..9ae752b6 100644 --- a/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/MariaDb10JdbcOperationsSessionRepositoryITests.java +++ b/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/MariaDb10JdbcOperationsSessionRepositoryITests.java @@ -35,8 +35,7 @@ import org.springframework.test.context.web.WebAppConfiguration; @ExtendWith(SpringExtension.class) @WebAppConfiguration @ContextConfiguration -public class MariaDb10JdbcOperationsSessionRepositoryITests - extends AbstractContainerJdbcOperationsSessionRepositoryITests { +class MariaDb10JdbcOperationsSessionRepositoryITests extends AbstractContainerJdbcOperationsSessionRepositoryITests { @Configuration static class Config extends BaseContainerConfig { diff --git a/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/MariaDb5JdbcOperationsSessionRepositoryITests.java b/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/MariaDb5JdbcOperationsSessionRepositoryITests.java index fd59b22c..e1dbe2a8 100644 --- a/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/MariaDb5JdbcOperationsSessionRepositoryITests.java +++ b/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/MariaDb5JdbcOperationsSessionRepositoryITests.java @@ -35,8 +35,7 @@ import org.springframework.test.context.web.WebAppConfiguration; @ExtendWith(SpringExtension.class) @WebAppConfiguration @ContextConfiguration -public class MariaDb5JdbcOperationsSessionRepositoryITests - extends AbstractContainerJdbcOperationsSessionRepositoryITests { +class MariaDb5JdbcOperationsSessionRepositoryITests extends AbstractContainerJdbcOperationsSessionRepositoryITests { @Configuration static class Config extends BaseContainerConfig { diff --git a/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/MySql5JdbcOperationsSessionRepositoryITests.java b/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/MySql5JdbcOperationsSessionRepositoryITests.java index 2a990660..439cbe6f 100644 --- a/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/MySql5JdbcOperationsSessionRepositoryITests.java +++ b/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/MySql5JdbcOperationsSessionRepositoryITests.java @@ -34,8 +34,7 @@ import org.springframework.test.context.web.WebAppConfiguration; @ExtendWith(SpringExtension.class) @WebAppConfiguration @ContextConfiguration -public class MySql5JdbcOperationsSessionRepositoryITests - extends AbstractContainerJdbcOperationsSessionRepositoryITests { +class MySql5JdbcOperationsSessionRepositoryITests extends AbstractContainerJdbcOperationsSessionRepositoryITests { @Configuration static class Config extends BaseContainerConfig { diff --git a/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/MySql8JdbcOperationsSessionRepositoryITests.java b/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/MySql8JdbcOperationsSessionRepositoryITests.java index 995fd20e..fe14e690 100644 --- a/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/MySql8JdbcOperationsSessionRepositoryITests.java +++ b/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/MySql8JdbcOperationsSessionRepositoryITests.java @@ -34,8 +34,7 @@ import org.springframework.test.context.web.WebAppConfiguration; @ExtendWith(SpringExtension.class) @WebAppConfiguration @ContextConfiguration -public class MySql8JdbcOperationsSessionRepositoryITests - extends AbstractContainerJdbcOperationsSessionRepositoryITests { +class MySql8JdbcOperationsSessionRepositoryITests extends AbstractContainerJdbcOperationsSessionRepositoryITests { @Configuration static class Config extends BaseContainerConfig { diff --git a/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/OracleJdbcOperationsSessionRepositoryITests.java b/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/OracleJdbcOperationsSessionRepositoryITests.java index 11e51b55..6db0119f 100644 --- a/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/OracleJdbcOperationsSessionRepositoryITests.java +++ b/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/OracleJdbcOperationsSessionRepositoryITests.java @@ -41,16 +41,14 @@ import org.springframework.util.ClassUtils; @ExtendWith(SpringExtension.class) @WebAppConfiguration @ContextConfiguration -public class OracleJdbcOperationsSessionRepositoryITests - extends AbstractContainerJdbcOperationsSessionRepositoryITests { +class OracleJdbcOperationsSessionRepositoryITests extends AbstractContainerJdbcOperationsSessionRepositoryITests { @BeforeAll - public static void setUpClass() { + static void setUpClass() { Assumptions.assumeTrue(ClassUtils.isPresent("oracle.jdbc.OracleDriver", null), "Oracle JDBC driver is present on the classpath"); Assumptions.assumeTrue( - TestcontainersConfiguration.getInstance().getProperties() - .getProperty("oracle.container.image") != null, + TestcontainersConfiguration.getInstance().getProperties().getProperty("oracle.container.image") != null, "Testcontainers property `oracle.container.image` is set"); } diff --git a/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/PostgreSql10JdbcOperationsSessionRepositoryITests.java b/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/PostgreSql10JdbcOperationsSessionRepositoryITests.java index ef3ae5ca..c57e6489 100644 --- a/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/PostgreSql10JdbcOperationsSessionRepositoryITests.java +++ b/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/PostgreSql10JdbcOperationsSessionRepositoryITests.java @@ -35,8 +35,7 @@ import org.springframework.test.context.web.WebAppConfiguration; @ExtendWith(SpringExtension.class) @WebAppConfiguration @ContextConfiguration -public class PostgreSql10JdbcOperationsSessionRepositoryITests - extends AbstractContainerJdbcOperationsSessionRepositoryITests { +class PostgreSql10JdbcOperationsSessionRepositoryITests extends AbstractContainerJdbcOperationsSessionRepositoryITests { @Configuration static class Config extends BaseContainerConfig { diff --git a/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/PostgreSql11JdbcOperationsSessionRepositoryITests.java b/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/PostgreSql11JdbcOperationsSessionRepositoryITests.java index e56573e9..f109cce4 100644 --- a/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/PostgreSql11JdbcOperationsSessionRepositoryITests.java +++ b/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/PostgreSql11JdbcOperationsSessionRepositoryITests.java @@ -35,8 +35,7 @@ import org.springframework.test.context.web.WebAppConfiguration; @ExtendWith(SpringExtension.class) @WebAppConfiguration @ContextConfiguration -public class PostgreSql11JdbcOperationsSessionRepositoryITests - extends AbstractContainerJdbcOperationsSessionRepositoryITests { +class PostgreSql11JdbcOperationsSessionRepositoryITests extends AbstractContainerJdbcOperationsSessionRepositoryITests { @Configuration static class Config extends BaseContainerConfig { diff --git a/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/PostgreSql9JdbcOperationsSessionRepositoryITests.java b/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/PostgreSql9JdbcOperationsSessionRepositoryITests.java index 15ecb86a..015d6573 100644 --- a/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/PostgreSql9JdbcOperationsSessionRepositoryITests.java +++ b/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/PostgreSql9JdbcOperationsSessionRepositoryITests.java @@ -35,8 +35,7 @@ import org.springframework.test.context.web.WebAppConfiguration; @ExtendWith(SpringExtension.class) @WebAppConfiguration @ContextConfiguration -public class PostgreSql9JdbcOperationsSessionRepositoryITests - extends AbstractContainerJdbcOperationsSessionRepositoryITests { +class PostgreSql9JdbcOperationsSessionRepositoryITests extends AbstractContainerJdbcOperationsSessionRepositoryITests { @Configuration static class Config extends BaseContainerConfig { diff --git a/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/SqlServerJdbcOperationsSessionRepositoryITests.java b/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/SqlServerJdbcOperationsSessionRepositoryITests.java index 01895813..fde69a3b 100644 --- a/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/SqlServerJdbcOperationsSessionRepositoryITests.java +++ b/spring-session-jdbc/src/integration-test/java/org/springframework/session/jdbc/SqlServerJdbcOperationsSessionRepositoryITests.java @@ -35,8 +35,7 @@ import org.springframework.test.context.web.WebAppConfiguration; @ExtendWith(SpringExtension.class) @WebAppConfiguration @ContextConfiguration -public class SqlServerJdbcOperationsSessionRepositoryITests - extends AbstractContainerJdbcOperationsSessionRepositoryITests { +class SqlServerJdbcOperationsSessionRepositoryITests extends AbstractContainerJdbcOperationsSessionRepositoryITests { @Configuration static class Config extends BaseContainerConfig { diff --git a/spring-session-jdbc/src/main/java/org/springframework/session/jdbc/JdbcOperationsSessionRepository.java b/spring-session-jdbc/src/main/java/org/springframework/session/jdbc/JdbcOperationsSessionRepository.java index e3196122..d6dcee3c 100644 --- a/spring-session-jdbc/src/main/java/org/springframework/session/jdbc/JdbcOperationsSessionRepository.java +++ b/spring-session-jdbc/src/main/java/org/springframework/session/jdbc/JdbcOperationsSessionRepository.java @@ -83,8 +83,8 @@ import org.springframework.util.StringUtils; * * * For additional information on how to create and configure {@link JdbcTemplate} and - * {@link PlatformTransactionManager}, refer to the - * + * {@link PlatformTransactionManager}, refer to the * Spring Framework Reference Documentation. *

    * By default, this implementation uses SPRING_SESSION and @@ -132,8 +132,8 @@ import org.springframework.util.StringUtils; * @author Craig Andrews * @since 1.2.0 */ -public class JdbcOperationsSessionRepository implements - FindByIndexNameSessionRepository { +public class JdbcOperationsSessionRepository + implements FindByIndexNameSessionRepository { /** * The default name of database table used by Spring Session to store sessions. @@ -142,52 +142,60 @@ public class JdbcOperationsSessionRepository implements private static final String SPRING_SECURITY_CONTEXT = "SPRING_SECURITY_CONTEXT"; - private static final String CREATE_SESSION_QUERY = - "INSERT INTO %TABLE_NAME%(PRIMARY_ID, SESSION_ID, CREATION_TIME, LAST_ACCESS_TIME, MAX_INACTIVE_INTERVAL, EXPIRY_TIME, PRINCIPAL_NAME) " + - "VALUES (?, ?, ?, ?, ?, ?, ?)"; + // @formatter:off + private static final String CREATE_SESSION_QUERY = "INSERT INTO %TABLE_NAME%(PRIMARY_ID, SESSION_ID, CREATION_TIME, LAST_ACCESS_TIME, MAX_INACTIVE_INTERVAL, EXPIRY_TIME, PRINCIPAL_NAME) " + + "VALUES (?, ?, ?, ?, ?, ?, ?)"; + // @formatter:on - private static final String CREATE_SESSION_ATTRIBUTE_QUERY = - "INSERT INTO %TABLE_NAME%_ATTRIBUTES(SESSION_PRIMARY_ID, ATTRIBUTE_NAME, ATTRIBUTE_BYTES) " + - "SELECT PRIMARY_ID, ?, ? " + - "FROM %TABLE_NAME% " + - "WHERE SESSION_ID = ?"; + // @formatter:off + private static final String CREATE_SESSION_ATTRIBUTE_QUERY = "INSERT INTO %TABLE_NAME%_ATTRIBUTES(SESSION_PRIMARY_ID, ATTRIBUTE_NAME, ATTRIBUTE_BYTES) " + + "SELECT PRIMARY_ID, ?, ? " + + "FROM %TABLE_NAME% " + + "WHERE SESSION_ID = ?"; + // @formatter:on - private static final String GET_SESSION_QUERY = - "SELECT S.PRIMARY_ID, S.SESSION_ID, S.CREATION_TIME, S.LAST_ACCESS_TIME, S.MAX_INACTIVE_INTERVAL, SA.ATTRIBUTE_NAME, SA.ATTRIBUTE_BYTES " + - "FROM %TABLE_NAME% S " + - "LEFT OUTER JOIN %TABLE_NAME%_ATTRIBUTES SA ON S.PRIMARY_ID = SA.SESSION_PRIMARY_ID " + - "WHERE S.SESSION_ID = ?"; + // @formatter:off + private static final String GET_SESSION_QUERY = "SELECT S.PRIMARY_ID, S.SESSION_ID, S.CREATION_TIME, S.LAST_ACCESS_TIME, S.MAX_INACTIVE_INTERVAL, SA.ATTRIBUTE_NAME, SA.ATTRIBUTE_BYTES " + + "FROM %TABLE_NAME% S " + + "LEFT OUTER JOIN %TABLE_NAME%_ATTRIBUTES SA ON S.PRIMARY_ID = SA.SESSION_PRIMARY_ID " + + "WHERE S.SESSION_ID = ?"; + // @formatter:on - private static final String UPDATE_SESSION_QUERY = - "UPDATE %TABLE_NAME% SET SESSION_ID = ?, LAST_ACCESS_TIME = ?, MAX_INACTIVE_INTERVAL = ?, EXPIRY_TIME = ?, PRINCIPAL_NAME = ? " + - "WHERE PRIMARY_ID = ?"; + // @formatter:off + private static final String UPDATE_SESSION_QUERY = "UPDATE %TABLE_NAME% SET SESSION_ID = ?, LAST_ACCESS_TIME = ?, MAX_INACTIVE_INTERVAL = ?, EXPIRY_TIME = ?, PRINCIPAL_NAME = ? " + + "WHERE PRIMARY_ID = ?"; + // @formatter:on - private static final String UPDATE_SESSION_ATTRIBUTE_QUERY = - "UPDATE %TABLE_NAME%_ATTRIBUTES SET ATTRIBUTE_BYTES = ? " + - "WHERE SESSION_PRIMARY_ID = ? " + - "AND ATTRIBUTE_NAME = ?"; + // @formatter:off + private static final String UPDATE_SESSION_ATTRIBUTE_QUERY = "UPDATE %TABLE_NAME%_ATTRIBUTES SET ATTRIBUTE_BYTES = ? " + + "WHERE SESSION_PRIMARY_ID = ? " + + "AND ATTRIBUTE_NAME = ?"; + // @formatter:on - private static final String DELETE_SESSION_ATTRIBUTE_QUERY = - "DELETE FROM %TABLE_NAME%_ATTRIBUTES " + - "WHERE SESSION_PRIMARY_ID = ? " + - "AND ATTRIBUTE_NAME = ?"; + // @formatter:off + private static final String DELETE_SESSION_ATTRIBUTE_QUERY = "DELETE FROM %TABLE_NAME%_ATTRIBUTES " + + "WHERE SESSION_PRIMARY_ID = ? " + + "AND ATTRIBUTE_NAME = ?"; + // @formatter:on - private static final String DELETE_SESSION_QUERY = - "DELETE FROM %TABLE_NAME% " + - "WHERE SESSION_ID = ?"; + // @formatter:off + private static final String DELETE_SESSION_QUERY = "DELETE FROM %TABLE_NAME% " + + "WHERE SESSION_ID = ?"; + // @formatter:on - private static final String LIST_SESSIONS_BY_PRINCIPAL_NAME_QUERY = - "SELECT S.PRIMARY_ID, S.SESSION_ID, S.CREATION_TIME, S.LAST_ACCESS_TIME, S.MAX_INACTIVE_INTERVAL, SA.ATTRIBUTE_NAME, SA.ATTRIBUTE_BYTES " + - "FROM %TABLE_NAME% S " + - "LEFT OUTER JOIN %TABLE_NAME%_ATTRIBUTES SA ON S.PRIMARY_ID = SA.SESSION_PRIMARY_ID " + - "WHERE S.PRINCIPAL_NAME = ?"; + // @formatter:off + private static final String LIST_SESSIONS_BY_PRINCIPAL_NAME_QUERY = "SELECT S.PRIMARY_ID, S.SESSION_ID, S.CREATION_TIME, S.LAST_ACCESS_TIME, S.MAX_INACTIVE_INTERVAL, SA.ATTRIBUTE_NAME, SA.ATTRIBUTE_BYTES " + + "FROM %TABLE_NAME% S " + + "LEFT OUTER JOIN %TABLE_NAME%_ATTRIBUTES SA ON S.PRIMARY_ID = SA.SESSION_PRIMARY_ID " + + "WHERE S.PRINCIPAL_NAME = ?"; + // @formatter:on - private static final String DELETE_SESSIONS_BY_EXPIRY_TIME_QUERY = - "DELETE FROM %TABLE_NAME% " + - "WHERE EXPIRY_TIME < ?"; + // @formatter:off + private static final String DELETE_SESSIONS_BY_EXPIRY_TIME_QUERY = "DELETE FROM %TABLE_NAME% " + + "WHERE EXPIRY_TIME < ?"; + // @formatter:on - private static final Log logger = LogFactory - .getLog(JdbcOperationsSessionRepository.class); + private static final Log logger = LogFactory.getLog(JdbcOperationsSessionRepository.class); private static final PrincipalNameResolver PRINCIPAL_NAME_RESOLVER = new PrincipalNameResolver(); @@ -398,9 +406,8 @@ public class JdbcOperationsSessionRepository implements @Override protected void doInTransactionWithoutResult(TransactionStatus status) { - JdbcOperationsSessionRepository.this.jdbcOperations.update( - JdbcOperationsSessionRepository.this.createSessionQuery, - (ps) -> { + JdbcOperationsSessionRepository.this.jdbcOperations + .update(JdbcOperationsSessionRepository.this.createSessionQuery, (ps) -> { ps.setString(1, session.primaryKey); ps.setString(2, session.getId()); ps.setLong(3, session.getCreationTime().toEpochMilli()); @@ -423,9 +430,8 @@ public class JdbcOperationsSessionRepository implements @Override protected void doInTransactionWithoutResult(TransactionStatus status) { if (session.isChanged()) { - JdbcOperationsSessionRepository.this.jdbcOperations.update( - JdbcOperationsSessionRepository.this.updateSessionQuery, - (ps) -> { + JdbcOperationsSessionRepository.this.jdbcOperations + .update(JdbcOperationsSessionRepository.this.updateSessionQuery, (ps) -> { ps.setString(1, session.getId()); ps.setLong(2, session.getLastAccessedTime().toEpochMilli()); ps.setInt(3, (int) session.getMaxInactiveInterval().getSeconds()); @@ -435,22 +441,19 @@ public class JdbcOperationsSessionRepository implements }); } List addedAttributeNames = session.delta.entrySet().stream() - .filter((entry) -> entry.getValue() == DeltaValue.ADDED) - .map(Map.Entry::getKey) + .filter((entry) -> entry.getValue() == DeltaValue.ADDED).map(Map.Entry::getKey) .collect(Collectors.toList()); if (!addedAttributeNames.isEmpty()) { insertSessionAttributes(session, addedAttributeNames); } List updatedAttributeNames = session.delta.entrySet().stream() - .filter((entry) -> entry.getValue() == DeltaValue.UPDATED) - .map(Map.Entry::getKey) + .filter((entry) -> entry.getValue() == DeltaValue.UPDATED).map(Map.Entry::getKey) .collect(Collectors.toList()); if (!updatedAttributeNames.isEmpty()) { updateSessionAttributes(session, updatedAttributeNames); } List removedAttributeNames = session.delta.entrySet().stream() - .filter((entry) -> entry.getValue() == DeltaValue.REMOVED) - .map(Map.Entry::getKey) + .filter((entry) -> entry.getValue() == DeltaValue.REMOVED).map(Map.Entry::getKey) .collect(Collectors.toList()); if (!removedAttributeNames.isEmpty()) { deleteSessionAttributes(session, removedAttributeNames); @@ -466,10 +469,8 @@ public class JdbcOperationsSessionRepository implements public JdbcSession findById(final String id) { final JdbcSession session = this.transactionOperations.execute((status) -> { List sessions = JdbcOperationsSessionRepository.this.jdbcOperations.query( - JdbcOperationsSessionRepository.this.getSessionQuery, - (ps) -> ps.setString(1, id), - JdbcOperationsSessionRepository.this.extractor - ); + JdbcOperationsSessionRepository.this.getSessionQuery, (ps) -> ps.setString(1, id), + JdbcOperationsSessionRepository.this.extractor); if (sessions.isEmpty()) { return null; } @@ -493,28 +494,25 @@ public class JdbcOperationsSessionRepository implements @Override protected void doInTransactionWithoutResult(TransactionStatus status) { - JdbcOperationsSessionRepository.this.jdbcOperations.update( - JdbcOperationsSessionRepository.this.deleteSessionQuery, id); + JdbcOperationsSessionRepository.this.jdbcOperations + .update(JdbcOperationsSessionRepository.this.deleteSessionQuery, id); } }); } @Override - public Map findByIndexNameAndIndexValue(String indexName, - final String indexValue) { + public Map findByIndexNameAndIndexValue(String indexName, final String indexValue) { if (!PRINCIPAL_NAME_INDEX_NAME.equals(indexName)) { return Collections.emptyMap(); } - List sessions = this.transactionOperations.execute((status) -> - JdbcOperationsSessionRepository.this.jdbcOperations.query( + List sessions = this.transactionOperations + .execute((status) -> JdbcOperationsSessionRepository.this.jdbcOperations.query( JdbcOperationsSessionRepository.this.listSessionsByPrincipalNameQuery, - (ps) -> ps.setString(1, indexValue), - JdbcOperationsSessionRepository.this.extractor)); + (ps) -> ps.setString(1, indexValue), JdbcOperationsSessionRepository.this.extractor)); - Map sessionMap = new HashMap<>( - sessions.size()); + Map sessionMap = new HashMap<>(sessions.size()); for (JdbcSession session : sessions) { sessionMap.put(session.getId(), session); @@ -528,19 +526,19 @@ public class JdbcOperationsSessionRepository implements if (attributeNames.size() > 1) { this.jdbcOperations.batchUpdate(this.createSessionAttributeQuery, new BatchPreparedStatementSetter() { - @Override - public void setValues(PreparedStatement ps, int i) throws SQLException { - String attributeName = attributeNames.get(i); - ps.setString(1, attributeName); - getLobHandler().getLobCreator().setBlobAsBytes(ps, 2, - serialize(session.getAttribute(attributeName))); - ps.setString(3, session.getId()); - } + @Override + public void setValues(PreparedStatement ps, int i) throws SQLException { + String attributeName = attributeNames.get(i); + ps.setString(1, attributeName); + getLobHandler().getLobCreator().setBlobAsBytes(ps, 2, + serialize(session.getAttribute(attributeName))); + ps.setString(3, session.getId()); + } - @Override - public int getBatchSize() { - return attributeNames.size(); - } + @Override + public int getBatchSize() { + return attributeNames.size(); + } }); } @@ -548,8 +546,7 @@ public class JdbcOperationsSessionRepository implements this.jdbcOperations.update(this.createSessionAttributeQuery, (ps) -> { String attributeName = attributeNames.get(0); ps.setString(1, attributeName); - getLobHandler().getLobCreator().setBlobAsBytes(ps, 2, - serialize(session.getAttribute(attributeName))); + getLobHandler().getLobCreator().setBlobAsBytes(ps, 2, serialize(session.getAttribute(attributeName))); ps.setString(3, session.getId()); }); } @@ -560,27 +557,26 @@ public class JdbcOperationsSessionRepository implements if (attributeNames.size() > 1) { this.jdbcOperations.batchUpdate(this.updateSessionAttributeQuery, new BatchPreparedStatementSetter() { - @Override - public void setValues(PreparedStatement ps, int i) throws SQLException { - String attributeName = attributeNames.get(i); - getLobHandler().getLobCreator().setBlobAsBytes(ps, 1, - serialize(session.getAttribute(attributeName))); - ps.setString(2, session.primaryKey); - ps.setString(3, attributeName); - } + @Override + public void setValues(PreparedStatement ps, int i) throws SQLException { + String attributeName = attributeNames.get(i); + getLobHandler().getLobCreator().setBlobAsBytes(ps, 1, + serialize(session.getAttribute(attributeName))); + ps.setString(2, session.primaryKey); + ps.setString(3, attributeName); + } - @Override - public int getBatchSize() { - return attributeNames.size(); - } + @Override + public int getBatchSize() { + return attributeNames.size(); + } }); } else { this.jdbcOperations.update(this.updateSessionAttributeQuery, (ps) -> { String attributeName = attributeNames.get(0); - getLobHandler().getLobCreator().setBlobAsBytes(ps, 1, - serialize(session.getAttribute(attributeName))); + getLobHandler().getLobCreator().setBlobAsBytes(ps, 1, serialize(session.getAttribute(attributeName))); ps.setString(2, session.primaryKey); ps.setString(3, attributeName); }); @@ -592,17 +588,17 @@ public class JdbcOperationsSessionRepository implements if (attributeNames.size() > 1) { this.jdbcOperations.batchUpdate(this.deleteSessionAttributeQuery, new BatchPreparedStatementSetter() { - @Override - public void setValues(PreparedStatement ps, int i) throws SQLException { - String attributeName = attributeNames.get(i); - ps.setString(1, session.primaryKey); - ps.setString(2, attributeName); - } + @Override + public void setValues(PreparedStatement ps, int i) throws SQLException { + String attributeName = attributeNames.get(i); + ps.setString(1, session.primaryKey); + ps.setString(2, attributeName); + } - @Override - public int getBatchSize() { - return attributeNames.size(); - } + @Override + public int getBatchSize() { + return attributeNames.size(); + } }); } @@ -616,8 +612,8 @@ public class JdbcOperationsSessionRepository implements } public void cleanUpExpiredSessions() { - Integer deletedCount = this.transactionOperations.execute((status) -> - JdbcOperationsSessionRepository.this.jdbcOperations.update( + Integer deletedCount = this.transactionOperations + .execute((status) -> JdbcOperationsSessionRepository.this.jdbcOperations.update( JdbcOperationsSessionRepository.this.deleteSessionsByExpiryTimeQuery, System.currentTimeMillis())); @@ -626,22 +622,17 @@ public class JdbcOperationsSessionRepository implements } } - private static TransactionTemplate createTransactionTemplate( - PlatformTransactionManager transactionManager) { - TransactionTemplate transactionTemplate = new TransactionTemplate( - transactionManager); - transactionTemplate.setPropagationBehavior( - TransactionDefinition.PROPAGATION_REQUIRES_NEW); + private static TransactionTemplate createTransactionTemplate(PlatformTransactionManager transactionManager) { + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); transactionTemplate.afterPropertiesSet(); return transactionTemplate; } private static GenericConversionService createDefaultConversionService() { GenericConversionService converter = new GenericConversionService(); - converter.addConverter(Object.class, byte[].class, - new SerializingConverter()); - converter.addConverter(byte[].class, Object.class, - new DeserializingConverter()); + converter.addConverter(Object.class, byte[].class, new SerializingConverter()); + converter.addConverter(byte[].class, Object.class, new DeserializingConverter()); return converter; } @@ -657,10 +648,8 @@ public class JdbcOperationsSessionRepository implements this.updateSessionAttributeQuery = getQuery(UPDATE_SESSION_ATTRIBUTE_QUERY); this.deleteSessionAttributeQuery = getQuery(DELETE_SESSION_ATTRIBUTE_QUERY); this.deleteSessionQuery = getQuery(DELETE_SESSION_QUERY); - this.listSessionsByPrincipalNameQuery = - getQuery(LIST_SESSIONS_BY_PRINCIPAL_NAME_QUERY); - this.deleteSessionsByExpiryTimeQuery = - getQuery(DELETE_SESSIONS_BY_EXPIRY_TIME_QUERY); + this.listSessionsByPrincipalNameQuery = getQuery(LIST_SESSIONS_BY_PRINCIPAL_NAME_QUERY); + this.deleteSessionsByExpiryTimeQuery = getQuery(DELETE_SESSIONS_BY_EXPIRY_TIME_QUERY); } private LobHandler getLobHandler() { @@ -668,8 +657,7 @@ public class JdbcOperationsSessionRepository implements } private byte[] serialize(Object object) { - return (byte[]) this.conversionService.convert(object, - TypeDescriptor.valueOf(Object.class), + return (byte[]) this.conversionService.convert(object, TypeDescriptor.valueOf(Object.class), TypeDescriptor.valueOf(byte[].class)); } @@ -793,27 +781,20 @@ public class JdbcOperationsSessionRepository implements } if (attributeExists) { if (attributeRemoved) { - this.delta.merge(attributeName, DeltaValue.REMOVED, (oldDeltaValue, - deltaValue) -> (oldDeltaValue == DeltaValue.ADDED) ? null - : deltaValue); + this.delta.merge(attributeName, DeltaValue.REMOVED, + (oldDeltaValue, deltaValue) -> (oldDeltaValue == DeltaValue.ADDED) ? null : deltaValue); } else { - this.delta.merge(attributeName, DeltaValue.UPDATED, - (oldDeltaValue, - deltaValue) -> (oldDeltaValue == DeltaValue.ADDED) - ? oldDeltaValue - : deltaValue); + this.delta.merge(attributeName, DeltaValue.UPDATED, (oldDeltaValue, + deltaValue) -> (oldDeltaValue == DeltaValue.ADDED) ? oldDeltaValue : deltaValue); } } else { - this.delta.merge(attributeName, DeltaValue.ADDED, - (oldDeltaValue, deltaValue) -> (oldDeltaValue == DeltaValue.ADDED) - ? oldDeltaValue - : DeltaValue.UPDATED); + this.delta.merge(attributeName, DeltaValue.ADDED, (oldDeltaValue, + deltaValue) -> (oldDeltaValue == DeltaValue.ADDED) ? oldDeltaValue : DeltaValue.UPDATED); } this.delegate.setAttribute(attributeName, value(attributeValue)); - if (PRINCIPAL_NAME_INDEX_NAME.equals(attributeName) || - SPRING_SECURITY_CONTEXT.equals(attributeName)) { + if (PRINCIPAL_NAME_INDEX_NAME.equals(attributeName) || SPRING_SECURITY_CONTEXT.equals(attributeName)) { this.changed = true; } } @@ -873,8 +854,7 @@ public class JdbcOperationsSessionRepository implements } Object authentication = session.getAttribute(SPRING_SECURITY_CONTEXT); if (authentication != null) { - Expression expression = this.parser - .parseExpression("authentication?.name"); + Expression expression = this.parser.parseExpression("authentication?.name"); return expression.getValue(authentication, String.class); } return null; @@ -904,8 +884,7 @@ public class JdbcOperationsSessionRepository implements String attributeName = rs.getString("ATTRIBUTE_NAME"); if (attributeName != null) { byte[] bytes = getLobHandler().getBlobAsBytes(rs, "ATTRIBUTE_BYTES"); - session.delegate.setAttribute(attributeName, - lazily(() -> deserialize(bytes))); + session.delegate.setAttribute(attributeName, lazily(() -> deserialize(bytes))); } sessions.add(session); } diff --git a/spring-session-jdbc/src/main/java/org/springframework/session/jdbc/config/annotation/SpringSessionDataSource.java b/spring-session-jdbc/src/main/java/org/springframework/session/jdbc/config/annotation/SpringSessionDataSource.java index 02ab9d96..e2969e47 100644 --- a/spring-session-jdbc/src/main/java/org/springframework/session/jdbc/config/annotation/SpringSessionDataSource.java +++ b/spring-session-jdbc/src/main/java/org/springframework/session/jdbc/config/annotation/SpringSessionDataSource.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,8 +34,7 @@ import org.springframework.session.jdbc.JdbcOperationsSessionRepository; * @author Vedran Pavic * @since 2.0.0 */ -@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, - ElementType.ANNOTATION_TYPE }) +@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented @Qualifier diff --git a/spring-session-jdbc/src/main/java/org/springframework/session/jdbc/config/annotation/web/http/JdbcHttpSessionConfiguration.java b/spring-session-jdbc/src/main/java/org/springframework/session/jdbc/config/annotation/web/http/JdbcHttpSessionConfiguration.java index 6dd891f0..a4ee8f7b 100644 --- a/spring-session-jdbc/src/main/java/org/springframework/session/jdbc/config/annotation/web/http/JdbcHttpSessionConfiguration.java +++ b/spring-session-jdbc/src/main/java/org/springframework/session/jdbc/config/annotation/web/http/JdbcHttpSessionConfiguration.java @@ -67,8 +67,7 @@ import org.springframework.util.StringValueResolver; @Configuration(proxyBeanMethods = false) @EnableScheduling public class JdbcHttpSessionConfiguration extends SpringHttpSessionConfiguration - implements BeanClassLoaderAware, EmbeddedValueResolverAware, ImportAware, - SchedulingConfigurer { + implements BeanClassLoaderAware, EmbeddedValueResolverAware, ImportAware, SchedulingConfigurer { static final String DEFAULT_CLEANUP_CRON = "0 * * * * *"; @@ -95,13 +94,12 @@ public class JdbcHttpSessionConfiguration extends SpringHttpSessionConfiguration @Bean public JdbcOperationsSessionRepository sessionRepository() { JdbcTemplate jdbcTemplate = createJdbcTemplate(this.dataSource); - JdbcOperationsSessionRepository sessionRepository = new JdbcOperationsSessionRepository( - jdbcTemplate, this.transactionManager); + JdbcOperationsSessionRepository sessionRepository = new JdbcOperationsSessionRepository(jdbcTemplate, + this.transactionManager); if (StringUtils.hasText(this.tableName)) { sessionRepository.setTableName(this.tableName); } - sessionRepository - .setDefaultMaxInactiveInterval(this.maxInactiveIntervalInSeconds); + sessionRepository.setDefaultMaxInactiveInterval(this.maxInactiveIntervalInSeconds); if (this.lobHandler != null) { sessionRepository.setLobHandler(this.lobHandler); } @@ -117,16 +115,14 @@ public class JdbcHttpSessionConfiguration extends SpringHttpSessionConfiguration sessionRepository.setConversionService(this.conversionService); } else { - sessionRepository - .setConversionService(createConversionServiceWithBeanClassLoader()); + sessionRepository.setConversionService(createConversionServiceWithBeanClassLoader()); } return sessionRepository; } private static boolean requiresTemporaryLob(DataSource dataSource) { try { - String productName = JdbcUtils.extractDatabaseMetaData(dataSource, - "getDatabaseProductName"); + String productName = JdbcUtils.extractDatabaseMetaData(dataSource, "getDatabaseProductName"); return "Oracle".equalsIgnoreCase(JdbcUtils.commonDatabaseName(productName)); } catch (MetaDataAccessException ex) { @@ -147,8 +143,7 @@ public class JdbcHttpSessionConfiguration extends SpringHttpSessionConfiguration } @Autowired - public void setDataSource( - @SpringSessionDataSource ObjectProvider springSessionDataSource, + public void setDataSource(@SpringSessionDataSource ObjectProvider springSessionDataSource, ObjectProvider dataSource) { DataSource dataSourceToUse = springSessionDataSource.getIfAvailable(); if (dataSourceToUse == null) { @@ -195,12 +190,10 @@ public class JdbcHttpSessionConfiguration extends SpringHttpSessionConfiguration Map attributeMap = importMetadata .getAnnotationAttributes(EnableJdbcHttpSession.class.getName()); AnnotationAttributes attributes = AnnotationAttributes.fromMap(attributeMap); - this.maxInactiveIntervalInSeconds = attributes - .getNumber("maxInactiveIntervalInSeconds"); + this.maxInactiveIntervalInSeconds = attributes.getNumber("maxInactiveIntervalInSeconds"); String tableNameValue = attributes.getString("tableName"); if (StringUtils.hasText(tableNameValue)) { - this.tableName = this.embeddedValueResolver - .resolveStringValue(tableNameValue); + this.tableName = this.embeddedValueResolver.resolveStringValue(tableNameValue); } String cleanupCron = attributes.getString("cleanupCron"); if (StringUtils.hasText(cleanupCron)) { @@ -210,8 +203,7 @@ public class JdbcHttpSessionConfiguration extends SpringHttpSessionConfiguration @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { - taskRegistrar.addCronTask(() -> sessionRepository().cleanUpExpiredSessions(), - this.cleanupCron); + taskRegistrar.addCronTask(() -> sessionRepository().cleanUpExpiredSessions(), this.cleanupCron); } private static JdbcTemplate createJdbcTemplate(DataSource dataSource) { @@ -222,10 +214,8 @@ public class JdbcHttpSessionConfiguration extends SpringHttpSessionConfiguration private GenericConversionService createConversionServiceWithBeanClassLoader() { GenericConversionService conversionService = new GenericConversionService(); - conversionService.addConverter(Object.class, byte[].class, - new SerializingConverter()); - conversionService.addConverter(byte[].class, Object.class, - new DeserializingConverter(this.classLoader)); + conversionService.addConverter(Object.class, byte[].class, new SerializingConverter()); + conversionService.addConverter(byte[].class, Object.class, new DeserializingConverter(this.classLoader)); return conversionService; } diff --git a/spring-session-jdbc/src/test/java/org/springframework/session/jdbc/JdbcOperationsSessionRepositoryTests.java b/spring-session-jdbc/src/test/java/org/springframework/session/jdbc/JdbcOperationsSessionRepositoryTests.java index 90ba7295..4ff240af 100644 --- a/spring-session-jdbc/src/test/java/org/springframework/session/jdbc/JdbcOperationsSessionRepositoryTests.java +++ b/spring-session-jdbc/src/test/java/org/springframework/session/jdbc/JdbcOperationsSessionRepositoryTests.java @@ -63,256 +63,219 @@ import static org.mockito.Mockito.verifyZeroInteractions; * @author Craig Andrews * @since 1.2.0 */ -public class JdbcOperationsSessionRepositoryTests { +class JdbcOperationsSessionRepositoryTests { private static final String SPRING_SECURITY_CONTEXT = "SPRING_SECURITY_CONTEXT"; private JdbcOperations jdbcOperations = mock(JdbcOperations.class); - private PlatformTransactionManager transactionManager = mock( - PlatformTransactionManager.class); + private PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); private JdbcOperationsSessionRepository repository; @BeforeEach - public void setUp() { - this.repository = new JdbcOperationsSessionRepository(this.jdbcOperations, - this.transactionManager); + void setUp() { + this.repository = new JdbcOperationsSessionRepository(this.jdbcOperations, this.transactionManager); } @Test - public void constructorNullJdbcOperations() { - assertThatIllegalArgumentException().isThrownBy( - () -> new JdbcOperationsSessionRepository(null, this.transactionManager)) + void constructorNullJdbcOperations() { + assertThatIllegalArgumentException() + .isThrownBy(() -> new JdbcOperationsSessionRepository(null, this.transactionManager)) .withMessage("JdbcOperations must not be null"); } @Test - public void constructorNullTransactionManager() { - assertThatIllegalArgumentException().isThrownBy( - () -> new JdbcOperationsSessionRepository(this.jdbcOperations, null)) + void constructorNullTransactionManager() { + assertThatIllegalArgumentException() + .isThrownBy(() -> new JdbcOperationsSessionRepository(this.jdbcOperations, null)) .withMessage("TransactionManager must not be null"); } @Test - public void setTableNameNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.repository.setTableName(null)) + void setTableNameNull() { + assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setTableName(null)) .withMessage("Table name must not be empty"); } @Test - public void setTableNameEmpty() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.repository.setTableName(" ")) + void setTableNameEmpty() { + assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setTableName(" ")) .withMessage("Table name must not be empty"); } @Test - public void setCreateSessionQueryNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.repository.setCreateSessionQuery(null)) + void setCreateSessionQueryNull() { + assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setCreateSessionQuery(null)) .withMessage("Query must not be empty"); } @Test - public void setCreateSessionQueryEmpty() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.repository.setCreateSessionQuery(" ")) + void setCreateSessionQueryEmpty() { + assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setCreateSessionQuery(" ")) .withMessage("Query must not be empty"); } @Test - public void setCreateSessionAttributeQueryNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.repository.setCreateSessionAttributeQuery(null)) + void setCreateSessionAttributeQueryNull() { + assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setCreateSessionAttributeQuery(null)) .withMessage("Query must not be empty"); } @Test - public void setCreateSessionAttributeQueryEmpty() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.repository.setCreateSessionAttributeQuery(" ")) + void setCreateSessionAttributeQueryEmpty() { + assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setCreateSessionAttributeQuery(" ")) .withMessage("Query must not be empty"); } @Test - public void setGetSessionQueryNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.repository.setGetSessionQuery(null)) + void setGetSessionQueryNull() { + assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setGetSessionQuery(null)) .withMessage("Query must not be empty"); } @Test - public void setGetSessionQueryEmpty() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.repository.setGetSessionQuery(" ")) + void setGetSessionQueryEmpty() { + assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setGetSessionQuery(" ")) .withMessage("Query must not be empty"); } @Test - public void setUpdateSessionQueryNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.repository.setUpdateSessionQuery(null)) + void setUpdateSessionQueryNull() { + assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setUpdateSessionQuery(null)) .withMessage("Query must not be empty"); } @Test - public void setUpdateSessionQueryEmpty() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.repository.setUpdateSessionQuery(" ")) + void setUpdateSessionQueryEmpty() { + assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setUpdateSessionQuery(" ")) .withMessage("Query must not be empty"); } @Test - public void setUpdateSessionAttributeQueryNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.repository.setUpdateSessionAttributeQuery(null)) + void setUpdateSessionAttributeQueryNull() { + assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setUpdateSessionAttributeQuery(null)) .withMessage("Query must not be empty"); } @Test - public void setUpdateSessionAttributeQueryEmpty() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.repository.setUpdateSessionAttributeQuery(" ")) + void setUpdateSessionAttributeQueryEmpty() { + assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setUpdateSessionAttributeQuery(" ")) .withMessage("Query must not be empty"); } @Test - public void setDeleteSessionAttributeQueryNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.repository.setDeleteSessionAttributeQuery(null)) + void setDeleteSessionAttributeQueryNull() { + assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setDeleteSessionAttributeQuery(null)) .withMessage("Query must not be empty"); } @Test - public void setDeleteSessionAttributeQueryEmpty() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.repository.setDeleteSessionAttributeQuery(" ")) + void setDeleteSessionAttributeQueryEmpty() { + assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setDeleteSessionAttributeQuery(" ")) .withMessage("Query must not be empty"); } @Test - public void setDeleteSessionQueryNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.repository.setDeleteSessionQuery(null)) + void setDeleteSessionQueryNull() { + assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setDeleteSessionQuery(null)) .withMessage("Query must not be empty"); } @Test - public void setDeleteSessionQueryEmpty() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.repository.setDeleteSessionQuery(" ")) + void setDeleteSessionQueryEmpty() { + assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setDeleteSessionQuery(" ")) .withMessage("Query must not be empty"); } @Test - public void setListSessionsByPrincipalNameQueryNull() { - assertThatIllegalArgumentException() - .isThrownBy( - () -> this.repository.setListSessionsByPrincipalNameQuery(null)) + void setListSessionsByPrincipalNameQueryNull() { + assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setListSessionsByPrincipalNameQuery(null)) .withMessage("Query must not be empty"); } @Test - public void setListSessionsByPrincipalNameQueryEmpty() { - assertThatIllegalArgumentException() - .isThrownBy( - () -> this.repository.setListSessionsByPrincipalNameQuery(" ")) + void setListSessionsByPrincipalNameQueryEmpty() { + assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setListSessionsByPrincipalNameQuery(" ")) .withMessage("Query must not be empty"); } @Test - public void setDeleteSessionsByLastAccessTimeQueryNull() { - assertThatIllegalArgumentException() - .isThrownBy( - () -> this.repository.setDeleteSessionsByExpiryTimeQuery(null)) + void setDeleteSessionsByLastAccessTimeQueryNull() { + assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setDeleteSessionsByExpiryTimeQuery(null)) .withMessage("Query must not be empty"); } @Test - public void setDeleteSessionsByLastAccessTimeQueryEmpty() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.repository.setDeleteSessionsByExpiryTimeQuery(" ")) + void setDeleteSessionsByLastAccessTimeQueryEmpty() { + assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setDeleteSessionsByExpiryTimeQuery(" ")) .withMessage("Query must not be empty"); } @Test - public void setLobHandlerNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.repository.setLobHandler(null)) + void setLobHandlerNull() { + assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setLobHandler(null)) .withMessage("LobHandler must not be null"); } @Test - public void setConversionServiceNull() { - assertThatIllegalArgumentException() - .isThrownBy(() -> this.repository.setConversionService(null)) + void setConversionServiceNull() { + assertThatIllegalArgumentException().isThrownBy(() -> this.repository.setConversionService(null)) .withMessage("conversionService must not be null"); } @Test - public void createSessionDefaultMaxInactiveInterval() { - JdbcOperationsSessionRepository.JdbcSession session = this.repository - .createSession(); + void createSessionDefaultMaxInactiveInterval() { + JdbcOperationsSessionRepository.JdbcSession session = this.repository.createSession(); assertThat(session.isNew()).isTrue(); - assertThat(session.getMaxInactiveInterval()) - .isEqualTo(new MapSession().getMaxInactiveInterval()); + assertThat(session.getMaxInactiveInterval()).isEqualTo(new MapSession().getMaxInactiveInterval()); verifyZeroInteractions(this.jdbcOperations); } @Test - public void createSessionCustomMaxInactiveInterval() { + void createSessionCustomMaxInactiveInterval() { int interval = 1; this.repository.setDefaultMaxInactiveInterval(interval); - JdbcOperationsSessionRepository.JdbcSession session = this.repository - .createSession(); + JdbcOperationsSessionRepository.JdbcSession session = this.repository.createSession(); assertThat(session.isNew()).isTrue(); - assertThat(session.getMaxInactiveInterval()) - .isEqualTo(Duration.ofSeconds(interval)); + assertThat(session.getMaxInactiveInterval()).isEqualTo(Duration.ofSeconds(interval)); verifyZeroInteractions(this.jdbcOperations); } @Test - public void saveNewWithoutAttributes() { - JdbcOperationsSessionRepository.JdbcSession session = this.repository - .createSession(); + void saveNewWithoutAttributes() { + JdbcOperationsSessionRepository.JdbcSession session = this.repository.createSession(); this.repository.save(session); assertThat(session.isNew()).isFalse(); assertPropagationRequiresNew(); - verify(this.jdbcOperations, times(1)).update(startsWith("INSERT"), - isA(PreparedStatementSetter.class)); + verify(this.jdbcOperations, times(1)).update(startsWith("INSERT"), isA(PreparedStatementSetter.class)); verifyZeroInteractions(this.jdbcOperations); } @Test - public void saveNewWithSingleAttribute() { - JdbcOperationsSessionRepository.JdbcSession session = this.repository - .createSession(); + void saveNewWithSingleAttribute() { + JdbcOperationsSessionRepository.JdbcSession session = this.repository.createSession(); session.setAttribute("testName", "testValue"); this.repository.save(session); assertThat(session.isNew()).isFalse(); assertPropagationRequiresNew(); - verify(this.jdbcOperations, times(1)).update( - startsWith("INSERT INTO SPRING_SESSION("), + verify(this.jdbcOperations, times(1)).update(startsWith("INSERT INTO SPRING_SESSION("), isA(PreparedStatementSetter.class)); - verify(this.jdbcOperations, times(1)).update( - startsWith("INSERT INTO SPRING_SESSION_ATTRIBUTES("), + verify(this.jdbcOperations, times(1)).update(startsWith("INSERT INTO SPRING_SESSION_ATTRIBUTES("), isA(PreparedStatementSetter.class)); verifyZeroInteractions(this.jdbcOperations); } @Test - public void saveNewWithMultipleAttributes() { - JdbcOperationsSessionRepository.JdbcSession session = this.repository - .createSession(); + void saveNewWithMultipleAttributes() { + JdbcOperationsSessionRepository.JdbcSession session = this.repository.createSession(); session.setAttribute("testName1", "testValue1"); session.setAttribute("testName2", "testValue2"); @@ -320,35 +283,32 @@ public class JdbcOperationsSessionRepositoryTests { assertThat(session.isNew()).isFalse(); assertPropagationRequiresNew(); - verify(this.jdbcOperations, times(1)).update( - startsWith("INSERT INTO SPRING_SESSION("), + verify(this.jdbcOperations, times(1)).update(startsWith("INSERT INTO SPRING_SESSION("), isA(PreparedStatementSetter.class)); - verify(this.jdbcOperations, times(1)).batchUpdate( - startsWith("INSERT INTO SPRING_SESSION_ATTRIBUTES("), + verify(this.jdbcOperations, times(1)).batchUpdate(startsWith("INSERT INTO SPRING_SESSION_ATTRIBUTES("), isA(BatchPreparedStatementSetter.class)); verifyZeroInteractions(this.jdbcOperations); } @Test - public void saveUpdatedAddSingleAttribute() { - JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession( - "primaryKey", new MapSession()); + void saveUpdatedAddSingleAttribute() { + JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession("primaryKey", + new MapSession()); session.setAttribute("testName", "testValue"); this.repository.save(session); assertThat(session.isNew()).isFalse(); assertPropagationRequiresNew(); - verify(this.jdbcOperations, times(1)).update( - startsWith("INSERT INTO SPRING_SESSION_ATTRIBUTES("), + verify(this.jdbcOperations, times(1)).update(startsWith("INSERT INTO SPRING_SESSION_ATTRIBUTES("), isA(PreparedStatementSetter.class)); verifyZeroInteractions(this.jdbcOperations); } @Test - public void saveUpdatedAddMultipleAttributes() { - JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession( - "primaryKey", new MapSession()); + void saveUpdatedAddMultipleAttributes() { + JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession("primaryKey", + new MapSession()); session.setAttribute("testName1", "testValue1"); session.setAttribute("testName2", "testValue2"); @@ -356,16 +316,15 @@ public class JdbcOperationsSessionRepositoryTests { assertThat(session.isNew()).isFalse(); assertPropagationRequiresNew(); - verify(this.jdbcOperations, times(1)).batchUpdate( - startsWith("INSERT INTO SPRING_SESSION_ATTRIBUTES("), + verify(this.jdbcOperations, times(1)).batchUpdate(startsWith("INSERT INTO SPRING_SESSION_ATTRIBUTES("), isA(BatchPreparedStatementSetter.class)); verifyZeroInteractions(this.jdbcOperations); } @Test - public void saveUpdatedModifySingleAttribute() { - JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession( - "primaryKey", new MapSession()); + void saveUpdatedModifySingleAttribute() { + JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession("primaryKey", + new MapSession()); session.setAttribute("testName", "testValue"); session.clearChangeFlags(); session.setAttribute("testName", "testValue"); @@ -374,16 +333,15 @@ public class JdbcOperationsSessionRepositoryTests { assertThat(session.isNew()).isFalse(); assertPropagationRequiresNew(); - verify(this.jdbcOperations, times(1)).update( - startsWith("UPDATE SPRING_SESSION_ATTRIBUTES SET"), + verify(this.jdbcOperations, times(1)).update(startsWith("UPDATE SPRING_SESSION_ATTRIBUTES SET"), isA(PreparedStatementSetter.class)); verifyZeroInteractions(this.jdbcOperations); } @Test - public void saveUpdatedModifyMultipleAttributes() { - JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession( - "primaryKey", new MapSession()); + void saveUpdatedModifyMultipleAttributes() { + JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession("primaryKey", + new MapSession()); session.setAttribute("testName1", "testValue1"); session.setAttribute("testName2", "testValue2"); session.clearChangeFlags(); @@ -394,16 +352,15 @@ public class JdbcOperationsSessionRepositoryTests { assertThat(session.isNew()).isFalse(); assertPropagationRequiresNew(); - verify(this.jdbcOperations, times(1)).batchUpdate( - startsWith("UPDATE SPRING_SESSION_ATTRIBUTES SET"), + verify(this.jdbcOperations, times(1)).batchUpdate(startsWith("UPDATE SPRING_SESSION_ATTRIBUTES SET"), isA(BatchPreparedStatementSetter.class)); verifyZeroInteractions(this.jdbcOperations); } @Test - public void saveUpdatedRemoveSingleAttribute() { - JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession( - "primaryKey", new MapSession()); + void saveUpdatedRemoveSingleAttribute() { + JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession("primaryKey", + new MapSession()); session.setAttribute("testName", "testValue"); session.clearChangeFlags(); session.removeAttribute("testName"); @@ -412,16 +369,15 @@ public class JdbcOperationsSessionRepositoryTests { assertThat(session.isNew()).isFalse(); assertPropagationRequiresNew(); - verify(this.jdbcOperations, times(1)).update( - startsWith("DELETE FROM SPRING_SESSION_ATTRIBUTES WHERE"), + verify(this.jdbcOperations, times(1)).update(startsWith("DELETE FROM SPRING_SESSION_ATTRIBUTES WHERE"), isA(PreparedStatementSetter.class)); verifyZeroInteractions(this.jdbcOperations); } @Test - public void saveUpdatedRemoveNonExistingAttribute() { - JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession( - "primaryKey", new MapSession()); + void saveUpdatedRemoveNonExistingAttribute() { + JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession("primaryKey", + new MapSession()); session.removeAttribute("testName"); this.repository.save(session); @@ -432,9 +388,9 @@ public class JdbcOperationsSessionRepositoryTests { } @Test - public void saveUpdatedRemoveMultipleAttributes() { - JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession( - "primaryKey", new MapSession()); + void saveUpdatedRemoveMultipleAttributes() { + JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession("primaryKey", + new MapSession()); session.setAttribute("testName1", "testValue1"); session.setAttribute("testName2", "testValue2"); session.clearChangeFlags(); @@ -445,16 +401,15 @@ public class JdbcOperationsSessionRepositoryTests { assertThat(session.isNew()).isFalse(); assertPropagationRequiresNew(); - verify(this.jdbcOperations, times(1)).batchUpdate( - startsWith("DELETE FROM SPRING_SESSION_ATTRIBUTES WHERE"), + verify(this.jdbcOperations, times(1)).batchUpdate(startsWith("DELETE FROM SPRING_SESSION_ATTRIBUTES WHERE"), isA(BatchPreparedStatementSetter.class)); verifyZeroInteractions(this.jdbcOperations); } @Test // gh-1070 - public void saveUpdatedAddAndModifyAttribute() { - JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession( - "primaryKey", new MapSession()); + void saveUpdatedAddAndModifyAttribute() { + JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession("primaryKey", + new MapSession()); session.setAttribute("testName", "testValue1"); session.setAttribute("testName", "testValue2"); @@ -462,16 +417,15 @@ public class JdbcOperationsSessionRepositoryTests { assertThat(session.isNew()).isFalse(); assertPropagationRequiresNew(); - verify(this.jdbcOperations).update( - startsWith("INSERT INTO SPRING_SESSION_ATTRIBUTES("), + verify(this.jdbcOperations).update(startsWith("INSERT INTO SPRING_SESSION_ATTRIBUTES("), isA(PreparedStatementSetter.class)); verifyZeroInteractions(this.jdbcOperations); } @Test // gh-1070 - public void saveUpdatedAddAndRemoveAttribute() { - JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession( - "primaryKey", new MapSession()); + void saveUpdatedAddAndRemoveAttribute() { + JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession("primaryKey", + new MapSession()); session.setAttribute("testName", "testValue"); session.removeAttribute("testName"); @@ -483,9 +437,9 @@ public class JdbcOperationsSessionRepositoryTests { } @Test // gh-1070 - public void saveUpdatedModifyAndRemoveAttribute() { - JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession( - "primaryKey", new MapSession()); + void saveUpdatedModifyAndRemoveAttribute() { + JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession("primaryKey", + new MapSession()); session.setAttribute("testName", "testValue1"); session.clearChangeFlags(); session.setAttribute("testName", "testValue2"); @@ -495,16 +449,15 @@ public class JdbcOperationsSessionRepositoryTests { assertThat(session.isNew()).isFalse(); assertPropagationRequiresNew(); - verify(this.jdbcOperations).update( - startsWith("DELETE FROM SPRING_SESSION_ATTRIBUTES WHERE"), + verify(this.jdbcOperations).update(startsWith("DELETE FROM SPRING_SESSION_ATTRIBUTES WHERE"), isA(PreparedStatementSetter.class)); verifyZeroInteractions(this.jdbcOperations); } @Test // gh-1070 - public void saveUpdatedRemoveAndAddAttribute() { - JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession( - "primaryKey", new MapSession()); + void saveUpdatedRemoveAndAddAttribute() { + JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession("primaryKey", + new MapSession()); session.setAttribute("testName", "testValue1"); session.clearChangeFlags(); session.removeAttribute("testName"); @@ -514,32 +467,30 @@ public class JdbcOperationsSessionRepositoryTests { assertThat(session.isNew()).isFalse(); assertPropagationRequiresNew(); - verify(this.jdbcOperations).update( - startsWith("UPDATE SPRING_SESSION_ATTRIBUTES SET"), + verify(this.jdbcOperations).update(startsWith("UPDATE SPRING_SESSION_ATTRIBUTES SET"), isA(PreparedStatementSetter.class)); verifyZeroInteractions(this.jdbcOperations); } @Test - public void saveUpdatedLastAccessedTime() { - JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession( - "primaryKey", new MapSession()); + void saveUpdatedLastAccessedTime() { + JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession("primaryKey", + new MapSession()); session.setLastAccessedTime(Instant.now()); this.repository.save(session); assertThat(session.isNew()).isFalse(); assertPropagationRequiresNew(); - verify(this.jdbcOperations, times(1)).update( - startsWith("UPDATE SPRING_SESSION SET"), + verify(this.jdbcOperations, times(1)).update(startsWith("UPDATE SPRING_SESSION SET"), isA(PreparedStatementSetter.class)); verifyZeroInteractions(this.jdbcOperations); } @Test - public void saveUnchanged() { - JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession( - "primaryKey", new MapSession()); + void saveUnchanged() { + JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession("primaryKey", + new MapSession()); this.repository.save(session); @@ -549,64 +500,56 @@ public class JdbcOperationsSessionRepositoryTests { @Test @SuppressWarnings("unchecked") - public void getSessionNotFound() { + void getSessionNotFound() { String sessionId = "testSessionId"; - given(this.jdbcOperations.query(isA(String.class), - isA(PreparedStatementSetter.class), isA(ResultSetExtractor.class))) - .willReturn(Collections.emptyList()); + given(this.jdbcOperations.query(isA(String.class), isA(PreparedStatementSetter.class), + isA(ResultSetExtractor.class))).willReturn(Collections.emptyList()); - JdbcOperationsSessionRepository.JdbcSession session = this.repository - .findById(sessionId); + JdbcOperationsSessionRepository.JdbcSession session = this.repository.findById(sessionId); assertThat(session).isNull(); assertPropagationRequiresNew(); - verify(this.jdbcOperations, times(1)).query(isA(String.class), - isA(PreparedStatementSetter.class), isA(ResultSetExtractor.class)); + verify(this.jdbcOperations, times(1)).query(isA(String.class), isA(PreparedStatementSetter.class), + isA(ResultSetExtractor.class)); } @Test @SuppressWarnings("unchecked") - public void getSessionExpired() { + void getSessionExpired() { Session expired = this.repository.new JdbcSession(); - expired.setLastAccessedTime(Instant.now() - .minusSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS + 1)); - given(this.jdbcOperations.query(isA(String.class), - isA(PreparedStatementSetter.class), isA(ResultSetExtractor.class))) - .willReturn(Collections.singletonList(expired)); + expired.setLastAccessedTime(Instant.now().minusSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS + 1)); + given(this.jdbcOperations.query(isA(String.class), isA(PreparedStatementSetter.class), + isA(ResultSetExtractor.class))).willReturn(Collections.singletonList(expired)); - JdbcOperationsSessionRepository.JdbcSession session = this.repository - .findById(expired.getId()); + JdbcOperationsSessionRepository.JdbcSession session = this.repository.findById(expired.getId()); assertThat(session).isNull(); assertPropagationRequiresNew(); - verify(this.jdbcOperations, times(1)).query(isA(String.class), - isA(PreparedStatementSetter.class), isA(ResultSetExtractor.class)); - verify(this.jdbcOperations, times(1)).update(startsWith("DELETE"), - eq(expired.getId())); + verify(this.jdbcOperations, times(1)).query(isA(String.class), isA(PreparedStatementSetter.class), + isA(ResultSetExtractor.class)); + verify(this.jdbcOperations, times(1)).update(startsWith("DELETE"), eq(expired.getId())); } @Test @SuppressWarnings("unchecked") - public void getSessionFound() { + void getSessionFound() { Session saved = this.repository.new JdbcSession("primaryKey", new MapSession()); saved.setAttribute("savedName", "savedValue"); - given(this.jdbcOperations.query(isA(String.class), - isA(PreparedStatementSetter.class), isA(ResultSetExtractor.class))) - .willReturn(Collections.singletonList(saved)); + given(this.jdbcOperations.query(isA(String.class), isA(PreparedStatementSetter.class), + isA(ResultSetExtractor.class))).willReturn(Collections.singletonList(saved)); - JdbcOperationsSessionRepository.JdbcSession session = this.repository - .findById(saved.getId()); + JdbcOperationsSessionRepository.JdbcSession session = this.repository.findById(saved.getId()); assertThat(session.getId()).isEqualTo(saved.getId()); assertThat(session.isNew()).isFalse(); assertThat(session.getAttribute("savedName")).isEqualTo("savedValue"); assertPropagationRequiresNew(); - verify(this.jdbcOperations, times(1)).query(isA(String.class), - isA(PreparedStatementSetter.class), isA(ResultSetExtractor.class)); + verify(this.jdbcOperations, times(1)).query(isA(String.class), isA(PreparedStatementSetter.class), + isA(ResultSetExtractor.class)); } @Test - public void delete() { + void delete() { String sessionId = "testSessionId"; this.repository.deleteById(sessionId); @@ -616,7 +559,7 @@ public class JdbcOperationsSessionRepositoryTests { } @Test - public void findByIndexNameAndIndexValueUnknownIndexName() { + void findByIndexNameAndIndexValueUnknownIndexName() { String indexValue = "testIndexValue"; Map sessions = this.repository @@ -628,29 +571,26 @@ public class JdbcOperationsSessionRepositoryTests { @Test @SuppressWarnings("unchecked") - public void findByIndexNameAndIndexValuePrincipalIndexNameNotFound() { + void findByIndexNameAndIndexValuePrincipalIndexNameNotFound() { String principal = "username"; - given(this.jdbcOperations.query(isA(String.class), - isA(PreparedStatementSetter.class), isA(ResultSetExtractor.class))) - .willReturn(Collections.emptyList()); + given(this.jdbcOperations.query(isA(String.class), isA(PreparedStatementSetter.class), + isA(ResultSetExtractor.class))).willReturn(Collections.emptyList()); Map sessions = this.repository - .findByIndexNameAndIndexValue( - FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, - principal); + .findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, principal); assertThat(sessions).isEmpty(); assertPropagationRequiresNew(); - verify(this.jdbcOperations, times(1)).query(isA(String.class), - isA(PreparedStatementSetter.class), isA(ResultSetExtractor.class)); + verify(this.jdbcOperations, times(1)).query(isA(String.class), isA(PreparedStatementSetter.class), + isA(ResultSetExtractor.class)); } @Test @SuppressWarnings("unchecked") - public void findByIndexNameAndIndexValuePrincipalIndexNameFound() { + void findByIndexNameAndIndexValuePrincipalIndexNameFound() { String principal = "username"; - Authentication authentication = new UsernamePasswordAuthenticationToken(principal, - "notused", AuthorityUtils.createAuthorityList("ROLE_USER")); + Authentication authentication = new UsernamePasswordAuthenticationToken(principal, "notused", + AuthorityUtils.createAuthorityList("ROLE_USER")); List saved = new ArrayList<>(2); Session saved1 = this.repository.new JdbcSession(); saved1.setAttribute(SPRING_SECURITY_CONTEXT, authentication); @@ -658,23 +598,20 @@ public class JdbcOperationsSessionRepositoryTests { Session saved2 = this.repository.new JdbcSession(); saved2.setAttribute(SPRING_SECURITY_CONTEXT, authentication); saved.add(saved2); - given(this.jdbcOperations.query(isA(String.class), - isA(PreparedStatementSetter.class), isA(ResultSetExtractor.class))) - .willReturn(saved); + given(this.jdbcOperations.query(isA(String.class), isA(PreparedStatementSetter.class), + isA(ResultSetExtractor.class))).willReturn(saved); Map sessions = this.repository - .findByIndexNameAndIndexValue( - FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, - principal); + .findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, principal); assertThat(sessions).hasSize(2); assertPropagationRequiresNew(); - verify(this.jdbcOperations, times(1)).query(isA(String.class), - isA(PreparedStatementSetter.class), isA(ResultSetExtractor.class)); + verify(this.jdbcOperations, times(1)).query(isA(String.class), isA(PreparedStatementSetter.class), + isA(ResultSetExtractor.class)); } @Test - public void cleanupExpiredSessions() { + void cleanupExpiredSessions() { this.repository.cleanUpExpiredSessions(); assertPropagationRequiresNew(); @@ -682,9 +619,8 @@ public class JdbcOperationsSessionRepositoryTests { } @Test // gh-1120 - public void getAttributeNamesAndRemove() { - JdbcOperationsSessionRepository.JdbcSession session = this.repository - .createSession(); + void getAttributeNamesAndRemove() { + JdbcOperationsSessionRepository.JdbcSession session = this.repository.createSession(); session.setAttribute("attribute1", "value1"); session.setAttribute("attribute2", "value2"); @@ -696,25 +632,23 @@ public class JdbcOperationsSessionRepositoryTests { } @Test - public void saveNewWithoutTransaction() { + void saveNewWithoutTransaction() { this.repository = new JdbcOperationsSessionRepository(this.jdbcOperations); - JdbcOperationsSessionRepository.JdbcSession session = this.repository - .createSession(); + JdbcOperationsSessionRepository.JdbcSession session = this.repository.createSession(); this.repository.save(session); - verify(this.jdbcOperations, times(1)).update( - startsWith("INSERT INTO SPRING_SESSION"), + verify(this.jdbcOperations, times(1)).update(startsWith("INSERT INTO SPRING_SESSION"), isA(PreparedStatementSetter.class)); verifyZeroInteractions(this.jdbcOperations); verifyZeroInteractions(this.transactionManager); } @Test - public void saveUpdatedWithoutTransaction() { + void saveUpdatedWithoutTransaction() { this.repository = new JdbcOperationsSessionRepository(this.jdbcOperations); - JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession( - "primaryKey", new MapSession()); + JdbcOperationsSessionRepository.JdbcSession session = this.repository.new JdbcSession("primaryKey", + new MapSession()); session.setLastAccessedTime(Instant.now()); this.repository.save(session); @@ -727,9 +661,9 @@ public class JdbcOperationsSessionRepositoryTests { @Test @SuppressWarnings("unchecked") - public void findByIdWithoutTransaction() { - given(this.jdbcOperations.query(anyString(), any(PreparedStatementSetter.class), - any(ResultSetExtractor.class))).willReturn(Collections.emptyList()); + void findByIdWithoutTransaction() { + given(this.jdbcOperations.query(anyString(), any(PreparedStatementSetter.class), any(ResultSetExtractor.class))) + .willReturn(Collections.emptyList()); this.repository = new JdbcOperationsSessionRepository(this.jdbcOperations); this.repository.findById("testSessionId"); @@ -740,47 +674,43 @@ public class JdbcOperationsSessionRepositoryTests { } @Test - public void deleteByIdWithoutTransaction() { + void deleteByIdWithoutTransaction() { this.repository = new JdbcOperationsSessionRepository(this.jdbcOperations); this.repository.deleteById("testSessionId"); - verify(this.jdbcOperations, times(1)).update( - eq("DELETE FROM SPRING_SESSION WHERE SESSION_ID = ?"), anyString()); + verify(this.jdbcOperations, times(1)).update(eq("DELETE FROM SPRING_SESSION WHERE SESSION_ID = ?"), + anyString()); verifyZeroInteractions(this.jdbcOperations); verifyZeroInteractions(this.transactionManager); } @Test @SuppressWarnings("unchecked") - public void findByIndexNameAndIndexValueWithoutTransaction() { - given(this.jdbcOperations.query(anyString(), any(PreparedStatementSetter.class), - any(ResultSetExtractor.class))).willReturn(Collections.emptyList()); + void findByIndexNameAndIndexValueWithoutTransaction() { + given(this.jdbcOperations.query(anyString(), any(PreparedStatementSetter.class), any(ResultSetExtractor.class))) + .willReturn(Collections.emptyList()); this.repository = new JdbcOperationsSessionRepository(this.jdbcOperations); - this.repository.findByIndexNameAndIndexValue( - FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, + this.repository.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, "testIndexValue"); - verify(this.jdbcOperations, times(1)).query( - endsWith("WHERE S.PRINCIPAL_NAME = ?"), + verify(this.jdbcOperations, times(1)).query(endsWith("WHERE S.PRINCIPAL_NAME = ?"), isA(PreparedStatementSetter.class), isA(ResultSetExtractor.class)); verifyZeroInteractions(this.jdbcOperations); verifyZeroInteractions(this.transactionManager); } @Test - public void cleanUpExpiredSessionsWithoutTransaction() { + void cleanUpExpiredSessionsWithoutTransaction() { this.repository = new JdbcOperationsSessionRepository(this.jdbcOperations); this.repository.cleanUpExpiredSessions(); - verify(this.jdbcOperations, times(1)).update( - eq("DELETE FROM SPRING_SESSION WHERE EXPIRY_TIME < ?"), anyLong()); + verify(this.jdbcOperations, times(1)).update(eq("DELETE FROM SPRING_SESSION WHERE EXPIRY_TIME < ?"), anyLong()); verifyZeroInteractions(this.jdbcOperations); verifyZeroInteractions(this.transactionManager); } private void assertPropagationRequiresNew() { - ArgumentCaptor argument = ArgumentCaptor - .forClass(TransactionDefinition.class); + ArgumentCaptor argument = ArgumentCaptor.forClass(TransactionDefinition.class); verify(this.transactionManager, atLeastOnce()).getTransaction(argument.capture()); assertThat(argument.getValue().getPropagationBehavior()) .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); diff --git a/spring-session-jdbc/src/test/java/org/springframework/session/jdbc/config/annotation/web/http/JdbcHttpSessionConfigurationTests.java b/spring-session-jdbc/src/test/java/org/springframework/session/jdbc/config/annotation/web/http/JdbcHttpSessionConfigurationTests.java index 566141a4..3485eb5c 100644 --- a/spring-session-jdbc/src/test/java/org/springframework/session/jdbc/config/annotation/web/http/JdbcHttpSessionConfigurationTests.java +++ b/spring-session-jdbc/src/test/java/org/springframework/session/jdbc/config/annotation/web/http/JdbcHttpSessionConfigurationTests.java @@ -47,7 +47,7 @@ import static org.mockito.Mockito.mock; * @author Eddú Meléndez * @since 1.2.0 */ -public class JdbcHttpSessionConfigurationTests { +class JdbcHttpSessionConfigurationTests { private static final String TABLE_NAME = "TEST_SESSION"; @@ -58,219 +58,174 @@ public class JdbcHttpSessionConfigurationTests { private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); @AfterEach - public void closeContext() { + void closeContext() { if (this.context != null) { this.context.close(); } } @Test - public void noDataSourceConfiguration() { + void noDataSourceConfiguration() { assertThatExceptionOfType(BeanCreationException.class) .isThrownBy(() -> registerAndRefresh(NoDataSourceConfiguration.class)) - .withMessageContaining( - "expected at least 1 bean which qualifies as autowire candidate"); + .withMessageContaining("expected at least 1 bean which qualifies as autowire candidate"); } @Test - public void defaultConfiguration() { + void defaultConfiguration() { registerAndRefresh(DataSourceConfiguration.class, DefaultConfiguration.class); - assertThat(this.context.getBean(JdbcOperationsSessionRepository.class)) - .isNotNull(); + assertThat(this.context.getBean(JdbcOperationsSessionRepository.class)).isNotNull(); } @Test - public void customTableNameAnnotation() { - registerAndRefresh(DataSourceConfiguration.class, - CustomTableNameAnnotationConfiguration.class); + void customTableNameAnnotation() { + registerAndRefresh(DataSourceConfiguration.class, CustomTableNameAnnotationConfiguration.class); - JdbcOperationsSessionRepository repository = this.context - .getBean(JdbcOperationsSessionRepository.class); + JdbcOperationsSessionRepository repository = this.context.getBean(JdbcOperationsSessionRepository.class); assertThat(repository).isNotNull(); - assertThat(ReflectionTestUtils.getField(repository, "tableName")) - .isEqualTo(TABLE_NAME); + assertThat(ReflectionTestUtils.getField(repository, "tableName")).isEqualTo(TABLE_NAME); } @Test - public void customTableNameSetter() { - registerAndRefresh(DataSourceConfiguration.class, - CustomTableNameSetterConfiguration.class); + void customTableNameSetter() { + registerAndRefresh(DataSourceConfiguration.class, CustomTableNameSetterConfiguration.class); - JdbcOperationsSessionRepository repository = this.context - .getBean(JdbcOperationsSessionRepository.class); + JdbcOperationsSessionRepository repository = this.context.getBean(JdbcOperationsSessionRepository.class); assertThat(repository).isNotNull(); - assertThat(ReflectionTestUtils.getField(repository, "tableName")) - .isEqualTo(TABLE_NAME); + assertThat(ReflectionTestUtils.getField(repository, "tableName")).isEqualTo(TABLE_NAME); } @Test - public void customMaxInactiveIntervalInSecondsAnnotation() { + void customMaxInactiveIntervalInSecondsAnnotation() { registerAndRefresh(DataSourceConfiguration.class, CustomMaxInactiveIntervalInSecondsAnnotationConfiguration.class); - JdbcOperationsSessionRepository repository = this.context - .getBean(JdbcOperationsSessionRepository.class); + JdbcOperationsSessionRepository repository = this.context.getBean(JdbcOperationsSessionRepository.class); assertThat(repository).isNotNull(); assertThat(ReflectionTestUtils.getField(repository, "defaultMaxInactiveInterval")) .isEqualTo(MAX_INACTIVE_INTERVAL_IN_SECONDS); } @Test - public void customMaxInactiveIntervalInSecondsSetter() { - registerAndRefresh(DataSourceConfiguration.class, - CustomMaxInactiveIntervalInSecondsSetterConfiguration.class); + void customMaxInactiveIntervalInSecondsSetter() { + registerAndRefresh(DataSourceConfiguration.class, CustomMaxInactiveIntervalInSecondsSetterConfiguration.class); - JdbcOperationsSessionRepository repository = this.context - .getBean(JdbcOperationsSessionRepository.class); + JdbcOperationsSessionRepository repository = this.context.getBean(JdbcOperationsSessionRepository.class); assertThat(repository).isNotNull(); assertThat(ReflectionTestUtils.getField(repository, "defaultMaxInactiveInterval")) .isEqualTo(MAX_INACTIVE_INTERVAL_IN_SECONDS); } @Test - public void customCleanupCronAnnotation() { - registerAndRefresh(DataSourceConfiguration.class, - CustomCleanupCronExpressionAnnotationConfiguration.class); + void customCleanupCronAnnotation() { + registerAndRefresh(DataSourceConfiguration.class, CustomCleanupCronExpressionAnnotationConfiguration.class); - JdbcHttpSessionConfiguration configuration = this.context - .getBean(JdbcHttpSessionConfiguration.class); + JdbcHttpSessionConfiguration configuration = this.context.getBean(JdbcHttpSessionConfiguration.class); assertThat(configuration).isNotNull(); - assertThat(ReflectionTestUtils.getField(configuration, "cleanupCron")) - .isEqualTo(CLEANUP_CRON_EXPRESSION); + assertThat(ReflectionTestUtils.getField(configuration, "cleanupCron")).isEqualTo(CLEANUP_CRON_EXPRESSION); } @Test - public void customCleanupCronSetter() { - registerAndRefresh(DataSourceConfiguration.class, - CustomCleanupCronExpressionSetterConfiguration.class); + void customCleanupCronSetter() { + registerAndRefresh(DataSourceConfiguration.class, CustomCleanupCronExpressionSetterConfiguration.class); - JdbcHttpSessionConfiguration configuration = this.context - .getBean(JdbcHttpSessionConfiguration.class); + JdbcHttpSessionConfiguration configuration = this.context.getBean(JdbcHttpSessionConfiguration.class); assertThat(configuration).isNotNull(); - assertThat(ReflectionTestUtils.getField(configuration, "cleanupCron")) - .isEqualTo(CLEANUP_CRON_EXPRESSION); + assertThat(ReflectionTestUtils.getField(configuration, "cleanupCron")).isEqualTo(CLEANUP_CRON_EXPRESSION); } @Test - public void qualifiedDataSourceConfiguration() { - registerAndRefresh(DataSourceConfiguration.class, - QualifiedDataSourceConfiguration.class); + void qualifiedDataSourceConfiguration() { + registerAndRefresh(DataSourceConfiguration.class, QualifiedDataSourceConfiguration.class); - JdbcOperationsSessionRepository repository = this.context - .getBean(JdbcOperationsSessionRepository.class); - DataSource dataSource = this.context.getBean("qualifiedDataSource", - DataSource.class); + JdbcOperationsSessionRepository repository = this.context.getBean(JdbcOperationsSessionRepository.class); + DataSource dataSource = this.context.getBean("qualifiedDataSource", DataSource.class); assertThat(repository).isNotNull(); assertThat(dataSource).isNotNull(); - JdbcOperations jdbcOperations = (JdbcOperations) ReflectionTestUtils - .getField(repository, "jdbcOperations"); + JdbcOperations jdbcOperations = (JdbcOperations) ReflectionTestUtils.getField(repository, "jdbcOperations"); assertThat(jdbcOperations).isNotNull(); - assertThat(ReflectionTestUtils.getField(jdbcOperations, "dataSource")) - .isEqualTo(dataSource); + assertThat(ReflectionTestUtils.getField(jdbcOperations, "dataSource")).isEqualTo(dataSource); } @Test - public void primaryDataSourceConfiguration() { - registerAndRefresh(DataSourceConfiguration.class, - PrimaryDataSourceConfiguration.class); + void primaryDataSourceConfiguration() { + registerAndRefresh(DataSourceConfiguration.class, PrimaryDataSourceConfiguration.class); - JdbcOperationsSessionRepository repository = this.context - .getBean(JdbcOperationsSessionRepository.class); - DataSource dataSource = this.context.getBean("primaryDataSource", - DataSource.class); + JdbcOperationsSessionRepository repository = this.context.getBean(JdbcOperationsSessionRepository.class); + DataSource dataSource = this.context.getBean("primaryDataSource", DataSource.class); assertThat(repository).isNotNull(); assertThat(dataSource).isNotNull(); - JdbcOperations jdbcOperations = (JdbcOperations) ReflectionTestUtils - .getField(repository, "jdbcOperations"); + JdbcOperations jdbcOperations = (JdbcOperations) ReflectionTestUtils.getField(repository, "jdbcOperations"); assertThat(jdbcOperations).isNotNull(); - assertThat(ReflectionTestUtils.getField(jdbcOperations, "dataSource")) - .isEqualTo(dataSource); + assertThat(ReflectionTestUtils.getField(jdbcOperations, "dataSource")).isEqualTo(dataSource); } @Test - public void qualifiedAndPrimaryDataSourceConfiguration() { - registerAndRefresh(DataSourceConfiguration.class, - QualifiedAndPrimaryDataSourceConfiguration.class); + void qualifiedAndPrimaryDataSourceConfiguration() { + registerAndRefresh(DataSourceConfiguration.class, QualifiedAndPrimaryDataSourceConfiguration.class); - JdbcOperationsSessionRepository repository = this.context - .getBean(JdbcOperationsSessionRepository.class); - DataSource dataSource = this.context.getBean("qualifiedDataSource", - DataSource.class); + JdbcOperationsSessionRepository repository = this.context.getBean(JdbcOperationsSessionRepository.class); + DataSource dataSource = this.context.getBean("qualifiedDataSource", DataSource.class); assertThat(repository).isNotNull(); assertThat(dataSource).isNotNull(); - JdbcOperations jdbcOperations = (JdbcOperations) ReflectionTestUtils - .getField(repository, "jdbcOperations"); + JdbcOperations jdbcOperations = (JdbcOperations) ReflectionTestUtils.getField(repository, "jdbcOperations"); assertThat(jdbcOperations).isNotNull(); - assertThat(ReflectionTestUtils.getField(jdbcOperations, "dataSource")) - .isEqualTo(dataSource); + assertThat(ReflectionTestUtils.getField(jdbcOperations, "dataSource")).isEqualTo(dataSource); } @Test - public void namedDataSourceConfiguration() { - registerAndRefresh(DataSourceConfiguration.class, - NamedDataSourceConfiguration.class); + void namedDataSourceConfiguration() { + registerAndRefresh(DataSourceConfiguration.class, NamedDataSourceConfiguration.class); - JdbcOperationsSessionRepository repository = this.context - .getBean(JdbcOperationsSessionRepository.class); + JdbcOperationsSessionRepository repository = this.context.getBean(JdbcOperationsSessionRepository.class); DataSource dataSource = this.context.getBean("dataSource", DataSource.class); assertThat(repository).isNotNull(); assertThat(dataSource).isNotNull(); - JdbcOperations jdbcOperations = (JdbcOperations) ReflectionTestUtils - .getField(repository, "jdbcOperations"); + JdbcOperations jdbcOperations = (JdbcOperations) ReflectionTestUtils.getField(repository, "jdbcOperations"); assertThat(jdbcOperations).isNotNull(); - assertThat(ReflectionTestUtils.getField(jdbcOperations, "dataSource")) - .isEqualTo(dataSource); + assertThat(ReflectionTestUtils.getField(jdbcOperations, "dataSource")).isEqualTo(dataSource); } @Test - public void multipleDataSourceConfiguration() { + void multipleDataSourceConfiguration() { assertThatExceptionOfType(BeanCreationException.class) - .isThrownBy(() -> registerAndRefresh(DataSourceConfiguration.class, - MultipleDataSourceConfiguration.class)) + .isThrownBy( + () -> registerAndRefresh(DataSourceConfiguration.class, MultipleDataSourceConfiguration.class)) .withMessageContaining("expected single matching bean but found 2"); } @Test - public void customLobHandlerConfiguration() { - registerAndRefresh(DataSourceConfiguration.class, - CustomLobHandlerConfiguration.class); + void customLobHandlerConfiguration() { + registerAndRefresh(DataSourceConfiguration.class, CustomLobHandlerConfiguration.class); - JdbcOperationsSessionRepository repository = this.context - .getBean(JdbcOperationsSessionRepository.class); + JdbcOperationsSessionRepository repository = this.context.getBean(JdbcOperationsSessionRepository.class); LobHandler lobHandler = this.context.getBean(LobHandler.class); assertThat(repository).isNotNull(); assertThat(lobHandler).isNotNull(); - assertThat(ReflectionTestUtils.getField(repository, "lobHandler")) - .isEqualTo(lobHandler); + assertThat(ReflectionTestUtils.getField(repository, "lobHandler")).isEqualTo(lobHandler); } @Test - public void customConversionServiceConfiguration() { - registerAndRefresh(DataSourceConfiguration.class, - CustomConversionServiceConfiguration.class); + void customConversionServiceConfiguration() { + registerAndRefresh(DataSourceConfiguration.class, CustomConversionServiceConfiguration.class); - JdbcOperationsSessionRepository repository = this.context - .getBean(JdbcOperationsSessionRepository.class); - ConversionService conversionService = this.context - .getBean("springSessionConversionService", ConversionService.class); + JdbcOperationsSessionRepository repository = this.context.getBean(JdbcOperationsSessionRepository.class); + ConversionService conversionService = this.context.getBean("springSessionConversionService", + ConversionService.class); assertThat(repository).isNotNull(); assertThat(conversionService).isNotNull(); - Object repositoryConversionService = ReflectionTestUtils.getField(repository, - "conversionService"); + Object repositoryConversionService = ReflectionTestUtils.getField(repository, "conversionService"); assertThat(repositoryConversionService).isEqualTo(conversionService); } @Test - public void resolveTableNameByPropertyPlaceholder() { - this.context.setEnvironment(new MockEnvironment() - .withProperty("session.jdbc.tableName", "custom_session_table")); - registerAndRefresh(DataSourceConfiguration.class, - CustomJdbcHttpSessionConfiguration.class); - JdbcHttpSessionConfiguration configuration = this.context - .getBean(JdbcHttpSessionConfiguration.class); - assertThat(ReflectionTestUtils.getField(configuration, "tableName")) - .isEqualTo("custom_session_table"); + void resolveTableNameByPropertyPlaceholder() { + this.context + .setEnvironment(new MockEnvironment().withProperty("session.jdbc.tableName", "custom_session_table")); + registerAndRefresh(DataSourceConfiguration.class, CustomJdbcHttpSessionConfiguration.class); + JdbcHttpSessionConfiguration configuration = this.context.getBean(JdbcHttpSessionConfiguration.class); + assertThat(ReflectionTestUtils.getField(configuration, "tableName")).isEqualTo("custom_session_table"); } private void registerAndRefresh(Class... annotatedClasses) { @@ -323,8 +278,7 @@ public class JdbcHttpSessionConfigurationTests { } @Configuration - static class CustomMaxInactiveIntervalInSecondsSetterConfiguration - extends JdbcHttpSessionConfiguration { + static class CustomMaxInactiveIntervalInSecondsSetterConfiguration extends JdbcHttpSessionConfiguration { CustomMaxInactiveIntervalInSecondsSetterConfiguration() { setMaxInactiveIntervalInSeconds(MAX_INACTIVE_INTERVAL_IN_SECONDS); @@ -338,8 +292,7 @@ public class JdbcHttpSessionConfigurationTests { } @Configuration - static class CustomCleanupCronExpressionSetterConfiguration - extends JdbcHttpSessionConfiguration { + static class CustomCleanupCronExpressionSetterConfiguration extends JdbcHttpSessionConfiguration { CustomCleanupCronExpressionSetterConfiguration() { setCleanupCron(CLEANUP_CRON_EXPRESSION); diff --git a/spring-session-samples/spring-session-sample-boot-findbyusername/src/integration-test/java/sample/FindByUsernameTests.java b/spring-session-samples/spring-session-sample-boot-findbyusername/src/integration-test/java/sample/FindByUsernameTests.java index 4c5e3798..8a2af87a 100644 --- a/spring-session-samples/spring-session-sample-boot-findbyusername/src/integration-test/java/sample/FindByUsernameTests.java +++ b/spring-session-samples/spring-session-sample-boot-findbyusername/src/integration-test/java/sample/FindByUsernameTests.java @@ -44,7 +44,7 @@ import org.springframework.test.web.servlet.htmlunit.webdriver.MockMvcHtmlUnitDr @ExtendWith(SpringExtension.class) @AutoConfigureMockMvc @SpringBootTest(webEnvironment = WebEnvironment.MOCK) -public class FindByUsernameTests { +class FindByUsernameTests { private static final String DOCKER_IMAGE = "redis:5.0.5"; @@ -54,23 +54,23 @@ public class FindByUsernameTests { private WebDriver driver; @BeforeEach - public void setup() { + void setup() { this.driver = MockMvcHtmlUnitDriverBuilder.mockMvcSetup(this.mockMvc).build(); } @AfterEach - public void tearDown() { + void tearDown() { this.driver.quit(); } @Test - public void home() { + void home() { LoginPage login = HomePage.go(this.driver); login.assertAt(); } @Test - public void login() { + void login() { LoginPage login = HomePage.go(this.driver); HomePage home = login.form().login(HomePage.class); home.assertAt(); @@ -84,8 +84,7 @@ public class FindByUsernameTests { @Bean public GenericContainer redisContainer() { - GenericContainer redisContainer = new GenericContainer(DOCKER_IMAGE) - .withExposedPorts(6379); + GenericContainer redisContainer = new GenericContainer(DOCKER_IMAGE).withExposedPorts(6379); redisContainer.start(); return redisContainer; } diff --git a/spring-session-samples/spring-session-sample-boot-findbyusername/src/integration-test/java/sample/pages/HomePage.java b/spring-session-samples/spring-session-sample-boot-findbyusername/src/integration-test/java/sample/pages/HomePage.java index 797d4192..4dc1f58d 100644 --- a/spring-session-samples/spring-session-sample-boot-findbyusername/src/integration-test/java/sample/pages/HomePage.java +++ b/spring-session-samples/spring-session-sample-boot-findbyusername/src/integration-test/java/sample/pages/HomePage.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,6 +33,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Rob Winch */ public class HomePage extends BasePage { + @FindBy(css = "input[type=\"submit\"]") WebElement logout; @@ -41,8 +42,7 @@ public class HomePage extends BasePage { } public void assertAt() { - assertThat(getDriver().getTitle()) - .isEqualTo("Spring Session Sample - Secured Content"); + assertThat(getDriver().getTitle()).isEqualTo("Spring Session Sample - Secured Content"); } public void containCookie(String cookieName) { @@ -76,4 +76,5 @@ public class HomePage extends BasePage { get(driver, "/"); return PageFactory.initElements(driver, LoginPage.class); } + } diff --git a/spring-session-samples/spring-session-sample-boot-findbyusername/src/integration-test/java/sample/pages/LoginPage.java b/spring-session-samples/spring-session-sample-boot-findbyusername/src/integration-test/java/sample/pages/LoginPage.java index 6e2044cc..8479ad02 100644 --- a/spring-session-samples/spring-session-sample-boot-findbyusername/src/integration-test/java/sample/pages/LoginPage.java +++ b/spring-session-samples/spring-session-sample-boot-findbyusername/src/integration-test/java/sample/pages/LoginPage.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,5 +64,7 @@ public class LoginPage extends BasePage { this.button.click(); return PageFactory.initElements(getDriver(), page); } + } + } diff --git a/spring-session-samples/spring-session-sample-boot-findbyusername/src/main/java/sample/FindByUsernameApplication.java b/spring-session-samples/spring-session-sample-boot-findbyusername/src/main/java/sample/FindByUsernameApplication.java index 9eaed3c6..58600dc8 100644 --- a/spring-session-samples/spring-session-sample-boot-findbyusername/src/main/java/sample/FindByUsernameApplication.java +++ b/spring-session-samples/spring-session-sample-boot-findbyusername/src/main/java/sample/FindByUsernameApplication.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,4 +28,5 @@ public class FindByUsernameApplication { public static void main(String[] args) { SpringApplication.run(FindByUsernameApplication.class, args); } + } diff --git a/spring-session-samples/spring-session-sample-boot-findbyusername/src/main/java/sample/config/GeoConfig.java b/spring-session-samples/spring-session-sample-boot-findbyusername/src/main/java/sample/config/GeoConfig.java index 02f7089c..dbc11a4f 100644 --- a/spring-session-samples/spring-session-sample-boot-findbyusername/src/main/java/sample/config/GeoConfig.java +++ b/spring-session-samples/spring-session-sample-boot-findbyusername/src/main/java/sample/config/GeoConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** - * * @author Rob Winch * */ @@ -33,9 +32,8 @@ import org.springframework.context.annotation.Configuration; public class GeoConfig { @Bean - public DatabaseReader geoDatabaseReader( - @Value("classpath:GeoLite2-City.mmdb") InputStream geoInputStream) - throws Exception { + public DatabaseReader geoDatabaseReader(@Value("classpath:GeoLite2-City.mmdb") InputStream geoInputStream) + throws Exception { return new DatabaseReader.Builder(geoInputStream).build(); } diff --git a/spring-session-samples/spring-session-sample-boot-findbyusername/src/main/java/sample/mvc/IndexController.java b/spring-session-samples/spring-session-sample-boot-findbyusername/src/main/java/sample/mvc/IndexController.java index d0903808..123c4f8e 100644 --- a/spring-session-samples/spring-session-sample-boot-findbyusername/src/main/java/sample/mvc/IndexController.java +++ b/spring-session-samples/spring-session-sample-boot-findbyusername/src/main/java/sample/mvc/IndexController.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,28 +37,27 @@ import org.springframework.web.bind.annotation.RequestMethod; */ @Controller public class IndexController { + // tag::findbyusername[] @Autowired FindByIndexNameSessionRepository sessions; @RequestMapping("/") public String index(Principal principal, Model model) { - Collection usersSessions = this.sessions - .findByPrincipalName(principal.getName()).values(); + Collection usersSessions = this.sessions.findByPrincipalName(principal.getName()).values(); model.addAttribute("sessions", usersSessions); return "index"; } // end::findbyusername[] @RequestMapping(value = "/sessions/{sessionIdToDelete}", method = RequestMethod.DELETE) - public String removeSession(Principal principal, - @PathVariable String sessionIdToDelete) { - Set usersSessionIds = this.sessions - .findByPrincipalName(principal.getName()).keySet(); + public String removeSession(Principal principal, @PathVariable String sessionIdToDelete) { + Set usersSessionIds = this.sessions.findByPrincipalName(principal.getName()).keySet(); if (usersSessionIds.contains(sessionIdToDelete)) { this.sessions.deleteById(sessionIdToDelete); } return "redirect:/"; } + } diff --git a/spring-session-samples/spring-session-sample-boot-findbyusername/src/main/java/sample/session/SessionDetails.java b/spring-session-samples/spring-session-sample-boot-findbyusername/src/main/java/sample/session/SessionDetails.java index ee9d3bec..1985648c 100644 --- a/spring-session-samples/spring-session-sample-boot-findbyusername/src/main/java/sample/session/SessionDetails.java +++ b/spring-session-samples/spring-session-sample-boot-findbyusername/src/main/java/sample/session/SessionDetails.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,6 +26,7 @@ import java.io.Serializable; */ // tag::class[] public class SessionDetails implements Serializable { + private String location; private String accessType; @@ -47,5 +48,6 @@ public class SessionDetails implements Serializable { } private static final long serialVersionUID = 8850489178248613501L; + } // end::class[] diff --git a/spring-session-samples/spring-session-sample-boot-findbyusername/src/main/java/sample/session/SessionDetailsFilter.java b/spring-session-samples/spring-session-sample-boot-findbyusername/src/main/java/sample/session/SessionDetailsFilter.java index 271dbb32..1aff9d74 100644 --- a/spring-session-samples/spring-session-sample-boot-findbyusername/src/main/java/sample/session/SessionDetailsFilter.java +++ b/spring-session-samples/spring-session-sample-boot-findbyusername/src/main/java/sample/session/SessionDetailsFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,6 +47,7 @@ import org.springframework.web.filter.OncePerRequestFilter; @Component @Order(Ordered.HIGHEST_PRECEDENCE + 101) public class SessionDetailsFilter extends OncePerRequestFilter { + static final String UNKNOWN = "Unknown"; private DatabaseReader reader; @@ -58,8 +59,8 @@ public class SessionDetailsFilter extends OncePerRequestFilter { // tag::dofilterinternal[] @Override - public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, - FilterChain chain) throws IOException, ServletException { + public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws IOException, ServletException { chain.doFilter(request, response); HttpSession session = request.getSession(false); @@ -108,5 +109,6 @@ public class SessionDetailsFilter extends OncePerRequestFilter { } return remoteAddr; } + } // end::class[] diff --git a/spring-session-samples/spring-session-sample-boot-findbyusername/src/test/java/sample/session/SessionDetailsFilterTests.java b/spring-session-samples/spring-session-sample-boot-findbyusername/src/test/java/sample/session/SessionDetailsFilterTests.java index 4f621078..9a2b5de9 100644 --- a/spring-session-samples/spring-session-sample-boot-findbyusername/src/test/java/sample/session/SessionDetailsFilterTests.java +++ b/spring-session-samples/spring-session-sample-boot-findbyusername/src/test/java/sample/session/SessionDetailsFilterTests.java @@ -34,32 +34,31 @@ import static org.assertj.core.api.Assertions.assertThat; */ @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = GeoConfig.class) -public class SessionDetailsFilterTests { +class SessionDetailsFilterTests { + @Autowired DatabaseReader reader; - SessionDetailsFilter filter; + private SessionDetailsFilter filter; @BeforeEach - public void setup() { + void setup() { this.filter = new SessionDetailsFilter(this.reader); } @Test - public void getGeoLocationHanldesInvalidIp() { - assertThat(this.filter.getGeoLocation("a")) - .isEqualTo(SessionDetailsFilter.UNKNOWN); + void getGeoLocationHanldesInvalidIp() { + assertThat(this.filter.getGeoLocation("a")).isEqualTo(SessionDetailsFilter.UNKNOWN); } @Test - public void getGeoLocationNullCity() { - assertThat(this.filter.getGeoLocation("22.231.113.64")) - .isEqualTo("United States"); + void getGeoLocationNullCity() { + assertThat(this.filter.getGeoLocation("22.231.113.64")).isEqualTo("United States"); } @Test - public void getGeoLocationBoth() { - assertThat(this.filter.getGeoLocation("184.154.83.119")) - .isEqualTo("Chicago, United States"); + void getGeoLocationBoth() { + assertThat(this.filter.getGeoLocation("184.154.83.119")).isEqualTo("Chicago, United States"); } + } diff --git a/spring-session-samples/spring-session-sample-boot-jdbc/src/integration-test/java/sample/BootTests.java b/spring-session-samples/spring-session-sample-boot-jdbc/src/integration-test/java/sample/BootTests.java index 70999917..67c4f4eb 100644 --- a/spring-session-samples/spring-session-sample-boot-jdbc/src/integration-test/java/sample/BootTests.java +++ b/spring-session-samples/spring-session-sample-boot-jdbc/src/integration-test/java/sample/BootTests.java @@ -39,7 +39,7 @@ import org.springframework.test.web.servlet.htmlunit.webdriver.MockMvcHtmlUnitDr @ExtendWith(SpringExtension.class) @AutoConfigureMockMvc @SpringBootTest(webEnvironment = WebEnvironment.MOCK) -public class BootTests { +class BootTests { @Autowired private MockMvc mockMvc; @@ -47,17 +47,17 @@ public class BootTests { private WebDriver driver; @BeforeEach - public void setup() { + void setup() { this.driver = MockMvcHtmlUnitDriverBuilder.mockMvcSetup(this.mockMvc).build(); } @AfterEach - public void tearDown() { + void tearDown() { this.driver.quit(); } @Test - public void home() { + void home() { LoginPage login = HomePage.go(this.driver); login.assertAt(); HomePage home = login.form().login(HomePage.class); @@ -65,7 +65,7 @@ public class BootTests { } @Test - public void login() { + void login() { LoginPage login = HomePage.go(this.driver); HomePage home = login.form().login(HomePage.class); home.containCookie("SESSION"); @@ -73,7 +73,7 @@ public class BootTests { } @Test - public void logout() { + void logout() { LoginPage login = HomePage.go(this.driver); HomePage home = login.form().login(HomePage.class); login = home.logout(); diff --git a/spring-session-samples/spring-session-sample-boot-jdbc/src/integration-test/java/sample/pages/LoginPage.java b/spring-session-samples/spring-session-sample-boot-jdbc/src/integration-test/java/sample/pages/LoginPage.java index b17c0d52..5cbb4e7a 100644 --- a/spring-session-samples/spring-session-sample-boot-jdbc/src/integration-test/java/sample/pages/LoginPage.java +++ b/spring-session-samples/spring-session-sample-boot-jdbc/src/integration-test/java/sample/pages/LoginPage.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,6 +64,7 @@ public class LoginPage extends BasePage { this.button.click(); return PageFactory.initElements(getDriver(), page); } + } } diff --git a/spring-session-samples/spring-session-sample-boot-jdbc/src/main/java/sample/Application.java b/spring-session-samples/spring-session-sample-boot-jdbc/src/main/java/sample/Application.java index aed31f40..d35a66ab 100644 --- a/spring-session-samples/spring-session-sample-boot-jdbc/src/main/java/sample/Application.java +++ b/spring-session-samples/spring-session-sample-boot-jdbc/src/main/java/sample/Application.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,4 +28,5 @@ public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } + } diff --git a/spring-session-samples/spring-session-sample-boot-redis-json/src/integration-test/java/sample/HttpRedisJsonTest.java b/spring-session-samples/spring-session-sample-boot-redis-json/src/integration-test/java/sample/HttpRedisJsonTest.java index 3230112e..e146737f 100644 --- a/spring-session-samples/spring-session-sample-boot-redis-json/src/integration-test/java/sample/HttpRedisJsonTest.java +++ b/spring-session-samples/spring-session-sample-boot-redis-json/src/integration-test/java/sample/HttpRedisJsonTest.java @@ -48,7 +48,7 @@ import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(SpringExtension.class) @SpringBootTest(webEnvironment = WebEnvironment.MOCK) @AutoConfigureMockMvc -public class HttpRedisJsonTest { +class HttpRedisJsonTest { private static final String DOCKER_IMAGE = "redis:5.0.5"; @@ -58,29 +58,29 @@ public class HttpRedisJsonTest { private WebDriver driver; @BeforeEach - public void setup() { + void setup() { this.driver = MockMvcHtmlUnitDriverBuilder.mockMvcSetup(this.mockMvc).build(); } @AfterEach - public void tearDown() { + void tearDown() { this.driver.quit(); } @Test - public void goLoginRedirectToLogin() { + void goLoginRedirectToLogin() { LoginPage login = HomePage.go(this.driver, LoginPage.class); login.assertAt(); } @Test - public void goHomeRedirectLoginPage() { + void goHomeRedirectLoginPage() { LoginPage login = HomePage.go(this.driver, LoginPage.class); login.assertAt(); } @Test - public void login() { + void login() { LoginPage login = HomePage.go(this.driver, LoginPage.class); HomePage home = login.form().login(HomePage.class); home.containCookie("SESSION"); @@ -88,7 +88,7 @@ public class HttpRedisJsonTest { } @Test - public void createAttribute() { + void createAttribute() { LoginPage login = HomePage.go(this.driver, LoginPage.class); HomePage home = login.form().login(HomePage.class); // @formatter:off @@ -108,8 +108,7 @@ public class HttpRedisJsonTest { @Bean public GenericContainer redisContainer() { - GenericContainer redisContainer = new GenericContainer(DOCKER_IMAGE) - .withExposedPorts(6379); + GenericContainer redisContainer = new GenericContainer(DOCKER_IMAGE).withExposedPorts(6379); redisContainer.start(); return redisContainer; } diff --git a/spring-session-samples/spring-session-sample-boot-redis-json/src/integration-test/java/sample/RedisSerializerTest.java b/spring-session-samples/spring-session-sample-boot-redis-json/src/integration-test/java/sample/RedisSerializerTest.java index cb27bad8..ac6a6842 100644 --- a/spring-session-samples/spring-session-sample-boot-redis-json/src/integration-test/java/sample/RedisSerializerTest.java +++ b/spring-session-samples/spring-session-sample-boot-redis-json/src/integration-test/java/sample/RedisSerializerTest.java @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ @ExtendWith(SpringExtension.class) @SpringBootTest -public class RedisSerializerTest { +class RedisSerializerTest { private static final String DOCKER_IMAGE = "redis:5.0.5"; @@ -45,7 +45,7 @@ public class RedisSerializerTest { private RedisTemplate sessionRedisTemplate; @Test - public void testRedisTemplate() { + void testRedisTemplate() { assertThat(this.sessionRedisTemplate).isNotNull(); assertThat(this.sessionRedisTemplate.getDefaultSerializer()).isNotNull(); assertThat(this.sessionRedisTemplate.getDefaultSerializer()) @@ -57,8 +57,7 @@ public class RedisSerializerTest { @Bean public GenericContainer redisContainer() { - GenericContainer redisContainer = new GenericContainer(DOCKER_IMAGE) - .withExposedPorts(6379); + GenericContainer redisContainer = new GenericContainer(DOCKER_IMAGE).withExposedPorts(6379); redisContainer.start(); return redisContainer; } diff --git a/spring-session-samples/spring-session-sample-boot-redis-json/src/integration-test/java/sample/pages/HomePage.java b/spring-session-samples/spring-session-sample-boot-redis-json/src/integration-test/java/sample/pages/HomePage.java index 2ecd4343..1a93614e 100644 --- a/spring-session-samples/spring-session-sample-boot-redis-json/src/integration-test/java/sample/pages/HomePage.java +++ b/spring-session-samples/spring-session-sample-boot-redis-json/src/integration-test/java/sample/pages/HomePage.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,8 +73,7 @@ public class HomePage { } public HomePage logout() { - WebElement logout = this.driver - .findElement(By.cssSelector("input[type=\"submit\"]")); + WebElement logout = this.driver.findElement(By.cssSelector("input[type=\"submit\"]")); logout.click(); return PageFactory.initElements(this.driver, HomePage.class); } @@ -93,6 +92,7 @@ public class HomePage { } public class Form { + @FindBy(name = "key") WebElement attributeName; @@ -120,9 +120,11 @@ public class HomePage { this.submit.click(); return PageFactory.initElements(HomePage.this.driver, page); } + } public static class Attribute { + @FindBy(xpath = ".//td[1]") WebElement attributeName; @@ -146,6 +148,7 @@ public class HomePage { public String getAttributeValue() { return this.attributeValue.getText(); } + } } diff --git a/spring-session-samples/spring-session-sample-boot-redis-json/src/integration-test/java/sample/pages/LoginPage.java b/spring-session-samples/spring-session-sample-boot-redis-json/src/integration-test/java/sample/pages/LoginPage.java index 380a0d10..322c4c3a 100644 --- a/spring-session-samples/spring-session-sample-boot-redis-json/src/integration-test/java/sample/pages/LoginPage.java +++ b/spring-session-samples/spring-session-sample-boot-redis-json/src/integration-test/java/sample/pages/LoginPage.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,6 +64,7 @@ public class LoginPage extends BasePage { this.button.click(); return PageFactory.initElements(getDriver(), page); } + } } diff --git a/spring-session-samples/spring-session-sample-boot-redis-json/src/main/java/sample/Application.java b/spring-session-samples/spring-session-sample-boot-redis-json/src/main/java/sample/Application.java index dfd68c1f..eae311b8 100644 --- a/spring-session-samples/spring-session-sample-boot-redis-json/src/main/java/sample/Application.java +++ b/spring-session-samples/spring-session-sample-boot-redis-json/src/main/java/sample/Application.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,4 +27,5 @@ public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } + } diff --git a/spring-session-samples/spring-session-sample-boot-redis-json/src/main/java/sample/config/SessionConfig.java b/spring-session-samples/spring-session-sample-boot-redis-json/src/main/java/sample/config/SessionConfig.java index 7093e0b3..f3c307d6 100644 --- a/spring-session-samples/spring-session-sample-boot-redis-json/src/main/java/sample/config/SessionConfig.java +++ b/spring-session-samples/spring-session-sample-boot-redis-json/src/main/java/sample/config/SessionConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,7 +40,6 @@ public class SessionConfig implements BeanClassLoaderAware { /** * Customized {@link ObjectMapper} to add mix-in for class that doesn't have default * constructors - * * @return the {@link ObjectMapper} to use */ private ObjectMapper objectMapper() { @@ -60,4 +59,5 @@ public class SessionConfig implements BeanClassLoaderAware { public void setBeanClassLoader(ClassLoader classLoader) { this.loader = classLoader; } + } diff --git a/spring-session-samples/spring-session-sample-boot-redis-json/src/main/java/sample/web/HomeController.java b/spring-session-samples/spring-session-sample-boot-redis-json/src/main/java/sample/web/HomeController.java index 32d7953e..ef514bea 100644 --- a/spring-session-samples/spring-session-sample-boot-redis-json/src/main/java/sample/web/HomeController.java +++ b/spring-session-samples/spring-session-sample-boot-redis-json/src/main/java/sample/web/HomeController.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,11 +30,11 @@ public class HomeController { @RequestMapping("/setValue") public String setValue(@RequestParam(name = "key", required = false) String key, - @RequestParam(name = "value", required = false) String value, - HttpServletRequest request) { + @RequestParam(name = "value", required = false) String value, HttpServletRequest request) { if (!ObjectUtils.isEmpty(key) && !ObjectUtils.isEmpty(value)) { request.getSession().setAttribute(key, value); } return "home"; } + } diff --git a/spring-session-samples/spring-session-sample-boot-redis-simple/src/integration-test/java/sample/BootTests.java b/spring-session-samples/spring-session-sample-boot-redis-simple/src/integration-test/java/sample/BootTests.java index b52edceb..5c2dabb2 100644 --- a/spring-session-samples/spring-session-sample-boot-redis-simple/src/integration-test/java/sample/BootTests.java +++ b/spring-session-samples/spring-session-sample-boot-redis-simple/src/integration-test/java/sample/BootTests.java @@ -86,8 +86,7 @@ class BootTests { @Bean public GenericContainer redisContainer() { - GenericContainer redisContainer = new GenericContainer(DOCKER_IMAGE) - .withExposedPorts(6379); + GenericContainer redisContainer = new GenericContainer(DOCKER_IMAGE).withExposedPorts(6379); redisContainer.start(); return redisContainer; } diff --git a/spring-session-samples/spring-session-sample-boot-redis-simple/src/integration-test/java/sample/pages/HomePage.java b/spring-session-samples/spring-session-sample-boot-redis-simple/src/integration-test/java/sample/pages/HomePage.java index 2e0c28e0..ab9aa87e 100644 --- a/spring-session-samples/spring-session-sample-boot-redis-simple/src/integration-test/java/sample/pages/HomePage.java +++ b/spring-session-samples/spring-session-sample-boot-redis-simple/src/integration-test/java/sample/pages/HomePage.java @@ -38,8 +38,7 @@ public class HomePage extends BasePage { } public void assertAt() { - assertThat(getDriver().getTitle()) - .isEqualTo("Spring Session Sample - Secured Content"); + assertThat(getDriver().getTitle()).isEqualTo("Spring Session Sample - Secured Content"); } public void containCookie(String cookieName) { @@ -53,8 +52,7 @@ public class HomePage extends BasePage { } public HomePage logout() { - WebElement logout = getDriver() - .findElement(By.cssSelector("input[type=\"submit\"]")); + WebElement logout = getDriver().findElement(By.cssSelector("input[type=\"submit\"]")); logout.click(); return PageFactory.initElements(getDriver(), HomePage.class); } diff --git a/spring-session-samples/spring-session-sample-boot-redis-simple/src/integration-test/java/sample/pages/LoginPage.java b/spring-session-samples/spring-session-sample-boot-redis-simple/src/integration-test/java/sample/pages/LoginPage.java index 99fd0fae..e72bba1e 100644 --- a/spring-session-samples/spring-session-sample-boot-redis-simple/src/integration-test/java/sample/pages/LoginPage.java +++ b/spring-session-samples/spring-session-sample-boot-redis-simple/src/integration-test/java/sample/pages/LoginPage.java @@ -60,6 +60,7 @@ public class LoginPage extends BasePage { this.button.click(); return PageFactory.initElements(getDriver(), page); } + } } diff --git a/spring-session-samples/spring-session-sample-boot-redis/src/integration-test/java/sample/BootTests.java b/spring-session-samples/spring-session-sample-boot-redis/src/integration-test/java/sample/BootTests.java index 8e3b8f03..aa03efeb 100644 --- a/spring-session-samples/spring-session-sample-boot-redis/src/integration-test/java/sample/BootTests.java +++ b/spring-session-samples/spring-session-sample-boot-redis/src/integration-test/java/sample/BootTests.java @@ -43,7 +43,7 @@ import org.springframework.test.web.servlet.htmlunit.webdriver.MockMvcHtmlUnitDr @ExtendWith(SpringExtension.class) @AutoConfigureMockMvc @SpringBootTest(webEnvironment = WebEnvironment.MOCK) -public class BootTests { +class BootTests { private static final String DOCKER_IMAGE = "redis:5.0.5"; @@ -53,23 +53,23 @@ public class BootTests { private WebDriver driver; @BeforeEach - public void setup() { + void setup() { this.driver = MockMvcHtmlUnitDriverBuilder.mockMvcSetup(this.mockMvc).build(); } @AfterEach - public void tearDown() { + void tearDown() { this.driver.quit(); } @Test - public void home() { + void home() { LoginPage login = HomePage.go(this.driver); login.assertAt(); } @Test - public void login() { + void login() { LoginPage login = HomePage.go(this.driver); HomePage home = login.form().login(HomePage.class); home.assertAt(); @@ -78,7 +78,7 @@ public class BootTests { } @Test - public void logout() { + void logout() { LoginPage login = HomePage.go(this.driver); HomePage home = login.form().login(HomePage.class); home.logout(); @@ -90,8 +90,7 @@ public class BootTests { @Bean public GenericContainer redisContainer() { - GenericContainer redisContainer = new GenericContainer(DOCKER_IMAGE) - .withExposedPorts(6379); + GenericContainer redisContainer = new GenericContainer(DOCKER_IMAGE).withExposedPorts(6379); redisContainer.start(); return redisContainer; } diff --git a/spring-session-samples/spring-session-sample-boot-redis/src/integration-test/java/sample/pages/LoginPage.java b/spring-session-samples/spring-session-sample-boot-redis/src/integration-test/java/sample/pages/LoginPage.java index b17c0d52..5cbb4e7a 100644 --- a/spring-session-samples/spring-session-sample-boot-redis/src/integration-test/java/sample/pages/LoginPage.java +++ b/spring-session-samples/spring-session-sample-boot-redis/src/integration-test/java/sample/pages/LoginPage.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,6 +64,7 @@ public class LoginPage extends BasePage { this.button.click(); return PageFactory.initElements(getDriver(), page); } + } } diff --git a/spring-session-samples/spring-session-sample-boot-redis/src/main/java/sample/Application.java b/spring-session-samples/spring-session-sample-boot-redis/src/main/java/sample/Application.java index aed31f40..d35a66ab 100644 --- a/spring-session-samples/spring-session-sample-boot-redis/src/main/java/sample/Application.java +++ b/spring-session-samples/spring-session-sample-boot-redis/src/main/java/sample/Application.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,4 +28,5 @@ public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } + } diff --git a/spring-session-samples/spring-session-sample-boot-webflux/src/integration-test/java/sample/AttributeTests.java b/spring-session-samples/spring-session-sample-boot-webflux/src/integration-test/java/sample/AttributeTests.java index 984e7f23..168ebd9e 100644 --- a/spring-session-samples/spring-session-sample-boot-webflux/src/integration-test/java/sample/AttributeTests.java +++ b/spring-session-samples/spring-session-sample-boot-webflux/src/integration-test/java/sample/AttributeTests.java @@ -45,7 +45,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ @ExtendWith(SpringExtension.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) -public class AttributeTests { +class AttributeTests { private static final String DOCKER_IMAGE = "redis:5.0.5"; @@ -55,29 +55,29 @@ public class AttributeTests { private WebDriver driver; @BeforeEach - public void setup() { + void setup() { this.driver = new HtmlUnitDriver(); } @AfterEach - public void tearDown() { + void tearDown() { this.driver.quit(); } @Test - public void home() { + void home() { HomePage home = HomePage.go(this.driver, this.port); home.assertAt(); } @Test - public void noAttributes() { + void noAttributes() { HomePage home = HomePage.go(this.driver, this.port); assertThat(home.attributes()).isEmpty(); } @Test - public void createAttribute() { + void createAttribute() { HomePage home = HomePage.go(this.driver, this.port); // @formatter:off home = home.form() @@ -98,8 +98,7 @@ public class AttributeTests { @Bean public GenericContainer redisContainer() { - GenericContainer redisContainer = new GenericContainer(DOCKER_IMAGE) - .withExposedPorts(6379); + GenericContainer redisContainer = new GenericContainer(DOCKER_IMAGE).withExposedPorts(6379); redisContainer.start(); return redisContainer; } diff --git a/spring-session-samples/spring-session-sample-boot-webflux/src/integration-test/java/sample/pages/HomePage.java b/spring-session-samples/spring-session-sample-boot-webflux/src/integration-test/java/sample/pages/HomePage.java index 6c2df7c9..c34a278a 100644 --- a/spring-session-samples/spring-session-sample-boot-webflux/src/integration-test/java/sample/pages/HomePage.java +++ b/spring-session-samples/spring-session-sample-boot-webflux/src/integration-test/java/sample/pages/HomePage.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,6 +77,7 @@ public class HomePage { } public class Form { + @FindBy(name = "attributeName") WebElement attributeName; @@ -104,9 +105,11 @@ public class HomePage { this.submit.click(); return PageFactory.initElements(HomePage.this.driver, page); } + } public static class Attribute { + @FindBy(xpath = ".//td[1]") WebElement attributeName; @@ -130,6 +133,7 @@ public class HomePage { public String getAttributeValue() { return this.attributeValue.getText(); } + } } diff --git a/spring-session-samples/spring-session-sample-boot-webflux/src/main/java/sample/SessionAttributeForm.java b/spring-session-samples/spring-session-sample-boot-webflux/src/main/java/sample/SessionAttributeForm.java index f7557853..0b69b270 100644 --- a/spring-session-samples/spring-session-sample-boot-webflux/src/main/java/sample/SessionAttributeForm.java +++ b/spring-session-samples/spring-session-sample-boot-webflux/src/main/java/sample/SessionAttributeForm.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,7 @@ package sample; * @since 5.0 */ public class SessionAttributeForm { + private String attributeName; private String attributeValue; @@ -40,4 +41,5 @@ public class SessionAttributeForm { public void setAttributeValue(String attributeValue) { this.attributeValue = attributeValue; } + } diff --git a/spring-session-samples/spring-session-sample-boot-webflux/src/main/java/sample/SessionController.java b/spring-session-samples/spring-session-sample-boot-webflux/src/main/java/sample/SessionController.java index 49616d02..d68f1ab0 100644 --- a/spring-session-samples/spring-session-sample-boot-webflux/src/main/java/sample/SessionController.java +++ b/spring-session-samples/spring-session-sample-boot-webflux/src/main/java/sample/SessionController.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,5 +40,6 @@ public class SessionController { } private static final long serialVersionUID = 2878267318695777395L; + } // tag::end[] diff --git a/spring-session-samples/spring-session-sample-boot-websocket/src/integration-test/java/sample/ApplicationTests.java b/spring-session-samples/spring-session-sample-boot-websocket/src/integration-test/java/sample/ApplicationTests.java index 08afdb6b..849506a9 100644 --- a/spring-session-samples/spring-session-sample-boot-websocket/src/integration-test/java/sample/ApplicationTests.java +++ b/spring-session-samples/spring-session-sample-boot-websocket/src/integration-test/java/sample/ApplicationTests.java @@ -50,7 +50,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; */ @ExtendWith(SpringExtension.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) -public class ApplicationTests { +class ApplicationTests { private static final String DOCKER_IMAGE = "redis:5.0.5"; @@ -61,14 +61,14 @@ public class ApplicationTests { private WebSocketHandler webSocketHandler; @Test - public void run() { + void run() { List transports = new ArrayList<>(2); transports.add(new WebSocketTransport(new StandardWebSocketClient())); transports.add(new RestTemplateXhrTransport()); SockJsClient sockJsClient = new SockJsClient(transports); - ListenableFuture wsSession = sockJsClient.doHandshake( - this.webSocketHandler, "ws://localhost:" + this.port + "/sockjs"); + ListenableFuture wsSession = sockJsClient.doHandshake(this.webSocketHandler, + "ws://localhost:" + this.port + "/sockjs"); assertThatExceptionOfType(ExecutionException.class) .isThrownBy(() -> wsSession.get().sendMessage(new TextMessage("a"))); @@ -79,8 +79,7 @@ public class ApplicationTests { @Bean public GenericContainer redisContainer() { - GenericContainer redisContainer = new GenericContainer(DOCKER_IMAGE) - .withExposedPorts(6379); + GenericContainer redisContainer = new GenericContainer(DOCKER_IMAGE).withExposedPorts(6379); redisContainer.start(); return redisContainer; } diff --git a/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/Application.java b/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/Application.java index 6157248a..d35a66ab 100644 --- a/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/Application.java +++ b/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/Application.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,4 +28,5 @@ public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } + } diff --git a/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/config/WebSocketConfig.java b/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/config/WebSocketConfig.java index 4d8caf1f..059c3e1d 100644 --- a/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/config/WebSocketConfig.java +++ b/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/config/WebSocketConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,12 +24,12 @@ import org.springframework.session.web.socket.config.annotation.AbstractSessionW import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; +// @formatter:off // tag::class[] @Configuration @EnableScheduling @EnableWebSocketMessageBroker -public class WebSocketConfig - extends AbstractSessionWebSocketMessageBrokerConfigurer { // <1> +public class WebSocketConfig extends AbstractSessionWebSocketMessageBrokerConfigurer { // <1> @Override protected void configureStompEndpoints(StompEndpointRegistry registry) { // <2> @@ -41,5 +41,7 @@ public class WebSocketConfig registry.enableSimpleBroker("/queue/", "/topic/"); registry.setApplicationDestinationPrefixes("/app"); } + } // end::class[] +// @formatter:on diff --git a/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/config/WebSocketHandlersConfig.java b/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/config/WebSocketHandlersConfig.java index 668c51c3..507979ea 100644 --- a/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/config/WebSocketHandlersConfig.java +++ b/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/config/WebSocketHandlersConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,16 +35,15 @@ import org.springframework.session.Session; public class WebSocketHandlersConfig { @Bean - public WebSocketConnectHandler webSocketConnectHandler( - SimpMessageSendingOperations messagingTemplate, + public WebSocketConnectHandler webSocketConnectHandler(SimpMessageSendingOperations messagingTemplate, ActiveWebSocketUserRepository repository) { return new WebSocketConnectHandler<>(messagingTemplate, repository); } @Bean - public WebSocketDisconnectHandler webSocketDisconnectHandler( - SimpMessageSendingOperations messagingTemplate, + public WebSocketDisconnectHandler webSocketDisconnectHandler(SimpMessageSendingOperations messagingTemplate, ActiveWebSocketUserRepository repository) { return new WebSocketDisconnectHandler<>(messagingTemplate, repository); } + } diff --git a/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/config/WebSocketSecurityConfig.java b/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/config/WebSocketSecurityConfig.java index 00034ee3..4361cc46 100644 --- a/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/config/WebSocketSecurityConfig.java +++ b/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/config/WebSocketSecurityConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,8 +24,7 @@ import org.springframework.security.config.annotation.web.socket.AbstractSecurit * @author Rob Winch */ @Configuration -public class WebSocketSecurityConfig - extends AbstractSecurityWebSocketMessageBrokerConfigurer { +public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer { // @formatter:off @Override @@ -36,4 +35,5 @@ public class WebSocketSecurityConfig .anyMessage().authenticated(); } // @formatter:on + } diff --git a/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/data/ActiveWebSocketUser.java b/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/data/ActiveWebSocketUser.java index 044d9e34..03b45640 100644 --- a/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/data/ActiveWebSocketUser.java +++ b/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/data/ActiveWebSocketUser.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +23,7 @@ import javax.persistence.Id; @Entity public class ActiveWebSocketUser { + @Id private String id; diff --git a/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/data/ActiveWebSocketUserRepository.java b/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/data/ActiveWebSocketUserRepository.java index 78c6486a..4151d23a 100644 --- a/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/data/ActiveWebSocketUserRepository.java +++ b/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/data/ActiveWebSocketUserRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,9 +21,9 @@ import java.util.List; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; -public interface ActiveWebSocketUserRepository - extends CrudRepository { +public interface ActiveWebSocketUserRepository extends CrudRepository { @Query("select DISTINCT(u.username) from ActiveWebSocketUser u where u.username != ?#{principal?.username}") List findAllActiveUsers(); + } diff --git a/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/data/InstantMessage.java b/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/data/InstantMessage.java index 60ea791c..ef5cfbf5 100644 --- a/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/data/InstantMessage.java +++ b/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/data/InstantMessage.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ package sample.data; import java.util.Calendar; public class InstantMessage { + private String to; private String from; diff --git a/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/data/User.java b/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/data/User.java index 5c7d9393..d815d2c8 100644 --- a/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/data/User.java +++ b/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/data/User.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -111,4 +111,5 @@ public class User implements Serializable { } private static final long serialVersionUID = 2738859149330833739L; + } diff --git a/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/data/UserRepository.java b/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/data/UserRepository.java index 6c60f050..edcbff6d 100644 --- a/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/data/UserRepository.java +++ b/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/data/UserRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,4 +27,5 @@ import org.springframework.data.repository.CrudRepository; public interface UserRepository extends CrudRepository { User findByEmail(String email); + } diff --git a/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/mvc/CsrfController.java b/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/mvc/CsrfController.java index 1c1283d5..a7bd4c24 100644 --- a/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/mvc/CsrfController.java +++ b/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/mvc/CsrfController.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,4 +27,5 @@ public class CsrfController { public CsrfToken csrf(CsrfToken token) { return token; } + } diff --git a/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/mvc/MessageController.java b/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/mvc/MessageController.java index 1a775927..4c7bef20 100644 --- a/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/mvc/MessageController.java +++ b/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/mvc/MessageController.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,7 +38,9 @@ import org.springframework.stereotype.Controller; */ @Controller public class MessageController { + private SimpMessageSendingOperations messagingTemplate; + private ActiveWebSocketUserRepository activeUserRepository; @Autowired @@ -59,4 +61,5 @@ public class MessageController { public List subscribeMessages() throws Exception { return this.activeUserRepository.findAllActiveUsers(); } + } diff --git a/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/security/UserRepositoryUserDetailsService.java b/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/security/UserRepositoryUserDetailsService.java index 897e96b7..a829e45a 100644 --- a/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/security/UserRepositoryUserDetailsService.java +++ b/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/security/UserRepositoryUserDetailsService.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,6 +35,7 @@ import org.springframework.stereotype.Service; */ @Service public class UserRepositoryUserDetailsService implements UserDetailsService { + private final UserRepository userRepository; @Autowired @@ -50,8 +51,7 @@ public class UserRepositoryUserDetailsService implements UserDetailsService { * (java.lang.String) */ @Override - public UserDetails loadUserByUsername(String username) - throws UsernameNotFoundException { + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = this.userRepository.findByEmail(username); if (user == null) { throw new UsernameNotFoundException("Could not find user " + username); @@ -96,5 +96,7 @@ public class UserRepositoryUserDetailsService implements UserDetailsService { } private static final long serialVersionUID = 5639683223516504866L; + } + } diff --git a/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/websocket/WebSocketConnectHandler.java b/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/websocket/WebSocketConnectHandler.java index ff41d09c..c7aa1182 100644 --- a/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/websocket/WebSocketConnectHandler.java +++ b/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/websocket/WebSocketConnectHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,9 +29,10 @@ import org.springframework.messaging.simp.SimpMessageHeaderAccessor; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.web.socket.messaging.SessionConnectEvent; -public class WebSocketConnectHandler - implements ApplicationListener { +public class WebSocketConnectHandler implements ApplicationListener { + private ActiveWebSocketUserRepository repository; + private SimpMessageSendingOperations messagingTemplate; public WebSocketConnectHandler(SimpMessageSendingOperations messagingTemplate, @@ -49,9 +50,8 @@ public class WebSocketConnectHandler return; } String id = SimpMessageHeaderAccessor.getSessionId(headers); - this.repository.save( - new ActiveWebSocketUser(id, user.getName(), Calendar.getInstance())); - this.messagingTemplate.convertAndSend("/topic/friends/signin", - Arrays.asList(user.getName())); + this.repository.save(new ActiveWebSocketUser(id, user.getName(), Calendar.getInstance())); + this.messagingTemplate.convertAndSend("/topic/friends/signin", Arrays.asList(user.getName())); } + } diff --git a/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/websocket/WebSocketDisconnectHandler.java b/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/websocket/WebSocketDisconnectHandler.java index f7384185..cd03f249 100644 --- a/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/websocket/WebSocketDisconnectHandler.java +++ b/spring-session-samples/spring-session-sample-boot-websocket/src/main/java/sample/websocket/WebSocketDisconnectHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,9 +24,10 @@ import org.springframework.context.ApplicationListener; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.web.socket.messaging.SessionDisconnectEvent; -public class WebSocketDisconnectHandler - implements ApplicationListener { +public class WebSocketDisconnectHandler implements ApplicationListener { + private ActiveWebSocketUserRepository repository; + private SimpMessageSendingOperations messagingTemplate; public WebSocketDisconnectHandler(SimpMessageSendingOperations messagingTemplate, @@ -44,8 +45,8 @@ public class WebSocketDisconnectHandler } this.repository.findById(id).ifPresent((user) -> { this.repository.deleteById(id); - this.messagingTemplate.convertAndSend("/topic/friends/signout", - Arrays.asList(user.getUsername())); + this.messagingTemplate.convertAndSend("/topic/friends/signout", Arrays.asList(user.getUsername())); }); } + } diff --git a/spring-session-samples/spring-session-sample-javaconfig-custom-cookie/src/integration-test/java/sample/AttributeTests.java b/spring-session-samples/spring-session-sample-javaconfig-custom-cookie/src/integration-test/java/sample/AttributeTests.java index a93598b5..6dc24a50 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-custom-cookie/src/integration-test/java/sample/AttributeTests.java +++ b/spring-session-samples/spring-session-sample-javaconfig-custom-cookie/src/integration-test/java/sample/AttributeTests.java @@ -32,34 +32,34 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Eddú Meléndez * @author Rob Winch */ -public class AttributeTests { +class AttributeTests { private WebDriver driver; @BeforeEach - public void setup() { + void setup() { this.driver = new HtmlUnitDriver(); } @AfterEach - public void tearDown() { + void tearDown() { this.driver.quit(); } @Test - public void home() { + void home() { HomePage home = HomePage.go(this.driver); home.assertAt(); } @Test - public void noAttributes() { + void noAttributes() { HomePage home = HomePage.go(this.driver); assertThat(home.attributes()).isEmpty(); } @Test - public void createAttribute() { + void createAttribute() { HomePage home = HomePage.go(this.driver); // @formatter:off home = home.form() diff --git a/spring-session-samples/spring-session-sample-javaconfig-custom-cookie/src/integration-test/java/sample/pages/HomePage.java b/spring-session-samples/spring-session-sample-javaconfig-custom-cookie/src/integration-test/java/sample/pages/HomePage.java index 2c40613a..c8604055 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-custom-cookie/src/integration-test/java/sample/pages/HomePage.java +++ b/spring-session-samples/spring-session-sample-javaconfig-custom-cookie/src/integration-test/java/sample/pages/HomePage.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,6 +77,7 @@ public class HomePage { } public class Form { + @FindBy(name = "attributeName") WebElement attributeName; @@ -104,9 +105,11 @@ public class HomePage { this.submit.click(); return PageFactory.initElements(HomePage.this.driver, page); } + } public static class Attribute { + @FindBy(xpath = ".//td[1]") WebElement attributeName; @@ -130,6 +133,7 @@ public class HomePage { public String getAttributeValue() { return this.attributeValue.getText(); } + } } diff --git a/spring-session-samples/spring-session-sample-javaconfig-custom-cookie/src/main/java/sample/Config.java b/spring-session-samples/spring-session-sample-javaconfig-custom-cookie/src/main/java/sample/Config.java index e185f0fb..28acd806 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-custom-cookie/src/main/java/sample/Config.java +++ b/spring-session-samples/spring-session-sample-javaconfig-custom-cookie/src/main/java/sample/Config.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,4 +42,5 @@ public class Config { return serializer; } // end::cookie-serializer[] + } diff --git a/spring-session-samples/spring-session-sample-javaconfig-custom-cookie/src/main/java/sample/EmbeddedRedisConfig.java b/spring-session-samples/spring-session-sample-javaconfig-custom-cookie/src/main/java/sample/EmbeddedRedisConfig.java index 653eceac..c1c334e0 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-custom-cookie/src/main/java/sample/EmbeddedRedisConfig.java +++ b/spring-session-samples/spring-session-sample-javaconfig-custom-cookie/src/main/java/sample/EmbeddedRedisConfig.java @@ -32,8 +32,7 @@ public class EmbeddedRedisConfig { @Bean public GenericContainer redisContainer() { - GenericContainer redisContainer = new GenericContainer(DOCKER_IMAGE) - .withExposedPorts(6379); + GenericContainer redisContainer = new GenericContainer(DOCKER_IMAGE).withExposedPorts(6379); redisContainer.start(); return redisContainer; } diff --git a/spring-session-samples/spring-session-sample-javaconfig-custom-cookie/src/main/java/sample/Initializer.java b/spring-session-samples/spring-session-sample-javaconfig-custom-cookie/src/main/java/sample/Initializer.java index 7654db28..ee9f478a 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-custom-cookie/src/main/java/sample/Initializer.java +++ b/spring-session-samples/spring-session-sample-javaconfig-custom-cookie/src/main/java/sample/Initializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,11 +18,14 @@ package sample; import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer; +// @formatter:off // tag::class[] public class Initializer extends AbstractHttpSessionApplicationInitializer { // <1> public Initializer() { super(Config.class); // <2> } + } // end::class[] +// @formatter:on diff --git a/spring-session-samples/spring-session-sample-javaconfig-custom-cookie/src/main/java/sample/SessionServlet.java b/spring-session-samples/spring-session-sample-javaconfig-custom-cookie/src/main/java/sample/SessionServlet.java index 4c7ce466..be7fbf62 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-custom-cookie/src/main/java/sample/SessionServlet.java +++ b/spring-session-samples/spring-session-sample-javaconfig-custom-cookie/src/main/java/sample/SessionServlet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,8 +29,7 @@ import javax.servlet.http.HttpServletResponse; public class SessionServlet extends HttpServlet { @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String attributeName = req.getParameter("attributeName"); String attributeValue = req.getParameter("attributeValue"); req.getSession().setAttribute(attributeName, attributeValue); @@ -38,5 +37,6 @@ public class SessionServlet extends HttpServlet { } private static final long serialVersionUID = 2878267318695777395L; + } // tag::end[] diff --git a/spring-session-samples/spring-session-sample-javaconfig-hazelcast/src/integration-test/java/sample/HazelcastSpringTests.java b/spring-session-samples/spring-session-sample-javaconfig-hazelcast/src/integration-test/java/sample/HazelcastSpringTests.java index effcbe4c..e5d08caa 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-hazelcast/src/integration-test/java/sample/HazelcastSpringTests.java +++ b/spring-session-samples/spring-session-sample-javaconfig-hazelcast/src/integration-test/java/sample/HazelcastSpringTests.java @@ -28,28 +28,28 @@ import sample.pages.LoginPage; * @author Eddú Meléndez * @author Rob Winch */ -public class HazelcastSpringTests { +class HazelcastSpringTests { private WebDriver driver; @BeforeEach - public void setup() { + void setup() { this.driver = new HtmlUnitDriver(); } @AfterEach - public void tearDown() { + void tearDown() { this.driver.quit(); } @Test - public void goHomeRedirectLoginPage() { + void goHomeRedirectLoginPage() { LoginPage login = HomePage.go(this.driver); login.assertAt(); } @Test - public void login() { + void login() { LoginPage login = HomePage.go(this.driver); login.assertAt(); HomePage home = login.form().login(HomePage.class); diff --git a/spring-session-samples/spring-session-sample-javaconfig-hazelcast/src/integration-test/java/sample/pages/LoginPage.java b/spring-session-samples/spring-session-sample-javaconfig-hazelcast/src/integration-test/java/sample/pages/LoginPage.java index b17c0d52..5cbb4e7a 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-hazelcast/src/integration-test/java/sample/pages/LoginPage.java +++ b/spring-session-samples/spring-session-sample-javaconfig-hazelcast/src/integration-test/java/sample/pages/LoginPage.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,6 +64,7 @@ public class LoginPage extends BasePage { this.button.click(); return PageFactory.initElements(getDriver(), page); } + } } diff --git a/spring-session-samples/spring-session-sample-javaconfig-hazelcast/src/main/java/sample/ObjectStreamSerializer.java b/spring-session-samples/spring-session-sample-javaconfig-hazelcast/src/main/java/sample/ObjectStreamSerializer.java index 1adfd3ab..b275313e 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-hazelcast/src/main/java/sample/ObjectStreamSerializer.java +++ b/spring-session-samples/spring-session-sample-javaconfig-hazelcast/src/main/java/sample/ObjectStreamSerializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,14 +36,14 @@ import com.hazelcast.nio.serialization.StreamSerializer; * */ public class ObjectStreamSerializer implements StreamSerializer { + @Override public int getTypeId() { return 2; } @Override - public void write(ObjectDataOutput objectDataOutput, Object object) - throws IOException { + public void write(ObjectDataOutput objectDataOutput, Object object) throws IOException { ObjectOutputStream out = new ObjectOutputStream((OutputStream) objectDataOutput); out.writeObject(object); out.flush(); diff --git a/spring-session-samples/spring-session-sample-javaconfig-hazelcast/src/main/java/sample/SecurityConfig.java b/spring-session-samples/spring-session-sample-javaconfig-hazelcast/src/main/java/sample/SecurityConfig.java index 89142199..41acbae6 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-hazelcast/src/main/java/sample/SecurityConfig.java +++ b/spring-session-samples/spring-session-sample-javaconfig-hazelcast/src/main/java/sample/SecurityConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,9 +26,11 @@ import org.springframework.security.core.userdetails.User; */ @EnableWebSecurity public class SecurityConfig { + @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication().withUser(User.withUsername("user") - .password("{noop}password").roles("USER").build()); + auth.inMemoryAuthentication() + .withUser(User.withUsername("user").password("{noop}password").roles("USER").build()); } + } diff --git a/spring-session-samples/spring-session-sample-javaconfig-hazelcast/src/main/java/sample/SecurityInitializer.java b/spring-session-samples/spring-session-sample-javaconfig-hazelcast/src/main/java/sample/SecurityInitializer.java index bf92b587..dbe12835 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-hazelcast/src/main/java/sample/SecurityInitializer.java +++ b/spring-session-samples/spring-session-sample-javaconfig-hazelcast/src/main/java/sample/SecurityInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,5 +24,6 @@ public class SecurityInitializer extends AbstractSecurityWebApplicationInitializ public SecurityInitializer() { super(SecurityConfig.class, SessionConfig.class); } + } // end::class[] diff --git a/spring-session-samples/spring-session-sample-javaconfig-hazelcast/src/main/java/sample/SessionConfig.java b/spring-session-samples/spring-session-sample-javaconfig-hazelcast/src/main/java/sample/SessionConfig.java index a048dc13..961e8807 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-hazelcast/src/main/java/sample/SessionConfig.java +++ b/spring-session-samples/spring-session-sample-javaconfig-hazelcast/src/main/java/sample/SessionConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,27 +41,21 @@ public class SessionConfig { int port = SocketUtils.findAvailableTcpPort(); - config.getNetworkConfig() - .setPort(port) - .getJoin().getMulticastConfig().setEnabled(false); + config.getNetworkConfig().setPort(port).getJoin().getMulticastConfig().setEnabled(false); System.out.println("Hazelcast port #: " + port); - SerializerConfig serializer = new SerializerConfig() - .setImplementation(new ObjectStreamSerializer()) + SerializerConfig serializer = new SerializerConfig().setImplementation(new ObjectStreamSerializer()) .setTypeClass(Object.class); - config.getSerializationConfig() - .addSerializerConfig(serializer); + config.getSerializationConfig().addSerializerConfig(serializer); MapAttributeConfig attributeConfig = new MapAttributeConfig() .setName(HazelcastSessionRepository.PRINCIPAL_NAME_ATTRIBUTE) .setExtractor(PrincipalNameExtractor.class.getName()); - config.getMapConfig(HazelcastSessionRepository.DEFAULT_SESSION_MAP_NAME) - .addMapAttributeConfig(attributeConfig) - .addMapIndexConfig(new MapIndexConfig( - HazelcastSessionRepository.PRINCIPAL_NAME_ATTRIBUTE, false)); + config.getMapConfig(HazelcastSessionRepository.DEFAULT_SESSION_MAP_NAME).addMapAttributeConfig(attributeConfig) + .addMapIndexConfig(new MapIndexConfig(HazelcastSessionRepository.PRINCIPAL_NAME_ATTRIBUTE, false)); return Hazelcast.newHazelcastInstance(config); } diff --git a/spring-session-samples/spring-session-sample-javaconfig-hazelcast/src/main/java/sample/SessionServlet.java b/spring-session-samples/spring-session-sample-javaconfig-hazelcast/src/main/java/sample/SessionServlet.java index 02967837..d65debe1 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-hazelcast/src/main/java/sample/SessionServlet.java +++ b/spring-session-samples/spring-session-sample-javaconfig-hazelcast/src/main/java/sample/SessionServlet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,8 +28,7 @@ import javax.servlet.http.HttpServletResponse; public class SessionServlet extends HttpServlet { @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String attributeName = req.getParameter("attributeName"); String attributeValue = req.getParameter("attributeValue"); req.getSession().setAttribute(attributeName, attributeValue); @@ -37,4 +36,5 @@ public class SessionServlet extends HttpServlet { } private static final long serialVersionUID = 2878267318695777395L; + } diff --git a/spring-session-samples/spring-session-sample-javaconfig-jdbc/src/integration-test/java/sample/AttributeTests.java b/spring-session-samples/spring-session-sample-javaconfig-jdbc/src/integration-test/java/sample/AttributeTests.java index a93598b5..6dc24a50 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-jdbc/src/integration-test/java/sample/AttributeTests.java +++ b/spring-session-samples/spring-session-sample-javaconfig-jdbc/src/integration-test/java/sample/AttributeTests.java @@ -32,34 +32,34 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Eddú Meléndez * @author Rob Winch */ -public class AttributeTests { +class AttributeTests { private WebDriver driver; @BeforeEach - public void setup() { + void setup() { this.driver = new HtmlUnitDriver(); } @AfterEach - public void tearDown() { + void tearDown() { this.driver.quit(); } @Test - public void home() { + void home() { HomePage home = HomePage.go(this.driver); home.assertAt(); } @Test - public void noAttributes() { + void noAttributes() { HomePage home = HomePage.go(this.driver); assertThat(home.attributes()).isEmpty(); } @Test - public void createAttribute() { + void createAttribute() { HomePage home = HomePage.go(this.driver); // @formatter:off home = home.form() diff --git a/spring-session-samples/spring-session-sample-javaconfig-jdbc/src/integration-test/java/sample/pages/HomePage.java b/spring-session-samples/spring-session-sample-javaconfig-jdbc/src/integration-test/java/sample/pages/HomePage.java index 2c40613a..c8604055 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-jdbc/src/integration-test/java/sample/pages/HomePage.java +++ b/spring-session-samples/spring-session-sample-javaconfig-jdbc/src/integration-test/java/sample/pages/HomePage.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,6 +77,7 @@ public class HomePage { } public class Form { + @FindBy(name = "attributeName") WebElement attributeName; @@ -104,9 +105,11 @@ public class HomePage { this.submit.click(); return PageFactory.initElements(HomePage.this.driver, page); } + } public static class Attribute { + @FindBy(xpath = ".//td[1]") WebElement attributeName; @@ -130,6 +133,7 @@ public class HomePage { public String getAttributeValue() { return this.attributeValue.getText(); } + } } diff --git a/spring-session-samples/spring-session-sample-javaconfig-jdbc/src/main/java/sample/Config.java b/spring-session-samples/spring-session-sample-javaconfig-jdbc/src/main/java/sample/Config.java index 1e4409d1..7eadf261 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-jdbc/src/main/java/sample/Config.java +++ b/spring-session-samples/spring-session-sample-javaconfig-jdbc/src/main/java/sample/Config.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,7 @@ public class Config { @Bean public EmbeddedDatabase dataSource() { return new EmbeddedDatabaseBuilder() // <2> - .setType(EmbeddedDatabaseType.H2) - .addScript("org/springframework/session/jdbc/schema-h2.sql").build(); + .setType(EmbeddedDatabaseType.H2).addScript("org/springframework/session/jdbc/schema-h2.sql").build(); } @Bean diff --git a/spring-session-samples/spring-session-sample-javaconfig-jdbc/src/main/java/sample/Initializer.java b/spring-session-samples/spring-session-sample-javaconfig-jdbc/src/main/java/sample/Initializer.java index c1de883a..0203a5f0 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-jdbc/src/main/java/sample/Initializer.java +++ b/spring-session-samples/spring-session-sample-javaconfig-jdbc/src/main/java/sample/Initializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,11 +17,14 @@ package sample; import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer; +// @formatter:off // tag::class[] public class Initializer extends AbstractHttpSessionApplicationInitializer { // <1> public Initializer() { super(Config.class); // <2> } + } // end::class[] +// @formatter:on diff --git a/spring-session-samples/spring-session-sample-javaconfig-jdbc/src/main/java/sample/SessionServlet.java b/spring-session-samples/spring-session-sample-javaconfig-jdbc/src/main/java/sample/SessionServlet.java index 4016f955..4765a51f 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-jdbc/src/main/java/sample/SessionServlet.java +++ b/spring-session-samples/spring-session-sample-javaconfig-jdbc/src/main/java/sample/SessionServlet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,8 +28,7 @@ import javax.servlet.http.HttpServletResponse; public class SessionServlet extends HttpServlet { @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String attributeName = req.getParameter("attributeName"); String attributeValue = req.getParameter("attributeValue"); req.getSession().setAttribute(attributeName, attributeValue); @@ -37,5 +36,6 @@ public class SessionServlet extends HttpServlet { } private static final long serialVersionUID = 2878267318695777395L; + } // tag::end[] diff --git a/spring-session-samples/spring-session-sample-javaconfig-redis/src/integration-test/java/sample/AttributeTests.java b/spring-session-samples/spring-session-sample-javaconfig-redis/src/integration-test/java/sample/AttributeTests.java index a93598b5..6dc24a50 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-redis/src/integration-test/java/sample/AttributeTests.java +++ b/spring-session-samples/spring-session-sample-javaconfig-redis/src/integration-test/java/sample/AttributeTests.java @@ -32,34 +32,34 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Eddú Meléndez * @author Rob Winch */ -public class AttributeTests { +class AttributeTests { private WebDriver driver; @BeforeEach - public void setup() { + void setup() { this.driver = new HtmlUnitDriver(); } @AfterEach - public void tearDown() { + void tearDown() { this.driver.quit(); } @Test - public void home() { + void home() { HomePage home = HomePage.go(this.driver); home.assertAt(); } @Test - public void noAttributes() { + void noAttributes() { HomePage home = HomePage.go(this.driver); assertThat(home.attributes()).isEmpty(); } @Test - public void createAttribute() { + void createAttribute() { HomePage home = HomePage.go(this.driver); // @formatter:off home = home.form() diff --git a/spring-session-samples/spring-session-sample-javaconfig-redis/src/integration-test/java/sample/pages/HomePage.java b/spring-session-samples/spring-session-sample-javaconfig-redis/src/integration-test/java/sample/pages/HomePage.java index 2c40613a..c8604055 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-redis/src/integration-test/java/sample/pages/HomePage.java +++ b/spring-session-samples/spring-session-sample-javaconfig-redis/src/integration-test/java/sample/pages/HomePage.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,6 +77,7 @@ public class HomePage { } public class Form { + @FindBy(name = "attributeName") WebElement attributeName; @@ -104,9 +105,11 @@ public class HomePage { this.submit.click(); return PageFactory.initElements(HomePage.this.driver, page); } + } public static class Attribute { + @FindBy(xpath = ".//td[1]") WebElement attributeName; @@ -130,6 +133,7 @@ public class HomePage { public String getAttributeValue() { return this.attributeValue.getText(); } + } } diff --git a/spring-session-samples/spring-session-sample-javaconfig-redis/src/main/java/sample/Config.java b/spring-session-samples/spring-session-sample-javaconfig-redis/src/main/java/sample/Config.java index 0d218d9c..366eb84b 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-redis/src/main/java/sample/Config.java +++ b/spring-session-samples/spring-session-sample-javaconfig-redis/src/main/java/sample/Config.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,5 +30,6 @@ public class Config { public LettuceConnectionFactory connectionFactory() { return new LettuceConnectionFactory(); // <2> } + } // end::class[] diff --git a/spring-session-samples/spring-session-sample-javaconfig-redis/src/main/java/sample/EmbeddedRedisConfig.java b/spring-session-samples/spring-session-sample-javaconfig-redis/src/main/java/sample/EmbeddedRedisConfig.java index 653eceac..c1c334e0 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-redis/src/main/java/sample/EmbeddedRedisConfig.java +++ b/spring-session-samples/spring-session-sample-javaconfig-redis/src/main/java/sample/EmbeddedRedisConfig.java @@ -32,8 +32,7 @@ public class EmbeddedRedisConfig { @Bean public GenericContainer redisContainer() { - GenericContainer redisContainer = new GenericContainer(DOCKER_IMAGE) - .withExposedPorts(6379); + GenericContainer redisContainer = new GenericContainer(DOCKER_IMAGE).withExposedPorts(6379); redisContainer.start(); return redisContainer; } diff --git a/spring-session-samples/spring-session-sample-javaconfig-redis/src/main/java/sample/Initializer.java b/spring-session-samples/spring-session-sample-javaconfig-redis/src/main/java/sample/Initializer.java index 7654db28..ee9f478a 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-redis/src/main/java/sample/Initializer.java +++ b/spring-session-samples/spring-session-sample-javaconfig-redis/src/main/java/sample/Initializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,11 +18,14 @@ package sample; import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer; +// @formatter:off // tag::class[] public class Initializer extends AbstractHttpSessionApplicationInitializer { // <1> public Initializer() { super(Config.class); // <2> } + } // end::class[] +// @formatter:on diff --git a/spring-session-samples/spring-session-sample-javaconfig-redis/src/main/java/sample/SessionServlet.java b/spring-session-samples/spring-session-sample-javaconfig-redis/src/main/java/sample/SessionServlet.java index 4c7ce466..be7fbf62 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-redis/src/main/java/sample/SessionServlet.java +++ b/spring-session-samples/spring-session-sample-javaconfig-redis/src/main/java/sample/SessionServlet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,8 +29,7 @@ import javax.servlet.http.HttpServletResponse; public class SessionServlet extends HttpServlet { @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String attributeName = req.getParameter("attributeName"); String attributeValue = req.getParameter("attributeValue"); req.getSession().setAttribute(attributeName, attributeValue); @@ -38,5 +37,6 @@ public class SessionServlet extends HttpServlet { } private static final long serialVersionUID = 2878267318695777395L; + } // tag::end[] diff --git a/spring-session-samples/spring-session-sample-javaconfig-rest/src/integration-test/java/rest/RestMockMvcTests.java b/spring-session-samples/spring-session-sample-javaconfig-rest/src/integration-test/java/rest/RestMockMvcTests.java index 9bffa200..c6417d2f 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-rest/src/integration-test/java/rest/RestMockMvcTests.java +++ b/spring-session-samples/spring-session-sample-javaconfig-rest/src/integration-test/java/rest/RestMockMvcTests.java @@ -49,10 +49,9 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @ExtendWith(SpringExtension.class) -@ContextConfiguration(classes = { RestMockMvcTests.Config.class, SecurityConfig.class, - MvcConfig.class }) +@ContextConfiguration(classes = { RestMockMvcTests.Config.class, SecurityConfig.class, MvcConfig.class }) @WebAppConfiguration -public class RestMockMvcTests { +class RestMockMvcTests { private static final String DOCKER_IMAGE = "redis:5.0.5"; @@ -65,27 +64,26 @@ public class RestMockMvcTests { private MockMvc mvc; @BeforeEach - public void setup() { + void setup() { this.mvc = MockMvcBuilders.webAppContextSetup(this.context).alwaysDo(print()) .addFilters(this.sessionRepositoryFilter).apply(springSecurity()).build(); } @Test - public void noSessionOnNoCredentials() throws Exception { + void noSessionOnNoCredentials() throws Exception { this.mvc.perform(get("/")).andExpect(header().doesNotExist("X-Auth-Token")) .andExpect(status().isUnauthorized()); } @WithMockUser @Test - public void autheticatedAnnotation() throws Exception { + void autheticatedAnnotation() throws Exception { this.mvc.perform(get("/")).andExpect(content().string("{\"username\":\"user\"}")); } @Test - public void autheticatedRequestPostProcessor() throws Exception { - this.mvc.perform(get("/").with(user("user"))) - .andExpect(content().string("{\"username\":\"user\"}")); + void autheticatedRequestPostProcessor() throws Exception { + this.mvc.perform(get("/").with(user("user"))).andExpect(content().string("{\"username\":\"user\"}")); } @Configuration @@ -94,8 +92,7 @@ public class RestMockMvcTests { @Bean public GenericContainer redisContainer() { - GenericContainer redisContainer = new GenericContainer(DOCKER_IMAGE) - .withExposedPorts(6379); + GenericContainer redisContainer = new GenericContainer(DOCKER_IMAGE).withExposedPorts(6379); redisContainer.start(); return redisContainer; } diff --git a/spring-session-samples/spring-session-sample-javaconfig-rest/src/integration-test/java/sample/RestTests.java b/spring-session-samples/spring-session-sample-javaconfig-rest/src/integration-test/java/sample/RestTests.java index 36a331d2..c7e9f243 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-rest/src/integration-test/java/sample/RestTests.java +++ b/spring-session-samples/spring-session-sample-javaconfig-rest/src/integration-test/java/sample/RestTests.java @@ -37,10 +37,12 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Pool Dolorier */ -public class RestTests { +class RestTests { private static final String AUTHORIZATION = "Authorization"; + private static final String BASIC = "Basic "; + private static final String X_AUTH_TOKEN = "X-Auth-Token"; private RestTemplate restTemplate; @@ -48,72 +50,65 @@ public class RestTests { private String baseUrl; @BeforeEach - public void setUp() { + void setUp() { this.baseUrl = "http://localhost:" + System.getProperty("app.port"); this.restTemplate = new RestTemplate(); } @Test - public void unauthenticatedUserSentToLogInPage() { + void unauthenticatedUserSentToLogInPage() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); assertThatExceptionOfType(HttpClientErrorException.class) .isThrownBy(() -> getForUser(this.baseUrl + "/", headers, String.class)) - .satisfies((e) -> assertThat(e.getStatusCode()) - .isEqualTo(HttpStatus.UNAUTHORIZED)); + .satisfies((e) -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED)); } @Test - public void authenticateWithBasicWorks() { + void authenticateWithBasicWorks() { String auth = getAuth("user", "password"); HttpHeaders headers = getHttpHeaders(); headers.set(AUTHORIZATION, BASIC + auth); - ResponseEntity entity = getForUser(this.baseUrl + "/", - headers, User.class); + ResponseEntity entity = getForUser(this.baseUrl + "/", headers, User.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getHeaders().containsKey(X_AUTH_TOKEN)).isTrue(); assertThat(entity.getBody().getUsername()).isEqualTo("user"); } @Test - public void authenticateWithXAuthTokenWorks() { + void authenticateWithXAuthTokenWorks() { String auth = getAuth("user", "password"); HttpHeaders headers = getHttpHeaders(); headers.set(AUTHORIZATION, BASIC + auth); - ResponseEntity entity = getForUser(this.baseUrl + "/", - headers, User.class); + ResponseEntity entity = getForUser(this.baseUrl + "/", headers, User.class); String token = entity.getHeaders().getFirst(X_AUTH_TOKEN); HttpHeaders authTokenHeader = new HttpHeaders(); authTokenHeader.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); authTokenHeader.set(X_AUTH_TOKEN, token); - ResponseEntity authTokenResponse = getForUser(this.baseUrl + "/", - authTokenHeader, User.class); + ResponseEntity authTokenResponse = getForUser(this.baseUrl + "/", authTokenHeader, User.class); assertThat(authTokenResponse.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(authTokenResponse.getBody().getUsername()).isEqualTo("user"); } @Test - public void logout() { + void logout() { String auth = getAuth("user", "password"); HttpHeaders headers = getHttpHeaders(); headers.set(AUTHORIZATION, BASIC + auth); - ResponseEntity entity = getForUser(this.baseUrl + "/", - headers, User.class); + ResponseEntity entity = getForUser(this.baseUrl + "/", headers, User.class); String token = entity.getHeaders().getFirst(X_AUTH_TOKEN); HttpHeaders logoutHeader = getHttpHeaders(); logoutHeader.set(X_AUTH_TOKEN, token); - ResponseEntity logoutResponse = getForUser(this.baseUrl + "/logout", - logoutHeader, User.class); + ResponseEntity logoutResponse = getForUser(this.baseUrl + "/logout", logoutHeader, User.class); assertThat(logoutResponse.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT); } private ResponseEntity getForUser(String resourceUrl, HttpHeaders headers, Class type) { - return this.restTemplate.exchange(resourceUrl, - HttpMethod.GET, new HttpEntity(headers), type); + return this.restTemplate.exchange(resourceUrl, HttpMethod.GET, new HttpEntity(headers), type); } private HttpHeaders getHttpHeaders() { @@ -126,4 +121,5 @@ public class RestTests { String auth = user + ":" + password; return Base64.getEncoder().encodeToString(auth.getBytes()); } + } diff --git a/spring-session-samples/spring-session-sample-javaconfig-rest/src/integration-test/java/sample/User.java b/spring-session-samples/spring-session-sample-javaconfig-rest/src/integration-test/java/sample/User.java index 287a646f..5c53924d 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-rest/src/integration-test/java/sample/User.java +++ b/spring-session-samples/spring-session-sample-javaconfig-rest/src/integration-test/java/sample/User.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,4 +30,5 @@ public class User { public void setUsername(String username) { this.username = username; } + } diff --git a/spring-session-samples/spring-session-sample-javaconfig-rest/src/main/java/sample/EmbeddedRedisConfig.java b/spring-session-samples/spring-session-sample-javaconfig-rest/src/main/java/sample/EmbeddedRedisConfig.java index 653eceac..c1c334e0 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-rest/src/main/java/sample/EmbeddedRedisConfig.java +++ b/spring-session-samples/spring-session-sample-javaconfig-rest/src/main/java/sample/EmbeddedRedisConfig.java @@ -32,8 +32,7 @@ public class EmbeddedRedisConfig { @Bean public GenericContainer redisContainer() { - GenericContainer redisContainer = new GenericContainer(DOCKER_IMAGE) - .withExposedPorts(6379); + GenericContainer redisContainer = new GenericContainer(DOCKER_IMAGE).withExposedPorts(6379); redisContainer.start(); return redisContainer; } diff --git a/spring-session-samples/spring-session-sample-javaconfig-rest/src/main/java/sample/HttpSessionConfig.java b/spring-session-samples/spring-session-sample-javaconfig-rest/src/main/java/sample/HttpSessionConfig.java index c9d2c02f..490b4c59 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-rest/src/main/java/sample/HttpSessionConfig.java +++ b/spring-session-samples/spring-session-sample-javaconfig-rest/src/main/java/sample/HttpSessionConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,5 +39,6 @@ public class HttpSessionConfig { public HttpSessionIdResolver httpSessionIdResolver() { return HeaderHttpSessionIdResolver.xAuthToken(); // <3> } + } // end::class[] diff --git a/spring-session-samples/spring-session-sample-javaconfig-rest/src/main/java/sample/SecurityConfig.java b/spring-session-samples/spring-session-sample-javaconfig-rest/src/main/java/sample/SecurityConfig.java index 13b28e95..5844d675 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-rest/src/main/java/sample/SecurityConfig.java +++ b/spring-session-samples/spring-session-sample-javaconfig-rest/src/main/java/sample/SecurityConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,7 +43,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication().withUser(User.withUsername("user") - .password("{noop}password").roles("USER").build()); + auth.inMemoryAuthentication() + .withUser(User.withUsername("user").password("{noop}password").roles("USER").build()); } + } diff --git a/spring-session-samples/spring-session-sample-javaconfig-rest/src/main/java/sample/mvc/MvcConfig.java b/spring-session-samples/spring-session-sample-javaconfig-rest/src/main/java/sample/mvc/MvcConfig.java index 9a427604..7f69a440 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-rest/src/main/java/sample/mvc/MvcConfig.java +++ b/spring-session-samples/spring-session-sample-javaconfig-rest/src/main/java/sample/mvc/MvcConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,4 +27,5 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc; @EnableWebMvc @ComponentScan public class MvcConfig { + } diff --git a/spring-session-samples/spring-session-sample-javaconfig-rest/src/main/java/sample/mvc/MvcInitializer.java b/spring-session-samples/spring-session-sample-javaconfig-rest/src/main/java/sample/mvc/MvcInitializer.java index b04ad7dd..79dabcf4 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-rest/src/main/java/sample/mvc/MvcInitializer.java +++ b/spring-session-samples/spring-session-sample-javaconfig-rest/src/main/java/sample/mvc/MvcInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,7 @@ import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatche * @author Rob Winch */ public class MvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { + // tag::config[] @Override protected Class[] getRootConfigClasses() { @@ -41,4 +42,5 @@ public class MvcInitializer extends AbstractAnnotationConfigDispatcherServletIni protected String[] getServletMappings() { return new String[] { "/" }; } + } diff --git a/spring-session-samples/spring-session-sample-javaconfig-rest/src/main/java/sample/mvc/RestDemoController.java b/spring-session-samples/spring-session-sample-javaconfig-rest/src/main/java/sample/mvc/RestDemoController.java index bf1242cb..35591fed 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-rest/src/main/java/sample/mvc/RestDemoController.java +++ b/spring-session-samples/spring-session-sample-javaconfig-rest/src/main/java/sample/mvc/RestDemoController.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,4 +45,5 @@ public class RestDemoController { public void logout(HttpSession session) { session.invalidate(); } + } diff --git a/spring-session-samples/spring-session-sample-javaconfig-security/src/integration-test/java/sample/SecurityTests.java b/spring-session-samples/spring-session-sample-javaconfig-security/src/integration-test/java/sample/SecurityTests.java index e9a00777..0979bcc5 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-security/src/integration-test/java/sample/SecurityTests.java +++ b/spring-session-samples/spring-session-sample-javaconfig-security/src/integration-test/java/sample/SecurityTests.java @@ -32,32 +32,31 @@ import sample.pages.LoginPage; import static org.assertj.core.api.Assertions.assertThat; /** - * * @author Pool Dolorier */ -public class SecurityTests { +class SecurityTests { private WebDriver driver; @BeforeEach - public void setUp() { + void setUp() { this.driver = new HtmlUnitDriver(); } @AfterEach - public void tearDown() { + void tearDown() { this.driver.quit(); } @Test - public void unauthenticatedUserSentToLogInPage() { + void unauthenticatedUserSentToLogInPage() { HomePage homePage = HomePage.go(this.driver); LoginPage loginPage = homePage.unauthenticated(); loginPage.assertAt(); } @Test - public void logInViewsHomePage() { + void logInViewsHomePage() { LoginPage loginPage = LoginPage.go(this.driver); HomePage homePage = loginPage.login("user", "password"); homePage.assertAt(); @@ -69,7 +68,7 @@ public class SecurityTests { } @Test - public void logOutSuccess() { + void logOutSuccess() { LoginPage loginPage = LoginPage.go(this.driver); HomePage homePage = loginPage.login("user", "password"); LoginPage successLogoutPage = homePage.logout(); @@ -77,7 +76,7 @@ public class SecurityTests { } @Test - public void loggedOutUserSentToLoginPage() { + void loggedOutUserSentToLoginPage() { LoginPage loginPage = LoginPage.go(this.driver); HomePage homePage = loginPage.login("user", "password"); homePage.logout(); @@ -85,4 +84,5 @@ public class SecurityTests { LoginPage backLoginPage = backHomePage.unauthenticated(); backLoginPage.assertAt(); } + } diff --git a/spring-session-samples/spring-session-sample-javaconfig-security/src/integration-test/java/sample/pages/BasePage.java b/spring-session-samples/spring-session-sample-javaconfig-security/src/integration-test/java/sample/pages/BasePage.java index 56e481ee..e12281ec 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-security/src/integration-test/java/sample/pages/BasePage.java +++ b/spring-session-samples/spring-session-sample-javaconfig-security/src/integration-test/java/sample/pages/BasePage.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,6 @@ package sample.pages; import org.openqa.selenium.WebDriver; /** - * * @author Pool Dolorier */ public abstract class BasePage { @@ -38,4 +37,5 @@ public abstract class BasePage { String baseUrl = "http://localhost:" + System.getProperty("app.port"); driver.get(baseUrl + get); } + } diff --git a/spring-session-samples/spring-session-sample-javaconfig-security/src/integration-test/java/sample/pages/HomePage.java b/spring-session-samples/spring-session-sample-javaconfig-security/src/integration-test/java/sample/pages/HomePage.java index 9a213b92..39786d72 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-security/src/integration-test/java/sample/pages/HomePage.java +++ b/spring-session-samples/spring-session-sample-javaconfig-security/src/integration-test/java/sample/pages/HomePage.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,7 +41,7 @@ public class HomePage extends BasePage { } public LoginPage unauthenticated() { - return LoginPage.go(getDriver()); + return LoginPage.go(getDriver()); } public void assertAt() { @@ -52,4 +52,5 @@ public class HomePage extends BasePage { this.button.click(); return LoginPage.go(getDriver()); } + } diff --git a/spring-session-samples/spring-session-sample-javaconfig-security/src/integration-test/java/sample/pages/LoginPage.java b/spring-session-samples/spring-session-sample-javaconfig-security/src/integration-test/java/sample/pages/LoginPage.java index 0949d16d..2502494f 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-security/src/integration-test/java/sample/pages/LoginPage.java +++ b/spring-session-samples/spring-session-sample-javaconfig-security/src/integration-test/java/sample/pages/LoginPage.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,6 +54,7 @@ public class LoginPage extends BasePage { this.username.sendKeys(user); this.password.sendKeys(password); this.button.click(); - return HomePage.go(getDriver()); + return HomePage.go(getDriver()); } + } diff --git a/spring-session-samples/spring-session-sample-javaconfig-security/src/main/java/sample/Config.java b/spring-session-samples/spring-session-sample-javaconfig-security/src/main/java/sample/Config.java index bede54d1..88fa06a3 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-security/src/main/java/sample/Config.java +++ b/spring-session-samples/spring-session-sample-javaconfig-security/src/main/java/sample/Config.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,5 +32,6 @@ public class Config { public LettuceConnectionFactory connectionFactory() { return new LettuceConnectionFactory(); // <2> } + } // end::class[] diff --git a/spring-session-samples/spring-session-sample-javaconfig-security/src/main/java/sample/EmbeddedRedisConfig.java b/spring-session-samples/spring-session-sample-javaconfig-security/src/main/java/sample/EmbeddedRedisConfig.java index 653eceac..c1c334e0 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-security/src/main/java/sample/EmbeddedRedisConfig.java +++ b/spring-session-samples/spring-session-sample-javaconfig-security/src/main/java/sample/EmbeddedRedisConfig.java @@ -32,8 +32,7 @@ public class EmbeddedRedisConfig { @Bean public GenericContainer redisContainer() { - GenericContainer redisContainer = new GenericContainer(DOCKER_IMAGE) - .withExposedPorts(6379); + GenericContainer redisContainer = new GenericContainer(DOCKER_IMAGE).withExposedPorts(6379); redisContainer.start(); return redisContainer; } diff --git a/spring-session-samples/spring-session-sample-javaconfig-security/src/main/java/sample/SecurityConfig.java b/spring-session-samples/spring-session-sample-javaconfig-security/src/main/java/sample/SecurityConfig.java index 89142199..41acbae6 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-security/src/main/java/sample/SecurityConfig.java +++ b/spring-session-samples/spring-session-sample-javaconfig-security/src/main/java/sample/SecurityConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,9 +26,11 @@ import org.springframework.security.core.userdetails.User; */ @EnableWebSecurity public class SecurityConfig { + @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication().withUser(User.withUsername("user") - .password("{noop}password").roles("USER").build()); + auth.inMemoryAuthentication() + .withUser(User.withUsername("user").password("{noop}password").roles("USER").build()); } + } diff --git a/spring-session-samples/spring-session-sample-javaconfig-security/src/main/java/sample/SecurityInitializer.java b/spring-session-samples/spring-session-sample-javaconfig-security/src/main/java/sample/SecurityInitializer.java index 1cb489dc..5cb39d6a 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-security/src/main/java/sample/SecurityInitializer.java +++ b/spring-session-samples/spring-session-sample-javaconfig-security/src/main/java/sample/SecurityInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,5 +24,6 @@ public class SecurityInitializer extends AbstractSecurityWebApplicationInitializ public SecurityInitializer() { super(SecurityConfig.class, Config.class); } + } // end::class[] diff --git a/spring-session-samples/spring-session-sample-javaconfig-security/src/main/java/sample/SessionServlet.java b/spring-session-samples/spring-session-sample-javaconfig-security/src/main/java/sample/SessionServlet.java index 02967837..d65debe1 100644 --- a/spring-session-samples/spring-session-sample-javaconfig-security/src/main/java/sample/SessionServlet.java +++ b/spring-session-samples/spring-session-sample-javaconfig-security/src/main/java/sample/SessionServlet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,8 +28,7 @@ import javax.servlet.http.HttpServletResponse; public class SessionServlet extends HttpServlet { @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String attributeName = req.getParameter("attributeName"); String attributeValue = req.getParameter("attributeValue"); req.getSession().setAttribute(attributeName, attributeValue); @@ -37,4 +36,5 @@ public class SessionServlet extends HttpServlet { } private static final long serialVersionUID = 2878267318695777395L; + } diff --git a/spring-session-samples/spring-session-sample-misc-hazelcast/src/integration-test/java/sample/AttributeTests.java b/spring-session-samples/spring-session-sample-misc-hazelcast/src/integration-test/java/sample/AttributeTests.java index 1518cdc0..720121d6 100644 --- a/spring-session-samples/spring-session-sample-misc-hazelcast/src/integration-test/java/sample/AttributeTests.java +++ b/spring-session-samples/spring-session-sample-misc-hazelcast/src/integration-test/java/sample/AttributeTests.java @@ -32,34 +32,34 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Eddú Meléndez * @author Rob Winch */ -public class AttributeTests { +class AttributeTests { private WebDriver driver; @BeforeEach - public void setup() { + void setup() { this.driver = new HtmlUnitDriver(); } @AfterEach - public void tearDown() { + void tearDown() { this.driver.quit(); } @Test - public void home() { + void home() { HomePage home = HomePage.go(this.driver); home.assertAt(); } @Test - public void noAttributes() { + void noAttributes() { HomePage home = HomePage.go(this.driver); assertThat(home.attributes().size()).isEqualTo(0); } @Test - public void createAttribute() { + void createAttribute() { HomePage home = HomePage.go(this.driver); // @formatter:off home = home.form() diff --git a/spring-session-samples/spring-session-sample-misc-hazelcast/src/integration-test/java/sample/pages/HomePage.java b/spring-session-samples/spring-session-sample-misc-hazelcast/src/integration-test/java/sample/pages/HomePage.java index 2c40613a..c8604055 100644 --- a/spring-session-samples/spring-session-sample-misc-hazelcast/src/integration-test/java/sample/pages/HomePage.java +++ b/spring-session-samples/spring-session-sample-misc-hazelcast/src/integration-test/java/sample/pages/HomePage.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,6 +77,7 @@ public class HomePage { } public class Form { + @FindBy(name = "attributeName") WebElement attributeName; @@ -104,9 +105,11 @@ public class HomePage { this.submit.click(); return PageFactory.initElements(HomePage.this.driver, page); } + } public static class Attribute { + @FindBy(xpath = ".//td[1]") WebElement attributeName; @@ -130,6 +133,7 @@ public class HomePage { public String getAttributeValue() { return this.attributeValue.getText(); } + } } diff --git a/spring-session-samples/spring-session-sample-misc-hazelcast/src/main/java/sample/Initializer.java b/spring-session-samples/spring-session-sample-misc-hazelcast/src/main/java/sample/Initializer.java index aeeb7fc9..6ee6a8a2 100644 --- a/spring-session-samples/spring-session-sample-misc-hazelcast/src/main/java/sample/Initializer.java +++ b/spring-session-samples/spring-session-sample-misc-hazelcast/src/main/java/sample/Initializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,8 +49,7 @@ public class Initializer implements ServletContextListener { Map sessions = this.instance.getMap(SESSION_MAP_NAME); MapSessionRepository sessionRepository = new MapSessionRepository(sessions); - SessionRepositoryFilter filter = new SessionRepositoryFilter<>( - sessionRepository); + SessionRepositoryFilter filter = new SessionRepositoryFilter<>(sessionRepository); Dynamic fr = sce.getServletContext().addFilter("springSessionFilter", filter); fr.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*"); @@ -64,12 +63,9 @@ public class Initializer implements ServletContextListener { private HazelcastInstance createHazelcastInstance() { Config config = new Config(); - config.getNetworkConfig() - .setPort(getAvailablePort()) - .getJoin().getMulticastConfig().setEnabled(false); + config.getNetworkConfig().setPort(getAvailablePort()).getJoin().getMulticastConfig().setEnabled(false); - config.getMapConfig(SESSION_MAP_NAME) - .setTimeToLiveSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS); + config.getMapConfig(SESSION_MAP_NAME).setTimeToLiveSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS); return Hazelcast.newHazelcastInstance(config); } diff --git a/spring-session-samples/spring-session-sample-misc-hazelcast/src/main/java/sample/SessionServlet.java b/spring-session-samples/spring-session-sample-misc-hazelcast/src/main/java/sample/SessionServlet.java index a474b78a..97f932e0 100644 --- a/spring-session-samples/spring-session-sample-misc-hazelcast/src/main/java/sample/SessionServlet.java +++ b/spring-session-samples/spring-session-sample-misc-hazelcast/src/main/java/sample/SessionServlet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +31,7 @@ import javax.servlet.http.HttpServletResponse; public class SessionServlet extends HttpServlet { @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String attributeName = req.getParameter("attributeName"); String attributeValue = req.getParameter("attributeValue"); req.getSession().setAttribute(attributeName, attributeValue); @@ -40,4 +39,5 @@ public class SessionServlet extends HttpServlet { } private static final long serialVersionUID = 2878267318695777395L; + } diff --git a/spring-session-samples/spring-session-sample-xml-jdbc/src/integration-test/java/sample/AttributeTests.java b/spring-session-samples/spring-session-sample-xml-jdbc/src/integration-test/java/sample/AttributeTests.java index a93598b5..6dc24a50 100644 --- a/spring-session-samples/spring-session-sample-xml-jdbc/src/integration-test/java/sample/AttributeTests.java +++ b/spring-session-samples/spring-session-sample-xml-jdbc/src/integration-test/java/sample/AttributeTests.java @@ -32,34 +32,34 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Eddú Meléndez * @author Rob Winch */ -public class AttributeTests { +class AttributeTests { private WebDriver driver; @BeforeEach - public void setup() { + void setup() { this.driver = new HtmlUnitDriver(); } @AfterEach - public void tearDown() { + void tearDown() { this.driver.quit(); } @Test - public void home() { + void home() { HomePage home = HomePage.go(this.driver); home.assertAt(); } @Test - public void noAttributes() { + void noAttributes() { HomePage home = HomePage.go(this.driver); assertThat(home.attributes()).isEmpty(); } @Test - public void createAttribute() { + void createAttribute() { HomePage home = HomePage.go(this.driver); // @formatter:off home = home.form() diff --git a/spring-session-samples/spring-session-sample-xml-jdbc/src/integration-test/java/sample/pages/HomePage.java b/spring-session-samples/spring-session-sample-xml-jdbc/src/integration-test/java/sample/pages/HomePage.java index 2c40613a..c8604055 100644 --- a/spring-session-samples/spring-session-sample-xml-jdbc/src/integration-test/java/sample/pages/HomePage.java +++ b/spring-session-samples/spring-session-sample-xml-jdbc/src/integration-test/java/sample/pages/HomePage.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,6 +77,7 @@ public class HomePage { } public class Form { + @FindBy(name = "attributeName") WebElement attributeName; @@ -104,9 +105,11 @@ public class HomePage { this.submit.click(); return PageFactory.initElements(HomePage.this.driver, page); } + } public static class Attribute { + @FindBy(xpath = ".//td[1]") WebElement attributeName; @@ -130,6 +133,7 @@ public class HomePage { public String getAttributeValue() { return this.attributeValue.getText(); } + } } diff --git a/spring-session-samples/spring-session-sample-xml-jdbc/src/main/java/sample/SessionServlet.java b/spring-session-samples/spring-session-sample-xml-jdbc/src/main/java/sample/SessionServlet.java index a86e6295..4c947403 100644 --- a/spring-session-samples/spring-session-sample-xml-jdbc/src/main/java/sample/SessionServlet.java +++ b/spring-session-samples/spring-session-sample-xml-jdbc/src/main/java/sample/SessionServlet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,8 +26,7 @@ import javax.servlet.http.HttpServletResponse; public class SessionServlet extends HttpServlet { @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String attributeName = req.getParameter("attributeName"); String attributeValue = req.getParameter("attributeValue"); req.getSession().setAttribute(attributeName, attributeValue); @@ -35,6 +34,7 @@ public class SessionServlet extends HttpServlet { } private static final long serialVersionUID = 2878267318695777395L; + } // end::class[] diff --git a/spring-session-samples/spring-session-sample-xml-redis/src/integration-test/java/sample/AttributeTests.java b/spring-session-samples/spring-session-sample-xml-redis/src/integration-test/java/sample/AttributeTests.java index a93c0ec4..0c5e7494 100644 --- a/spring-session-samples/spring-session-sample-xml-redis/src/integration-test/java/sample/AttributeTests.java +++ b/spring-session-samples/spring-session-sample-xml-redis/src/integration-test/java/sample/AttributeTests.java @@ -32,28 +32,28 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Eddú Meléndez * @author Rob Winch */ -public class AttributeTests { +class AttributeTests { private WebDriver driver; @BeforeEach - public void setup() { + void setup() { this.driver = new HtmlUnitDriver(); } @AfterEach - public void tearDown() { + void tearDown() { this.driver.quit(); } @Test - public void noAttributes() { + void noAttributes() { HomePage home = HomePage.go(this.driver, HomePage.class); assertThat(home.attributes()).isEmpty(); } @Test - public void createAttribute() { + void createAttribute() { HomePage home = HomePage.go(this.driver, HomePage.class); // @formatter:off home = home.form() diff --git a/spring-session-samples/spring-session-sample-xml-redis/src/integration-test/java/sample/pages/HomePage.java b/spring-session-samples/spring-session-sample-xml-redis/src/integration-test/java/sample/pages/HomePage.java index e142c980..7d8a805f 100644 --- a/spring-session-samples/spring-session-sample-xml-redis/src/integration-test/java/sample/pages/HomePage.java +++ b/spring-session-samples/spring-session-sample-xml-redis/src/integration-test/java/sample/pages/HomePage.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,6 +77,7 @@ public class HomePage { } public class Form { + @FindBy(name = "attributeName") WebElement attributeName; @@ -104,9 +105,11 @@ public class HomePage { this.submit.click(); return PageFactory.initElements(HomePage.this.driver, page); } + } public static class Attribute { + @FindBy(xpath = ".//td[1]") WebElement attributeName; @@ -130,6 +133,7 @@ public class HomePage { public String getAttributeValue() { return this.attributeValue.getText(); } + } } diff --git a/spring-session-samples/spring-session-sample-xml-redis/src/main/java/sample/EmbeddedRedisConfig.java b/spring-session-samples/spring-session-sample-xml-redis/src/main/java/sample/EmbeddedRedisConfig.java index 653eceac..c1c334e0 100644 --- a/spring-session-samples/spring-session-sample-xml-redis/src/main/java/sample/EmbeddedRedisConfig.java +++ b/spring-session-samples/spring-session-sample-xml-redis/src/main/java/sample/EmbeddedRedisConfig.java @@ -32,8 +32,7 @@ public class EmbeddedRedisConfig { @Bean public GenericContainer redisContainer() { - GenericContainer redisContainer = new GenericContainer(DOCKER_IMAGE) - .withExposedPorts(6379); + GenericContainer redisContainer = new GenericContainer(DOCKER_IMAGE).withExposedPorts(6379); redisContainer.start(); return redisContainer; } diff --git a/spring-session-samples/spring-session-sample-xml-redis/src/main/java/sample/SessionServlet.java b/spring-session-samples/spring-session-sample-xml-redis/src/main/java/sample/SessionServlet.java index c0deae5d..29d63554 100644 --- a/spring-session-samples/spring-session-sample-xml-redis/src/main/java/sample/SessionServlet.java +++ b/spring-session-samples/spring-session-sample-xml-redis/src/main/java/sample/SessionServlet.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,8 +27,7 @@ import javax.servlet.http.HttpServletResponse; public class SessionServlet extends HttpServlet { @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String attributeName = req.getParameter("attributeName"); String attributeValue = req.getParameter("attributeValue"); req.getSession().setAttribute(attributeName, attributeValue); @@ -36,6 +35,7 @@ public class SessionServlet extends HttpServlet { } private static final long serialVersionUID = 2878267318695777395L; + } // end::class[]