auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void should_fail_if_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> maps.assertContainsOnlyKeys(someInfo(), null, START Arrays.asList("name"))) END .withMessage(actualIsNull()); } replace all `Arrays.asList` by `org.assertj.core.util.Lists.list` and static import it for readability.

Target:
public void should_fail_if_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> maps.assertContainsOnlyKeys(someInfo(), null, list("name"))) .withMessage(actualIsNull()); }
Source:
private AssertionError assertionFailedError(String message) { try { Object o = constructorInvoker.newInstance("org.opentest4j.AssertionFailedError", MSG_ARG_TYPES_FOR_ASSERTION_FAILED_ERROR, message, actual, START expected); END if (o instanceof AssertionError) { AssertionError assertionError = (AssertionError) o; Failures.instance().removeAssertJRelatedElementsFromStackTraceIfNeeded(assertionError); return assertionError; } return null; } catch (Throwable e) { return null; } } the code was correct as per https://github.com/ota4j-team/opentest4j/blob/master/src/main/java/org/opentest4j/AssertionFailedError.java#L65 where expected comes before actual.

Target:
private AssertionError assertionFailedError(String message) { try { Object o = constructorInvoker.newInstance("org.opentest4j.AssertionFailedError", MSG_ARG_TYPES_FOR_ASSERTION_FAILED_ERROR, message, expected, actual); if (o instanceof AssertionError) { AssertionError assertionError = (AssertionError) o; Failures.instance().removeAssertJRelatedElementsFromStackTraceIfNeeded(assertionError); return assertionError; } return null; } catch (Throwable e) { return null; } }
Source:
protected void verify_internal_effects() { START verify(iterables).assertHasOnlyOneElementSatisfying(info(), newArrayList(internalArray()), consumer); END } use `list` in place of `newArrayList`, it does the same thing but is a bit lighter to read.

Target:
protected void verify_internal_effects() { verify(iterables).assertHasOnlyOneElementSatisfying(info(), list(internalArray()), consumer); }
Source:
public void should_initialise_actual() { Iterator<String> names = asList("Luke", "Leia").iterator(); START Iterable<String> actual = (Iterable<String>) assertThat(names).toIterable().actual; END assertThat(actual).containsOnly("Leia", "Luke"); } this test class should only deal with `Iterator`, `actual` should be an `Iterator` and not an `Iterable`

Target:
public void should_initialise_actual() { Iterator<String> names = asList("Luke", "Leia").iterator(); Iterator<String> actual = (Iterator<String>) assertThat(names).actual; assertThat(actual).hasNext(); }
Source:
public SELF isEqualTo(ZonedDateTime expected) { Objects.instance().assertNotNull(info, actual); START assertDateTimeParameterIsNotNull(expected); END return super.isEqualTo(sameInstantInActualTimeZone(expected)); } To be consistent with `AbstractAssert.isEqualTo`, this assertion should pass when both actual and expected are null. a possible implementation would be to make `sameInstantInActualTimeZone` return null when given null.

Target:
public SELF isEqualTo(ZonedDateTime expected) { return super.isEqualTo(sameInstantInActualTimeZone(expected)); }
Source:
public void should_fail_when_asserting_no_exception_raised_but_exception_occurs() { // Given Exception exception = new Exception("boom"); ThrowingCallable boom = raisingException(exception); // Expect START thrown.expectAssertionError(ShouldNotHaveThrown.shouldNotHaveThrown(exception)); END // When assertThatCode(boom).doesNotThrowAnyException(); } `startsWith` and `contains` String assertions should do the job.

Target:
public void should_fail_when_asserting_no_exception_raised_but_exception_occurs() { // Given Exception exception = new Exception("boom"); ThrowingCallable boom = raisingException(exception); // Expect thrown.expectAssertionError(shouldNotHaveThrown(exception)); // When assertThatCode(boom).doesNotThrowAnyException(); }
Source:
public void catchThrowableOfType_should_succeed_and_return_actual_instance_with_correct_class() { final Exception expected = new RuntimeException("boom!!"); Exception actual = null; try { actual = catchThrowableOfType(raisingException(expected), Exception.class); } catch (AssertionError a) { START Fail.fail("catchThrowableOfType should not have asserted", a); END } assertThat(actual).isSameAs(expected); } static import `fail`

Target:
public void catchThrowableOfType_should_succeed_and_return_actual_instance_with_correct_class() { final Exception expected = new RuntimeException("boom!!"); Exception actual = null; try { actual = catchThrowableOfType(raisingException(expected), Exception.class); } catch (AssertionError a) { fail("catchThrowableOfType should not have asserted", a); } assertThat(actual).isSameAs(expected); }
Source:
private boolean notNullSeqContainsOnlyWhitespaces(CharSequence actual) { for (int i = 0; i < actual.length(); i++) { START if (!Character.isWhitespace(actual.charAt(i))) return false; END } return true; } minor static import `isWhitespace` for readability

Target:
private boolean notNullSeqContainsOnlyWhitespaces(CharSequence actual) { for (int i = 0; i < actual.length(); i++) { if (!isWhitespace(actual.charAt(i))) return false; } return true; }
Source:
private boolean isNullOrEmpty(CharSequence actual) { START return (actual == null || actual.length() == 0); END } remove unnecessary parenthesis

Target:
private boolean isNullOrEmpty(CharSequence actual) { return actual == null || actual.length() == 0; }
Source:
private static List<Object> flattenNonRecursive(Collection<? extends Object> list) { List<Object> result = new ArrayList<>(); LinkedList<Object> stack = new LinkedList<>(list); while (!stack.isEmpty()) { Object e = stack.pop(); if (e instanceof List<?>) stack.addAll(0, (List<?>)e); else START result.add(e); END } return result; } format as: ```java if (e instanceof List<?>) stack.addAll(0, (List<?>)e); else result.add(e); ```

Target:
private static List<Object> flattenNonRecursive(Collection<? extends Object> list) { List<Object> result = new ArrayList<>(); for (Object item : list) { if (item instanceof List<?>) result.addAll(0, (List<?>)item); else result.add(item); } return result; }
Source:
START protected String defaultErrorMessage(Description description, Representation representation) { END if (actualAndExpectedHaveSameStringRepresentation()) { return defaultDetailedErrorMessage(description, representation); } return comparisonStrategy.isStandard() ? messageFormatter.format(description, representation, EXPECTED_BUT_WAS_MESSAGE, actual, expected) : messageFormatter.format(description, representation, EXPECTED_BUT_WAS_MESSAGE_USING_COMPARATOR, actual, expected, comparisonStrategy); } why has this changed to `protected` ?

Target:
private String defaultErrorMessage(Description description, Representation representation) { if (actualAndExpectedHaveSameStringRepresentation()) { // Example : actual = 42f and expected = 42d gives actual : "42" and expected : "42" therefore we need // to create a detailed error message` return defaultDetailedErrorMessage(description, representation); } return comparisonStrategy.isStandard() ? messageFormatter.format(description, representation, EXPECTED_BUT_WAS_MESSAGE, actual, expected) : messageFormatter.format(description, representation, EXPECTED_BUT_WAS_MESSAGE_USING_COMPARATOR, actual, expected, comparisonStrategy); }
Source:
public void should_create_AssertionError_if_created_ComparisonFailure_and_AssertionFailedError_is_null() throws Exception { START when(constructorInvoker.newInstance(any(String.class), any(Class[].class), anyVararg())).thenReturn(null); END AssertionError error = factory.newAssertionError(description, new StandardRepresentation()); check(error); } `anyVararg` is deprecated, is that possible to use something else here ?

Target:
public void should_create_AssertionError_if_created_ComparisonFailure_and_AssertionFailedError_is_null() throws Exception { when(constructorInvoker.newInstance(any(String.class), any(Class[].class), any(Object[].class))).thenReturn(null); AssertionError error = factory.newAssertionError(description, new StandardRepresentation()); check(error); }
Source:
public void assertHasDeclaredMethods(AssertionInfo info, Class<?> actual, String... methods) { assertNotNull(info, actual); START doAssertHasMethods(info, actual, actual.getDeclaredMethods(), methods); END } how do you now in `doAssertHasMethods` that the error message is about declared methods and not methods ?

Target:
public void assertHasDeclaredMethods(AssertionInfo info, Class<?> actual, String... methods) { assertNotNull(info, actual); doAssertHasMethods(info, actual, actual.getDeclaredMethods(), true, methods); }
Source:
public void should_pass_if_actual_contains_given_values_exactly_with_null_elements() { iterables.assertContainsExactlyInAnyOrder(someInfo(), actual, array("Luke", "Yoda", "Leia")); actual.add(null); START iterables.assertContainsExactlyInAnyOrder(someInfo(), actual, array("Luke", "Yoda", "Leia", null)); END } I would just shuffle the order

Target:
public void should_pass_if_actual_contains_given_values_exactly_with_null_elements() { iterables.assertContainsExactlyInAnyOrder(someInfo(), actual, array("Leia", "Yoda", "Luke")); actual.add(null); iterables.assertContainsExactlyInAnyOrder(someInfo(), actual, array("Leia", null, "Yoda", "Luke")); }
Source:
public void should_pass_if_difference_is_less_than_given_percentage() { bigDecimals.assertIsCloseToPercentage(someInfo(), ONE, ONE, withPercentage(valueOf(1))); START bigDecimals.assertIsCloseToPercentage(someInfo(), ONE, TWO, withPercentage(valueOf(50))); END } If I'm not wrong, the difference = 1 and the allowed margin is 2*50%=1, so the difference == allowed margin and not < margin. you need to move this to `should_pass_if_difference_is_equal_to_given_percentage`

Target:
public void should_pass_if_difference_is_less_than_given_percentage() { bigDecimals.assertIsCloseToPercentage(someInfo(), ONE, ONE, withPercentage(valueOf(1))); bigDecimals.assertIsCloseToPercentage(someInfo(), ONE, TWO, withPercentage(valueOf(100))); }
Source:
public void should_pass_if_actual_contains_only_expected_entries() throws Exception { START maps.assertContainsOnlyKeys(someInfo(), actual, "name", "color"); END } add `maps.assertContainsOnlyKeys(someInfo(), actual, "color", "name");` to check that order does not matter

Target:
public void should_pass_if_actual_contains_only_expected_entries() throws Exception { maps.assertContainsOnlyKeys(someInfo(), actual, "color", "name"); }
Source:
public Cluster(String name, String region, Set<String> soloInstances) { Validate.notNull(name); Validate.notNull(region); START Validate.notNull(autoScalingGroups); END this.name = name; this.region = region; for (String soleInstance : soloInstances) { this.soloInstances.add(soleInstance); } } autoScalingGroups should be soloInstances

Target:
public Cluster(String name, String region, Set<String> soloInstances) { Validate.notNull(name); Validate.notNull(region); Validate.notNull(soloInstances); this.name = name; this.region = region; for (String soleInstance : soloInstances) { this.soloInstances.add(soleInstance); } }
Source:
protected MavenModuleSet getProject() { MavenModuleSet project = createJob(); START copyFilesToWorkspace(project, "checkstyle-qualitygate.xml"); END copyToWorkspace(project, "pom.xml"); return project; } s. Baseclass Kommentar

Target:
protected MavenModuleSet getProject() { MavenModuleSet project = createJob(); copyToWorkspace(project, "pom.xml"); return project; }
Source:
protected FileAnnotation getErrorNumber( final int number) throws IOException { Collection<FileAnnotation> warnings = new SdccParser().parse(openFile("sdcc_Output.txt")); START Iterator<FileAnnotation> iterator = warnings.iterator(); END FileAnnotation annotation = iterator.next(); for(int i = 1; i < number; i++) { annotation = iterator.next(); } return annotation; } Use a list to access at index

Target:
protected FileAnnotation getErrorNumber( final int number) throws IOException { List<FileAnnotation> warnings = new SdccParser().parse(openFile("sdcc_Output.txt")); return warnings.get(number); }
Source:
public ClangTidyParser() { super(Messages._Warnings_ClangTidy_ParserName(), Messages._Warnings_ClangTidy_LinkName(), Messages._Warnings_ClangTidy_TrendName(), CLANG_TIDY_WARNING_PATTERN, START false); END } false is default

Target:
public ClangTidyParser() { super(Messages._Warnings_ClangTidy_ParserName(), Messages._Warnings_ClangTidy_LinkName(), Messages._Warnings_ClangTidy_TrendName(), CLANG_TIDY_WARNING_PATTERN); }
Source:
public DrMemoryParser() { super(Messages._Warnings_DrMemory_ParserName(), Messages._Warnings_DrMemory_LinkName(), Messages._Warnings_DrMemory_TrendName(), START DR_MEMORY_WARNING_PATTERN, true); END } If the last parameter is true, then you need to override isLineInteresting. Otherwise remove true.

Target:
public DrMemoryParser() { super(Messages._Warnings_DrMemory_ParserName(), Messages._Warnings_DrMemory_LinkName(), Messages._Warnings_DrMemory_TrendName(), DR_MEMORY_WARNING_PATTERN, false); }
Source:
private MockHttpServletRequest requestToSave() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServerPort(443); request.setSecure(true); request.setScheme("https"); request.setServerName("abc.com"); request.setRequestURI("/destination"); START request.setServletPath("/destination"); END request.setQueryString("param1=a&param2=b&param3=1122"); return request; } We should not have to set the servlet path for this test to pass.

Target:
private MockHttpServletRequest requestToSave() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServerPort(443); request.setSecure(true); request.setScheme("https"); request.setServerName("abc.com"); request.setRequestURI("/destination"); request.setQueryString("param1=a&param2=b&param3=1122"); return request; }
Source:
private Set<SignatureAlgorithm> fetchSignatureAlgorithms() { if (StringUtils.isEmpty(jwkSetUri)) { return Collections.emptySet(); } try { START return parseAlgorithms(JWKSet.load(toURL(jwkSetUri), 5000, 5000, 0)); END } catch (Exception ex) { log.error("Failed to load Signature Algorithms from remote JWK source."); return Collections.emptySet(); } } Let's please use the `JWKSource` to retrieve JWKs. That will allow you to use a `JWKMatcher` that removes some of the validation you are doing in `parseAlgorithms`.

Target:
private Set<SignatureAlgorithm> fetchSignatureAlgorithms() { try { return parseAlgorithms(JWKSet.load(toURL(jwkSetUri), 5000, 5000, 0)); } catch (Exception ex) { throw new IllegalArgumentException("Failed to load Signature Algorithms from remote JWK source.", ex); } }
Source:
public NimbusJwtDecoder build() { START ConfigurableJWTProcessor<SecurityContext> processor = processor(); END jwtProcessorCustomizer.accept(processor); return new NimbusJwtDecoder(processor); } It seems like the delta would be less if you had `processor()` use the `jwtProcessorCustomizer` instead. Any reason that it needs to be inside the `build()` method?

Target:
public NimbusJwtDecoder build() { return new NimbusJwtDecoder(processor()); }
Source:
JWTProcessor<SecurityContext> processor() { ResourceRetriever jwkSetRetriever = new RestOperationsResourceRetriever(this.restOperations); JWKSource<SecurityContext> jwkSource = jwkSource(jwkSetRetriever); ConfigurableJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>(); jwtProcessor.setJWSKeySelector(jwsKeySelector(jwkSource)); // Spring Security validates the claim set independent from Nimbus jwtProcessor.setJWTClaimsSetVerifier((claims, context) -> { }); START jwtProcessorCustomizer.accept(jwtProcessor); END return jwtProcessor; } For consistency with the rest of the code here, will you please prefix member variable references with `this.`?

Target:
JWTProcessor<SecurityContext> processor() { ResourceRetriever jwkSetRetriever = new RestOperationsResourceRetriever(this.restOperations); JWKSource<SecurityContext> jwkSource = jwkSource(jwkSetRetriever); ConfigurableJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>(); jwtProcessor.setJWSKeySelector(jwsKeySelector(jwkSource)); // Spring Security validates the claim set independent from Nimbus jwtProcessor.setJWTClaimsSetVerifier((claims, context) -> { }); this.jwtProcessorCustomizer.accept(jwtProcessor); return jwtProcessor; }
Source:
public SwitchUserWebFilter(ReactiveUserDetailsService userDetailsService, String successTargetUrl, @Nullable String failureTargetUrl) { Assert.notNull(userDetailsService, "userDetailsService must be specified"); Assert.notNull(successTargetUrl, "successTargetUrl must be specified"); this.userDetailsService = userDetailsService; this.successHandler = new RedirectServerAuthenticationSuccessHandler(successTargetUrl); START this.failureHandler = Optional.ofNullable(failureTargetUrl). END map(RedirectServerAuthenticationFailureHandler::new).orElse(null); this.securityContextRepository = new WebSessionServerSecurityContextRepository(); this.userDetailsChecker = new AccountStatusUserDetailsChecker(); } In order to reduce the overhead of creating additional objects, we prefer to use null checks instead of `Optional.ofNullable`. For more information see gh-7155.

Target:
public SwitchUserWebFilter(ReactiveUserDetailsService userDetailsService, String successTargetUrl, @Nullable String failureTargetUrl) { Assert.notNull(userDetailsService, "userDetailsService must be specified"); Assert.notNull(successTargetUrl, "successTargetUrl must be specified"); this.userDetailsService = userDetailsService; this.successHandler = new RedirectServerAuthenticationSuccessHandler(successTargetUrl); if (failureTargetUrl != null) { this.failureHandler = new RedirectServerAuthenticationFailureHandler(failureTargetUrl); } else { this.failureHandler = null; } this.securityContextRepository = new WebSessionServerSecurityContextRepository(); this.userDetailsChecker = new AccountStatusUserDetailsChecker(); }
Source:
START protected Mono<Void> onAuthenticationSuccess(Authentication authentication, WebFilterExchange webFilterExchange) { END final ServerWebExchange exchange = webFilterExchange.getExchange(); final SecurityContextImpl securityContext = new SecurityContextImpl(authentication); return securityContextRepository.save(exchange, securityContext) .then(this.successHandler.onAuthenticationSuccess(webFilterExchange, authentication)) .subscriberContext(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext))); } I believe this method should be private. If a user wishes to override this behavior they can supply a custom successHandler. Similar for `onAuthenticationFailure`.

Target:
private Mono<Void> onAuthenticationSuccess(Authentication authentication, WebFilterExchange webFilterExchange) { final ServerWebExchange exchange = webFilterExchange.getExchange(); final SecurityContextImpl securityContext = new SecurityContextImpl(authentication); return securityContextRepository.save(exchange, securityContext) .then(this.successHandler.onAuthenticationSuccess(webFilterExchange, authentication)) .subscriberContext(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext))); }
Source:
protected Mono<Authentication> attemptSwitchUser(Authentication currentAuthentication, String userName) { Assert.notNull(userName, "The userName can not be null."); if (this.logger.isDebugEnabled()) { this.logger.debug("Attempt to switch to user [" + userName + "]"); } START END return userDetailsService.findByUsername(userName) .switchIfEmpty(Mono.error(this::noTargetAuthenticationException)) .doOnNext(userDetailsChecker::check) .map(userDetails -> createSwitchUserToken(userDetails, currentAuthentication)); } Could you explain why `switchUser` and `attemptSwitchUser` are split up this way? Would it make sense to combine them into a single method? Similar question for `exitSwitchUser` and `attemptExitUser`.

Target:
private Mono<Authentication> attemptSwitchUser(Authentication currentAuthentication, String userName) { Assert.notNull(userName, "The userName can not be null."); if (this.logger.isDebugEnabled()) { this.logger.debug("Attempt to switch to user [" + userName + "]"); } return userDetailsService.findByUsername(userName) .switchIfEmpty(Mono.error(this::noTargetAuthenticationException)) .doOnNext(userDetailsChecker::check) .map(userDetails -> createSwitchUserToken(userDetails, currentAuthentication)); }
Source:
START default Map<String, Object> getAttributes() { END return Collections.emptyMap(); } Since a SAML Attribute map can have multiple values, the type here should be `Map<String, List<Object>>`.

Target:
default Map<String, List<Object>> getAttributes() { return Collections.emptyMap(); }
Source:
START default <A> A getAttribute(String name) { END return (A) getAttributes().get(name); } I agree that to get the underlying list you can call `getAttributes().get("tenant")`. Since there is the possibility of adding both somewhere down the road, I'm leaning more heavily now towards renaming this method to `getFirstAttribute`. I believe this aligns nicely with `MultiValueMap` which is similar in concept and also has a method called `getFirst()`.

Target:
default <A> List<A> getAttribute(String name) { return (List<A>) getAttributes().get(name); }
Source:
START @Override public boolean isMergeEnabled() { END return true; } Can you please put `@Override` on its own line to be consistent with Spring Security code conventions? ```suggestion @Override public boolean isMergeEnabled() { ```

Target:
public boolean isMergeEnabled() { return true; }
Source:
@Override public Object merge( Object parent ) { if (parent == null) { return this; } START if (parent instanceof MockHttpServletRequestBuilder) { END this.mergeable = (Mergeable) parent; return this.mergeable; } else { throw new IllegalArgumentException("Cannot merge with [" + parent.getClass().getName() + "]"); } } I think we can just check if it is an instance of `Mergeable` since that is what we are casting it to. The check for what we pass in is a `MockHttpServletRequestBuilder` will be done when we invoke `MockHttpServletRequestBuilder.merge`

Target:
public Object merge(Object parent) { if (parent == null) { return this; } if (parent instanceof Mergeable) { this.parent = (Mergeable) parent; return this; } else { throw new IllegalArgumentException("Cannot merge with [" + parent.getClass().getName() + "]"); } }
Source:
private void configure(B builder) { OAuth2AuthorizationRequestRedirectFilter authorizationRequestRedirectFilter = createAuthorizationRequestRedirectFilter(builder); builder.addFilter(postProcess(authorizationRequestRedirectFilter)); OAuth2AuthorizationCodeGrantFilter authorizationCodeGrantFilter = createAuthorizationCodeGrantFilter(builder); START RequestCache requestCache = builder.getSharedObject(RequestCache.class); END if (requestCache != null) { authorizationCodeGrantFilter.setRequestCache(requestCache); } builder.addFilter(postProcess(authorizationCodeGrantFilter)); } Can you move this logic to `createAuthorizationCodeGrantFilter()`

Target:
private void configure(B builder) { OAuth2AuthorizationRequestRedirectFilter authorizationRequestRedirectFilter = createAuthorizationRequestRedirectFilter(builder); builder.addFilter(postProcess(authorizationRequestRedirectFilter)); OAuth2AuthorizationCodeGrantFilter authorizationCodeGrantFilter = createAuthorizationCodeGrantFilter(builder); builder.addFilter(postProcess(authorizationCodeGrantFilter)); }
Source:
public void setAuthenticationManager(AuthenticationManager authenticationManager) { START Assert.notNull(authenticationManager, "authenticationManager cannot be null"); END this.authenticationManager = authenticationManager; } This is not really making any guarantees since the value is possibly null before, so we don't do an assertion here.

Target:
public void setAuthenticationManager(AuthenticationManager authenticationManager) { this.authenticationManager = authenticationManager; }
Source:
public Resource retrieveResource(URL url) { START String jwkSet = cache.get(url.toString(), () -> resourceRetriever.retrieveResource(url).getContent()); END return new Resource(jwkSet, "UTF-8"); } I think we may want to wrap any exception in an `IOException`, like `RestOperationsResourceRetriever` does. The reason for that is so that Nimbus's `RemoteJWKSet` can react appropriately and throw its `RemoteKeySourceException`. My concern is that adding this cache will change the exception callers see from a `RemoteKeySourceException` to a `ValueRetreivalException`.

Target:
public Resource retrieveResource(URL url) throws IOException { String jwkSet; try { jwkSet = cache.get(url.toString(), () -> resourceRetriever.retrieveResource(url).getContent()); } catch (Exception ex) { throw new IOException(ex); } return new Resource(jwkSet, "UTF-8"); }
Source:
public void setPostLogoutRedirectUri(URI postLogoutRedirectUri) { Assert.notNull(postLogoutRedirectUri, "postLogoutRedirectUri cannot be empty"); START this.postLogoutRedirectUriTemplate = postLogoutRedirectUri.toASCIIString(); END } This needs to be `@Deprecated` as well

Target:
public void setPostLogoutRedirectUri(URI postLogoutRedirectUri) { Assert.notNull(postLogoutRedirectUri, "postLogoutRedirectUri cannot be empty"); this.postLogoutRedirectUri = postLogoutRedirectUri.toASCIIString(); }
Source:
public void emptyMapCausesException() { Map<Class<? extends AuthenticationException>, Class<? extends AbstractAuthenticationFailureEvent>> mappings = new HashMap<>(); publisher = new DefaultAuthenticationEventPublisher(); publisher.setAdditionalExceptionMappings(mappings); START ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class); END publisher.setApplicationEventPublisher(appPublisher); } Are the last two lines of this test necessary? Let's go ahead and remove any unnecessary lines of code.

Target:
public void emptyMapCausesException() { Map<Class<? extends AuthenticationException>, Class<? extends AbstractAuthenticationFailureEvent>> mappings = new HashMap<>(); publisher = new DefaultAuthenticationEventPublisher(); publisher.setAdditionalExceptionMappings(mappings); }
Source:
START protected OAuth2AccessTokenResponse populateTokenResponse(T grantRequest, OAuth2AccessTokenResponse tokenResponse) { END if (CollectionUtils.isEmpty(tokenResponse.getAccessToken().getScopes())) { Set<String> defaultScopes = defaultScopes(grantRequest); tokenResponse = OAuth2AccessTokenResponse.withResponse(tokenResponse) .scopes(defaultScopes) .build(); } return tokenResponse; } Do we need to expose this right now? I'd prefer to make `private` if we don't need to expose now.

Target:
OAuth2AccessTokenResponse populateTokenResponse(T grantRequest, OAuth2AccessTokenResponse tokenResponse) { if (CollectionUtils.isEmpty(tokenResponse.getAccessToken().getScopes())) { Set<String> defaultScopes = defaultScopes(grantRequest); tokenResponse = OAuth2AccessTokenResponse.withResponse(tokenResponse) .scopes(defaultScopes) .build(); } return tokenResponse; }
Source:
private RequestContextSubscriber(CoreSubscriber<T> delegate, Authentication authentication) { this.delegate = delegate; Context parentContext = this.delegate.currentContext(); Context context; START if (parentContext.hasKey(REQUEST_CONTEXT_DATA_HOLDER_ATTR_NAME)) { END context = parentContext; } else { context = parentContext.put(REQUEST_CONTEXT_DATA_HOLDER_ATTR_NAME, new RequestContextDataHolder(authentication)); } this.context = context; } maybe it would be better not to create empty RequestContextDataHolder? by ```java if (authentication == null || parentContext.hasKey(REQUEST_CONTEXT_DATA_HOLDER_ATTR_NAME)) ```

Target:
private RequestContextSubscriber(CoreSubscriber<T> delegate, Authentication authentication) { this.delegate = delegate; Context parentContext = this.delegate.currentContext(); Context context; if (authentication == null || parentContext.hasKey(REQUEST_CONTEXT_DATA_HOLDER_ATTR_NAME)) { context = parentContext; } else { context = parentContext.put(REQUEST_CONTEXT_DATA_HOLDER_ATTR_NAME, new RequestContextDataHolder(authentication)); } this.context = context; }
Source:
private boolean shouldProcessAuthorizationResponse(HttpServletRequest request) { OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestRepository.loadAuthorizationRequest(request); if (authorizationRequest == null) { return false; } MultiValueMap<String, String> params = OAuth2AuthorizationResponseUtils.toMultiMap(request.getParameterMap()); START if (isValidRedirectUrl(request, authorizationRequest.getRedirectUri()) && END OAuth2AuthorizationResponseUtils.isAuthorizationResponse(params)) { return true; } return false; } @ttddyy This can be simplified as follows: ```java String requestUrl = UrlUtils.buildFullRequestUrl(request); MultiValueMap<String, String> params = OAuth2AuthorizationResponseUtils.toMultiMap(request.getParameterMap()); if (requestUrl.startsWith(authorizationRequest.getRedirectUri()) && OAuth2AuthorizationResponseUtils.isAuthorizationResponse(params)) { return true; } ```

Target:
private boolean shouldProcessAuthorizationResponse(HttpServletRequest request) { OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestRepository.loadAuthorizationRequest(request); if (authorizationRequest == null) { return false; } MultiValueMap<String, String> params = OAuth2AuthorizationResponseUtils.toMultiMap(request.getParameterMap()); if (OAuth2AuthorizationResponseUtils.isAuthorizationResponse(params) && isValidRedirectUrl(request, authorizationRequest.getRedirectUri())) { return true; } return false; }
Source:
public Collection<GrantedAuthority> convert(Jwt jwt) { Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (String authority : getAuthorities(jwt)) { START grantedAuthorities.add(new SimpleGrantedAuthority(authorityPrefix + authority)); END } return grantedAuthorities; } To conform with our team standard, would you please prefix the field with `this.`?

Target:
public Collection<GrantedAuthority> convert(Jwt jwt) { Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (String authority : getAuthorities(jwt)) { grantedAuthorities.add(new SimpleGrantedAuthority(this.authorityPrefix + authority)); } return grantedAuthorities; }
Source:
START public RequestContextDataHolder(@Nullable HttpServletRequest request, END @Nullable HttpServletResponse response, @Nullable Authentication authentication) { this.request = request; this.response = response; this.authentication = authentication; } Make `private`

Target:
RequestContextDataHolder(@Nullable HttpServletRequest request, @Nullable HttpServletResponse response, @Nullable Authentication authentication) { this.request = request; this.response = response; this.authentication = authentication; }
Source:
START public HttpServletRequest getRequest() { END return request; } Make getters `private` and use `this` on instance members.

Target:
private HttpServletRequest getRequest() { return this.request; }
Source:
private List<String> getPrimaryBeanNames(String[] beanNamesForType) { START final List<String> list = new ArrayList<>(); END if (!(applicationContext instanceof ConfigurableApplicationContext)) { return Collections.emptyList(); } for (String beanName: beanNamesForType) { if (((ConfigurableApplicationContext) applicationContext).getBeanFactory() .getBeanDefinition(beanName).isPrimary()) { list.add(beanName); } } return list; } So that this aligns with the rest of the codebase, let's remove the `final` keyword here.

Target:
private List<String> getPrimaryBeanNames(String[] beanNamesForType) { List<String> list = new ArrayList<>(); if (!(applicationContext instanceof ConfigurableApplicationContext)) { return Collections.emptyList(); } for (String beanName : beanNamesForType) { if (((ConfigurableApplicationContext) applicationContext).getBeanFactory() .getBeanDefinition(beanName).isPrimary()) { list.add(beanName); } } return list; }
Source:
private static Map<String, ClientRegistration> toUnmodifiableConcurrentMap(List<ClientRegistration> registrations) { final ConcurrentHashMap<String, ClientRegistration> result = new ConcurrentHashMap<>(); for (ClientRegistration registration : registrations) { START if (result.containsKey(registration.getRegistrationId())) { END throw new IllegalStateException(String.format("Duplicate key %s", registration.getRegistrationId())); } result.put(registration.getRegistrationId(), registration); } return Collections.unmodifiableMap(result); } Why is this check necessary?

Target:
private static Map<String, ClientRegistration> toUnmodifiableConcurrentMap(List<ClientRegistration> registrations) { ConcurrentHashMap<String, ClientRegistration> result = new ConcurrentHashMap<>(); for (ClientRegistration registration : registrations) { if (result.containsKey(registration.getRegistrationId())) { throw new IllegalStateException(String.format("Duplicate key %s", registration.getRegistrationId())); } result.put(registration.getRegistrationId(), registration); } return Collections.unmodifiableMap(result); }
Source:
private LinkedHashSet<String> toLinkedHashSet(String... scope) { START final LinkedHashSet<String> result = new LinkedHashSet<>(); END Collections.addAll(result, scope); return result; } To conform with other Spring Security code, please remove the `final` keyword from in front of local variables.

Target:
private LinkedHashSet<String> toLinkedHashSet(String... scope) { LinkedHashSet<String> result = new LinkedHashSet<>(); Collections.addAll(result, scope); return result; }
Source:
private ConcurrentHashMap<String, ClientRegistration> toConcurrentMap(List<ClientRegistration> registrations) { START final ConcurrentHashMap<String, ClientRegistration> result = new ConcurrentHashMap<>(); END for (ClientRegistration registration : registrations) { result.put(registration.getRegistrationId(), registration); } return result; } For consistency across the project, please remove the `final` keyword here.

Target:
private ConcurrentHashMap<String, ClientRegistration> toConcurrentMap(List<ClientRegistration> registrations) { ConcurrentHashMap<String, ClientRegistration> result = new ConcurrentHashMap<>(); for (ClientRegistration registration : registrations) { result.put(registration.getRegistrationId(), registration); } return result; }
Source:
public OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context) { Assert.notNull(context, "context cannot be null"); for (OAuth2AuthorizedClientProvider authorizedClientProvider: authorizedClientProviders) { START final OAuth2AuthorizedClient oauth2AuthorizedClient = authorizedClientProvider.authorize(context); END if (oauth2AuthorizedClient != null) { return oauth2AuthorizedClient; } } return null; } Thanks for simplifying this. Will you please also remove the `final` keyword from the local variable here?

Target:
public OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context) { Assert.notNull(context, "context cannot be null"); for (OAuth2AuthorizedClientProvider authorizedClientProvider : authorizedClientProviders) { OAuth2AuthorizedClient oauth2AuthorizedClient = authorizedClientProvider.authorize(context); if (oauth2AuthorizedClient != null) { return oauth2AuthorizedClient; } } return null; }
Source:
private void rejectedUntrustedHosts(HttpServletRequest request) { String serverName = request.getServerName(); START if (this.allowedHostnames != null && !this.allowedHostnames.test(serverName)) { END throw new RequestRejectedException("The request was rejected because the domain " + serverName + " is untrusted."); } } Sorry, the concern isn't that `this.allowedHostnames` would be `null` at this point, but that `serverName` would be `null`. Because of the change to `DummyRequest`, it's possible for `getServerName` to return `null`. So, we'd want to do: ```suggestion if (serverName != null && !this.allowedHostnames.test(serverName)) { ```

Target:
private void rejectedUntrustedHosts(HttpServletRequest request) { String serverName = request.getServerName(); if (serverName != null && !this.allowedHostnames.test(serverName)) { throw new RequestRejectedException("The request was rejected because the domain " + serverName + " is untrusted."); } }
Source:
START public SingleKeyJWSKeySelector(JWSAlgorithm expectedJwsAlgorithm, Key key) { END Assert.notNull(expectedJwsAlgorithm, "expectedJwsAlgorithm cannot be null"); Assert.notNull(key, "key cannot be null"); this.keySet = Arrays.asList(key); this.expectedJwsAlgorithm = expectedJwsAlgorithm; } You can remove the `public` modifier since the class is `package-private`

Target:
SingleKeyJWSKeySelector(JWSAlgorithm expectedJwsAlgorithm, Key key) { Assert.notNull(expectedJwsAlgorithm, "expectedJwsAlgorithm cannot be null"); Assert.notNull(key, "key cannot be null"); this.keySet = Arrays.asList(key); this.expectedJwsAlgorithm = expectedJwsAlgorithm; }
Source:
START public void customWithUriVars() throws Exception { END MockHttpServletRequest request = logout().logoutUrl("/uri-logout/{var1}/{var2}", "val1", "val2").buildRequest( servletContext); CsrfToken token = (CsrfToken) request.getAttribute(CsrfRequestPostProcessor.TestCsrfTokenRepository.TOKEN_ATTR_NAME); assertThat(request.getMethod()).isEqualTo("POST"); assertThat(request.getParameter(token.getParameterName())).isEqualTo( token.getToken()); assertThat(request.getRequestURI()).isEqualTo("/uri-logout/val1/val2"); } This `throws` clause is redundant.

Target:
public void customWithUriVars() { MockHttpServletRequest request = logout().logoutUrl("/uri-logout/{var1}/{var2}", "val1", "val2").buildRequest( servletContext); CsrfToken token = (CsrfToken) request.getAttribute(CsrfRequestPostProcessor.TestCsrfTokenRepository.TOKEN_ATTR_NAME); assertThat(request.getMethod()).isEqualTo("POST"); assertThat(request.getParameter(token.getParameterName())).isEqualTo( token.getToken()); assertThat(request.getRequestURI()).isEqualTo("/uri-logout/val1/val2"); }
Source:
public MockMethodInvocation(Object targetObject, Class clazz, String methodName, Class[] parameterTypes, Object[] arguments) throws NoSuchMethodException { START this.method = clazz.getMethod(methodName, parameterTypes); END this.targetObject = targetObject; this.arguments = arguments; } Is there any reason you aren't calling `this(targetObject, clazz, methodName, parameterTypes)`? If not, would you mind changing this? I realize it's a minor point, but it's one less thing to keep track off.

Target:
public MockMethodInvocation(Object targetObject, Class clazz, String methodName, Class[] parameterTypes, Object[] arguments) throws NoSuchMethodException { this(targetObject, clazz, methodName, parameterTypes); this.arguments = arguments; }
Source:
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { if (this.clientRegistrationRepository != null && this.authorizedClientRepository != null) { OAuth2AuthorizedClientArgumentResolver authorizedClientArgumentResolver = new OAuth2AuthorizedClientArgumentResolver( this.clientRegistrationRepository, this.authorizedClientRepository); START if (accessTokenResponseClient != null) { END authorizedClientArgumentResolver.setClientCredentialsTokenResponseClient(accessTokenResponseClient); } argumentResolvers.add(authorizedClientArgumentResolver); } } Please update `accessTokenResponseClient` to `this.accessTokenResponseClient` - it's common practice within the team to prefix `this` for class members.

Target:
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { if (this.clientRegistrationRepository != null && this.authorizedClientRepository != null) { OAuth2AuthorizedClientArgumentResolver authorizedClientArgumentResolver = new OAuth2AuthorizedClientArgumentResolver( this.clientRegistrationRepository, this.authorizedClientRepository); if (this.accessTokenResponseClient != null) { authorizedClientArgumentResolver.setClientCredentialsTokenResponseClient(accessTokenResponseClient); } argumentResolvers.add(authorizedClientArgumentResolver); } }
Source:
public Consumer<WebClient.Builder> oauth2Configuration() { START Hooks.onLastOperator(REQUEST_CONTEXT_OPERATOR_KEY, Operators.lift((s, sub) -> createRequestContextSubscriber(sub))); END return builder -> builder.defaultRequest(defaultRequest()).filter(this); } We can make this implement DisposableBean to clean up the hooks

Target:
public Consumer<WebClient.Builder> oauth2Configuration() { return builder -> builder.defaultRequest(defaultRequest()).filter(this); }
Source:
public void issuerWhenTokenEndpointAuthMethodsNoneThenMethodIsNone() throws Exception { this.response.put("token_endpoint_auth_methods_supported", Arrays.asList("none")); ClientRegistration registration = registration("") START .clientAuthenticationMethod(ClientAuthenticationMethod.NONE) END .build(); assertThat(registration.getClientAuthenticationMethod()).isEqualTo(ClientAuthenticationMethod.NONE); } This line should be removed to ensure `clientAuthenticationMethod` is `ClientAuthenticationMethod.NONE`

Target:
public void issuerWhenTokenEndpointAuthMethodsNoneThenMethodIsNone() throws Exception { this.response.put("token_endpoint_auth_methods_supported", Arrays.asList("none")); ClientRegistration registration = registration("").build(); assertThat(registration.getClientAuthenticationMethod()).isEqualTo(ClientAuthenticationMethod.NONE); }
Source:
public void writeHeadersWhenWhiteList() { START WhiteListedAllowFromStrategy whitelist = new WhiteListedAllowFromStrategy(Collections.singletonList("example.com")); END XFrameOptionsHeaderWriter writer = new XFrameOptionsHeaderWriter(whitelist); writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderValue(XFrameOptionsHeaderWriter.XFRAME_OPTIONS_HEADER)).isEqualTo("DENY"); } Is this change necessary for this PR? I see that you are using `Collections.singletonList` below in your test, but I'd recommend bringing other tests into conformance be in a different PR. (For example, you could also change old tests to refer to member variables via `this.`, but we aren't doing that here since that isn't the purpose of this PR)

Target:
public void writeHeadersWhenWhiteList() { WhiteListedAllowFromStrategy whitelist = new WhiteListedAllowFromStrategy(Arrays.asList("example.com")); XFrameOptionsHeaderWriter writer = new XFrameOptionsHeaderWriter(whitelist); writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeaderValue(XFrameOptionsHeaderWriter.XFRAME_OPTIONS_HEADER)).isEqualTo("DENY"); }
Source:
public void writeHeaders(HttpServletRequest request, HttpServletResponse response) { START headerWriters.forEach(headerWriter -> headerWriter.writeHeaders(request, response)); END } Just a quick reminder here, too, about `this`, so ```suggestion this.headerWriters.forEach(headerWriter -> headerWriter.writeHeaders(request, response)); ```

Target:
public void writeHeaders(HttpServletRequest request, HttpServletResponse response) { this.headerWriters.forEach(headerWriter -> headerWriter.writeHeaders(request, response)); }
Source:
public C requestMatchers(RequestMatcher... requestMatchers) { START if (!Objects.equals(requestMatchers[0], AnyRequestMatcher.INSTANCE)){ END Assert.state(!this.anyRequestConfigured, "Can't configure requestMatchers after anyRequest"); } return chainRequestMatchers(Arrays.asList(requestMatchers)); } @ankurpathak, this approach won't work because it changes the inheritance behavior. For example, if I had overridden `requestMatchers`, I may be expecting `anyMatcher` to call it (since it originally was). `anyMatcher` needs to continue to call `requestMatchers` in order to remain backwards compatible.

Target:
public C requestMatchers(RequestMatcher... requestMatchers) { Assert.state(!this.anyRequestConfigured, "Can't configure requestMatchers after anyRequest"); return chainRequestMatchers(Arrays.asList(requestMatchers)); }
Source:
public OAuth2IntrospectionAuthenticationToken(OAuth2AccessToken token, Map<String, Object> attributes, Collection<? extends GrantedAuthority> authorities) { this(token, attributes, authorities, null); START setAuthenticated(true); END } `setAuthenticated(true)` should get pushed to the 4 arg constructor.

Target:
public OAuth2IntrospectionAuthenticationToken(OAuth2AccessToken token, Map<String, Object> attributes, Collection<? extends GrantedAuthority> authorities) { this(token, attributes, authorities, null); }
Source:
public void setVariable(String name, @Nullable Object value) { START if (name == null) END throw new IllegalArgumentException("name should not be null"); else super.setVariable(name, value); } Please add `{` to follow Spring Security's code conventions

Target:
public void setVariable(String name, @Nullable Object value) { if ( name == null ) { throw new IllegalArgumentException("name should not be null"); } else { super.setVariable(name, value); } }
Source:
public HeaderBearerTokenResolver(String header) { START Assert.notNull(header, "header cannot be null"); END Assert.hasText(header, "header cannot be empty"); this.header = header; } Is there a need to have both asserts? The reason I'd prefer only one is that I don't want the user to get one error, fix it, and then get another. Since `nonNull` is implied by `hasText`, we can give the user only one error message that will repair both problems.

Target:
public HeaderBearerTokenResolver(String header) { Assert.hasText(header, "header cannot be empty"); this.header = header; }
Source:
START protected ServerOAuth2AuthorizedClientExchangeFilterFunction(ServerOAuth2AuthorizedClientRepository authorizedClientRepository, OAuth2AuthorizedClientResolver authorizedClientResolver) { END this.authorizedClientRepository = authorizedClientRepository; this.authorizedClientResolver = authorizedClientResolver; } Let's remove `protected` so it's package-private instead.

Target:
ServerOAuth2AuthorizedClientExchangeFilterFunction(ServerOAuth2AuthorizedClientRepository authorizedClientRepository, OAuth2AuthorizedClientResolver authorizedClientResolver) { this.authorizedClientRepository = authorizedClientRepository; this.authorizedClientResolver = authorizedClientResolver; }
Source:
public JdbcAclService(DataSource dataSource, LookupStrategy lookupStrategy) { Assert.notNull(dataSource, "DataSource required"); START Assert.notNull(lookupStrategy, "LookupStrategy required"); END this.jdbcOperations = new JdbcTemplate(dataSource); this.lookupStrategy = lookupStrategy; this.aclClassIdUtils = new AclClassIdUtils(); } This constructor can just invoke `this(new JdbcTemplate(dataSource), lookupStrategy)`

Target:
public JdbcAclService(DataSource dataSource, LookupStrategy lookupStrategy) { this(new JdbcTemplate(dataSource), lookupStrategy); }
Source:
START protected ReactiveAuthenticationManager getAuthenticationManager() { END if (this.authenticationManager == null) { ReactiveJwtDecoder jwtDecoder = getJwtDecoder(); ReactiveAuthenticationManager authenticationManager = new JwtReactiveAuthenticationManager(jwtDecoder); return authenticationManager; } return this.authenticationManager; } Can this be private?

Target:
private ReactiveAuthenticationManager getAuthenticationManager() { if (this.authenticationManager != null) { return this.authenticationManager; } ReactiveJwtDecoder jwtDecoder = getJwtDecoder(); ReactiveAuthenticationManager authenticationManager = new JwtReactiveAuthenticationManager(jwtDecoder); return authenticationManager; }
Source:
public static OAuth2AuthorizationRequest.Builder request() { String registrationId = "registration-id"; String clientId = "client-id"; Map<String, Object> additionalParameters = new HashMap<>(); additionalParameters.put(OAuth2ParameterNames.REGISTRATION_ID, registrationId); return OAuth2AuthorizationRequest.authorizationCode() .authorizationUri("https://example.com/login/oauth/authorize") .clientId(clientId) START .scope("openid") END .redirectUri("https://example.com/authorize/oauth2/code/registration-id") .state("state") .additionalParameters(additionalParameters); } Did you verify this isn't going to break any existing test assumptions? We probably shouldn't modify this as we don't know what impact this is having on existing tests. It may invalidate a test that has different expectations of the scopes.

Target:
public static OAuth2AuthorizationRequest.Builder request() { String registrationId = "registration-id"; String clientId = "client-id"; Map<String, Object> additionalParameters = new HashMap<>(); additionalParameters.put(OAuth2ParameterNames.REGISTRATION_ID, registrationId); return OAuth2AuthorizationRequest.authorizationCode() .authorizationUri("https://example.com/login/oauth/authorize") .clientId(clientId) .redirectUri("https://example.com/authorize/oauth2/code/registration-id") .state("state") .additionalParameters(additionalParameters); }