From 834dcf5bcf989f1595464aa548bcec666ad55465 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Thu, 30 Jul 2020 00:31:13 -0700 Subject: [PATCH] Use consistent ternary expression style Update all ternary expressions so that the condition is always in parentheses and "not equals" is used in the test. This helps to bring consistency across the codebase which makes ternary expression easier to scan. For example: `a = (a != null) ? a : b` Issue gh-8945 --- .../acls/domain/AccessControlEntryImpl.java | 2 +- .../security/acls/domain/AclImpl.java | 10 +++--- .../CasAuthenticationToken.java | 3 +- .../EhCacheBasedTicketCache.java | 2 +- .../SpringCacheBasedTicketCache.java | 4 +-- .../config/SecurityNamespaceHandler.java | 2 +- .../LdapAuthenticationProviderConfigurer.java | 4 +-- .../web/AbstractRequestMatcherRegistry.java | 4 +-- .../annotation/web/builders/WebSecurity.java | 4 +-- .../WebSecurityConfiguration.java | 2 +- .../web/configurers/JeeConfigurer.java | 2 +- .../web/configurers/RememberMeConfigurer.java | 4 +-- .../SecurityContextConfigurer.java | 4 +-- .../web/configurers/ServletApiConfigurer.java | 6 ++-- .../SessionManagementConfigurer.java | 2 +- .../client/ImplicitGrantConfigurer.java | 2 +- .../oauth2/client/OAuth2LoginConfigurer.java | 2 +- ...nvocationSecurityMetadataSourceParser.java | 4 +-- .../http/FormLoginBeanDefinitionParser.java | 2 +- .../http/HeadersBeanDefinitionParser.java | 26 +++++++-------- .../OAuth2ClientBeanDefinitionParser.java | 6 ++-- ...balMethodSecurityBeanDefinitionParser.java | 4 +-- ...ientRegistrationsBeanDefinitionParser.java | 6 ++-- .../config/web/server/ServerHttpSecurity.java | 4 +-- ...ageBrokerSecurityBeanDefinitionParser.java | 4 +-- .../OAuth2ClientConfigurationTests.java | 4 +-- ...OAuth2ClientBeanDefinitionParserTests.java | 2 +- .../OAuth2LoginBeanDefinitionParserTests.java | 2 +- .../server/HtmlUnitWebTestClient.java | 2 +- ...tExpressionBasedMethodConfigAttribute.java | 8 ++--- ...essionBasedAnnotationAttributeFactory.java | 17 +++++----- .../PostInvocationExpressionAttribute.java | 4 +-- .../PreInvocationExpressionAttribute.java | 4 +-- .../access/intercept/RunAsUserToken.java | 2 +- .../AbstractMethodSecurityMetadataSource.java | 2 +- ...elegatingMethodSecurityMetadataSource.java | 4 +-- ...rePostAdviceReactiveMethodInterceptor.java | 6 ++-- ...ePostAnnotationSecurityMetadataSource.java | 10 +++--- .../DefaultAuthenticationEventPublisher.java | 2 +- .../jaas/memory/InMemoryConfiguration.java | 2 +- .../rcp/RemoteAuthenticationProvider.java | 2 +- .../DelegatingSecurityContextCallable.java | 4 +-- .../DelegatingSecurityContextRunnable.java | 4 +-- .../core/SpringSecurityCoreVersion.java | 2 +- ...leAttributes2GrantedAuthoritiesMapper.java | 2 +- .../MapReactiveUserDetailsService.java | 2 +- .../cache/SpringCacheBasedUserCache.java | 2 +- .../security/util/SimpleMethodInvocation.java | 2 +- .../crypto/bcrypt/BCryptPasswordEncoder.java | 2 +- .../security/crypto/codec/Base64.java | 12 ++++--- .../crypto/encrypt/AesBytesEncryptor.java | 10 +++--- .../BouncyCastleAesCbcBytesEncryptor.java | 2 +- .../BouncyCastleAesGcmBytesEncryptor.java | 2 +- .../password/LdapShaPasswordEncoder.java | 2 +- etc/checkstyle/checkstyle-suppressions.xml | 1 - .../FilterChainPerformanceTests.java | 2 +- .../ldap/SpringSecurityLdapTemplate.java | 2 +- ...veDirectoryLdapAuthenticationProvider.java | 4 +-- .../search/FilterBasedLdapUserSearch.java | 2 +- .../ldap/userdetails/LdapAuthority.java | 2 +- .../NestedLdapAuthoritiesPopulator.java | 2 +- ...thenticationPrincipalArgumentResolver.java | 2 +- ...urrentSecurityContextArgumentResolver.java | 2 +- .../SimpDestinationMessageMatcher.java | 4 +-- .../web/csrf/CsrfChannelInterceptor.java | 4 +-- .../handler/invocation/ResolvableMethod.java | 8 ++--- ...2AuthorizationCodeAuthenticationToken.java | 2 +- ...sAuthorizationCodeTokenResponseClient.java | 4 +-- .../OAuth2RefreshTokenGrantRequest.java | 2 +- .../http/OAuth2ErrorResponseErrorHandler.java | 4 +-- .../OidcReactiveOAuth2UserService.java | 2 +- .../registration/ClientRegistration.java | 2 +- ...ultOAuth2AuthorizationRequestResolver.java | 10 +++--- ...ReactiveOAuth2AuthorizedClientManager.java | 2 +- ...nOAuth2AuthorizationRequestRepository.java | 4 +-- ...ssionOAuth2AuthorizedClientRepository.java | 4 +-- .../OAuth2AuthorizationCodeGrantFilter.java | 2 +- ...uthorizedClientExchangeFilterFunction.java | 2 +- ...verOAuth2AuthorizationRequestResolver.java | 8 ++--- ...erverOAuth2AuthorizedClientRepository.java | 4 +-- ...uth2AuthenticationExceptionMixinTests.java | 2 +- .../OAuth2AuthenticationTokenMixinTests.java | 6 ++-- .../OAuth2AuthorizationRequestMixinTests.java | 2 +- .../OAuth2AuthorizedClientMixinTests.java | 8 ++--- .../ClientRegistrationsTests.java | 4 +-- ...AuthorizedClientArgumentResolverTests.java | 4 +-- .../oauth2/core/AbstractOAuth2Token.java | 15 +++++---- .../DefaultOAuth2AuthenticatedPrincipal.java | 6 ++-- .../oauth2/core/OAuth2AccessToken.java | 2 +- .../security/oauth2/core/OAuth2Error.java | 2 +- .../converter/ObjectToStringConverter.java | 2 +- .../endpoint/OAuth2AccessTokenResponse.java | 5 +-- .../oidc/DefaultAddressStandardClaim.java | 33 ++++++++++--------- .../core/oidc/user/OidcUserAuthority.java | 5 +-- ...Auth2AccessTokenResponseBodyExtractor.java | 8 ++--- .../security/openid/OpenID4JavaConsumer.java | 2 +- .../ContextPropagatingRemoteInvocation.java | 2 +- .../util/matcher/PayloadExchangeMatcher.java | 4 ++- .../security/saml2/core/Saml2Error.java | 2 +- .../OpenSamlAuthenticationProvider.java | 4 +-- .../service/authentication/Saml2Error.java | 2 +- .../servlet/filter/Saml2ServletUtils.java | 8 ++--- ...faultRelyingPartyRegistrationResolver.java | 8 ++--- .../security/taglibs/TagLibConfig.java | 4 +-- ...hSecurityContextTestExecutionListener.java | 4 +-- .../SecurityMockMvcRequestPostProcessors.java | 2 +- ...ckMvcRequestPostProcessorsDigestTests.java | 4 +-- .../security/web/FilterChainProxy.java | 2 +- .../security/web/FilterInvocation.java | 4 +-- .../channel/AbstractRetryEntryPoint.java | 2 +- .../WebExpressionConfigAttribute.java | 2 +- .../web/access/intercept/RequestKey.java | 2 +- .../J2eePreAuthenticatedProcessingFilter.java | 2 +- .../AbstractRememberMeServices.java | 4 +-- .../TokenBasedRememberMeServices.java | 2 +- .../switchuser/SwitchUserFilter.java | 5 +-- .../ui/DefaultLoginPageGeneratingFilter.java | 2 +- .../web/csrf/CookieCsrfTokenRepository.java | 4 +-- .../web/firewall/DefaultHttpFirewall.java | 2 +- .../web/jackson2/CookieDeserializer.java | 6 +++- ...thenticationPrincipalArgumentResolver.java | 2 +- ...urrentSecurityContextArgumentResolver.java | 2 +- .../savedrequest/RequestCacheAwareFilter.java | 2 +- ...erverHttpBasicAuthenticationConverter.java | 2 +- .../csrf/CookieServerCsrfTokenRepository.java | 4 +-- .../CookieServerRequestCache.java | 2 +- .../WebSessionServerRequestCache.java | 2 +- .../util/matcher/MvcRequestMatcher.java | 2 +- .../web/util/OnCommittedResponseWrapper.java | 6 ++-- .../util/matcher/AntPathRequestMatcher.java | 4 +-- .../security/web/method/ResolvableMethod.java | 2 +- 131 files changed, 277 insertions(+), 265 deletions(-) diff --git a/acl/src/main/java/org/springframework/security/acls/domain/AccessControlEntryImpl.java b/acl/src/main/java/org/springframework/security/acls/domain/AccessControlEntryImpl.java index 98dcc1e874..e58d3d5562 100644 --- a/acl/src/main/java/org/springframework/security/acls/domain/AccessControlEntryImpl.java +++ b/acl/src/main/java/org/springframework/security/acls/domain/AccessControlEntryImpl.java @@ -125,7 +125,7 @@ public class AccessControlEntryImpl implements AccessControlEntry, AuditableAcce @Override public int hashCode() { int result = this.permission.hashCode(); - result = 31 * result + (this.id != null ? this.id.hashCode() : 0); + result = 31 * result + ((this.id != null) ? this.id.hashCode() : 0); result = 31 * result + (this.sid.hashCode()); result = 31 * result + (this.auditFailure ? 1 : 0); result = 31 * result + (this.auditSuccess ? 1 : 0); diff --git a/acl/src/main/java/org/springframework/security/acls/domain/AclImpl.java b/acl/src/main/java/org/springframework/security/acls/domain/AclImpl.java index 3ef40c7b47..bbba414e96 100644 --- a/acl/src/main/java/org/springframework/security/acls/domain/AclImpl.java +++ b/acl/src/main/java/org/springframework/security/acls/domain/AclImpl.java @@ -307,15 +307,15 @@ public class AclImpl implements Acl, MutableAcl, AuditableAcl, OwnershipAcl { @Override public int hashCode() { - int result = this.parentAcl != null ? this.parentAcl.hashCode() : 0; + int result = (this.parentAcl != null) ? this.parentAcl.hashCode() : 0; result = 31 * result + this.aclAuthorizationStrategy.hashCode(); result = 31 * result - + (this.permissionGrantingStrategy != null ? this.permissionGrantingStrategy.hashCode() : 0); - result = 31 * result + (this.aces != null ? this.aces.hashCode() : 0); + + ((this.permissionGrantingStrategy != null) ? this.permissionGrantingStrategy.hashCode() : 0); + result = 31 * result + ((this.aces != null) ? this.aces.hashCode() : 0); result = 31 * result + this.objectIdentity.hashCode(); result = 31 * result + this.id.hashCode(); - result = 31 * result + (this.owner != null ? this.owner.hashCode() : 0); - result = 31 * result + (this.loadedSids != null ? this.loadedSids.hashCode() : 0); + result = 31 * result + ((this.owner != null) ? this.owner.hashCode() : 0); + result = 31 * result + ((this.loadedSids != null) ? this.loadedSids.hashCode() : 0); result = 31 * result + (this.entriesInheriting ? 1 : 0); return result; } diff --git a/cas/src/main/java/org/springframework/security/cas/authentication/CasAuthenticationToken.java b/cas/src/main/java/org/springframework/security/cas/authentication/CasAuthenticationToken.java index f44403e829..1b35db4a77 100644 --- a/cas/src/main/java/org/springframework/security/cas/authentication/CasAuthenticationToken.java +++ b/cas/src/main/java/org/springframework/security/cas/authentication/CasAuthenticationToken.java @@ -26,6 +26,7 @@ import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.SpringSecurityCoreVersion; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.util.Assert; +import org.springframework.util.ObjectUtils; /** * Represents a successful CAS Authentication. @@ -141,7 +142,7 @@ public class CasAuthenticationToken extends AbstractAuthenticationToken implemen result = 31 * result + this.principal.hashCode(); result = 31 * result + this.userDetails.hashCode(); result = 31 * result + this.keyHash; - result = 31 * result + (this.assertion != null ? this.assertion.hashCode() : 0); + result = 31 * result + ObjectUtils.nullSafeHashCode(this.assertion); return result; } diff --git a/cas/src/main/java/org/springframework/security/cas/authentication/EhCacheBasedTicketCache.java b/cas/src/main/java/org/springframework/security/cas/authentication/EhCacheBasedTicketCache.java index 4d54de1aed..68fcd3caaf 100644 --- a/cas/src/main/java/org/springframework/security/cas/authentication/EhCacheBasedTicketCache.java +++ b/cas/src/main/java/org/springframework/security/cas/authentication/EhCacheBasedTicketCache.java @@ -49,7 +49,7 @@ public class EhCacheBasedTicketCache implements StatelessTicketCache, Initializi logger.debug("Cache hit: " + (element != null) + "; service ticket: " + serviceTicket); } - return element == null ? null : (CasAuthenticationToken) element.getValue(); + return (element != null) ? (CasAuthenticationToken) element.getValue() : null; } public Ehcache getCache() { diff --git a/cas/src/main/java/org/springframework/security/cas/authentication/SpringCacheBasedTicketCache.java b/cas/src/main/java/org/springframework/security/cas/authentication/SpringCacheBasedTicketCache.java index 35eb7b084e..33d3ce49a6 100644 --- a/cas/src/main/java/org/springframework/security/cas/authentication/SpringCacheBasedTicketCache.java +++ b/cas/src/main/java/org/springframework/security/cas/authentication/SpringCacheBasedTicketCache.java @@ -42,13 +42,13 @@ public class SpringCacheBasedTicketCache implements StatelessTicketCache { @Override public CasAuthenticationToken getByTicketId(final String serviceTicket) { - final Cache.ValueWrapper element = serviceTicket != null ? this.cache.get(serviceTicket) : null; + final Cache.ValueWrapper element = (serviceTicket != null) ? this.cache.get(serviceTicket) : null; if (logger.isDebugEnabled()) { logger.debug("Cache hit: " + (element != null) + "; service ticket: " + serviceTicket); } - return element == null ? null : (CasAuthenticationToken) element.get(); + return (element != null) ? (CasAuthenticationToken) element.get() : null; } @Override diff --git a/config/src/main/java/org/springframework/security/config/SecurityNamespaceHandler.java b/config/src/main/java/org/springframework/security/config/SecurityNamespaceHandler.java index 6bce596593..9273bee2af 100644 --- a/config/src/main/java/org/springframework/security/config/SecurityNamespaceHandler.java +++ b/config/src/main/java/org/springframework/security/config/SecurityNamespaceHandler.java @@ -151,7 +151,7 @@ public final class SecurityNamespaceHandler implements NamespaceHandler { private void reportUnsupportedNodeType(String name, ParserContext pc, Node node) { pc.getReaderContext().fatal("Security namespace does not support decoration of " - + (node instanceof Element ? "element" : "attribute") + " [" + name + "]", node); + + ((node instanceof Element) ? "element" : "attribute") + " [" + name + "]", node); } private void reportMissingWebClasses(String nodeName, ParserContext pc, Node node) { diff --git a/config/src/main/java/org/springframework/security/config/annotation/authentication/configurers/ldap/LdapAuthenticationProviderConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/authentication/configurers/ldap/LdapAuthenticationProviderConfigurer.java index 54a97b4d67..389a39eda6 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/authentication/configurers/ldap/LdapAuthenticationProviderConfigurer.java +++ b/config/src/main/java/org/springframework/security/config/annotation/authentication/configurers/ldap/LdapAuthenticationProviderConfigurer.java @@ -187,8 +187,8 @@ public class LdapAuthenticationProviderConfigurer { * @return a {@link List} of {@link AntPathRequestMatcher} instances */ static List antMatchers(HttpMethod httpMethod, String... antPatterns) { - String method = httpMethod == null ? null : httpMethod.toString(); + String method = (httpMethod != null) ? httpMethod.toString() : null; List matchers = new ArrayList<>(); for (String pattern : antPatterns) { matchers.add(new AntPathRequestMatcher(pattern, method)); @@ -275,7 +275,7 @@ public abstract class AbstractRequestMatcherRegistry { * @return a {@link List} of {@link RegexRequestMatcher} instances */ static List regexMatchers(HttpMethod httpMethod, String... regexPatterns) { - String method = httpMethod == null ? null : httpMethod.toString(); + String method = (httpMethod != null) ? httpMethod.toString() : null; List matchers = new ArrayList<>(); for (String pattern : regexPatterns) { matchers.add(new RegexRequestMatcher(pattern, method)); diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/builders/WebSecurity.java b/config/src/main/java/org/springframework/security/config/annotation/web/builders/WebSecurity.java index 0acebe06fd..5ff35ec68f 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/builders/WebSecurity.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/builders/WebSecurity.java @@ -242,8 +242,8 @@ public final class WebSecurity extends AbstractConfiguredSecurityBuilder clazz = (obj instanceof Class ? (Class) obj : obj.getClass()); + Class clazz = ((obj instanceof Class) ? (Class) obj : obj.getClass()); Order order = AnnotationUtils.findAnnotation(clazz, Order.class); if (order != null) { return order.value(); diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/JeeConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/JeeConfigurer.java index 0cf5b51224..078adc18b0 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/JeeConfigurer.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/JeeConfigurer.java @@ -230,7 +230,7 @@ public final class JeeConfigurer> extends Abstr * @return the {@link AuthenticationUserDetailsService} to use */ private AuthenticationUserDetailsService getUserDetailsService() { - return this.authenticationUserDetailsService == null + return (this.authenticationUserDetailsService != null) ? new PreAuthenticatedGrantedAuthoritiesUserDetailsService() : this.authenticationUserDetailsService; } diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/RememberMeConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/RememberMeConfigurer.java index f710b7a7a4..1c54f5e440 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/RememberMeConfigurer.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/RememberMeConfigurer.java @@ -369,8 +369,8 @@ public final class RememberMeConfigurer> * @return the {@link RememberMeServices} to use */ private AbstractRememberMeServices createRememberMeServices(H http, String key) { - return this.tokenRepository == null ? createTokenBasedRememberMeServices(http, key) - : createPersistentRememberMeServices(http, key); + return (this.tokenRepository != null) ? createPersistentRememberMeServices(http, key) + : createTokenBasedRememberMeServices(http, key); } /** diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/SecurityContextConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/SecurityContextConfigurer.java index 07dba22037..acd06c1221 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/SecurityContextConfigurer.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/SecurityContextConfigurer.java @@ -90,8 +90,8 @@ public final class SecurityContextConfigurer> SecurityContextPersistenceFilter securityContextFilter = new SecurityContextPersistenceFilter( securityContextRepository); SessionManagementConfigurer sessionManagement = http.getConfigurer(SessionManagementConfigurer.class); - SessionCreationPolicy sessionCreationPolicy = sessionManagement == null ? null - : sessionManagement.getSessionCreationPolicy(); + SessionCreationPolicy sessionCreationPolicy = (sessionManagement != null) + ? sessionManagement.getSessionCreationPolicy() : null; if (SessionCreationPolicy.ALWAYS == sessionCreationPolicy) { securityContextFilter.setForceEagerSessionCreation(true); } diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/ServletApiConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/ServletApiConfigurer.java index 3a3373d634..5959d9d08e 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/ServletApiConfigurer.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/ServletApiConfigurer.java @@ -80,11 +80,11 @@ public final class ServletApiConfigurer> public void configure(H http) { this.securityContextRequestFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class)); ExceptionHandlingConfigurer exceptionConf = http.getConfigurer(ExceptionHandlingConfigurer.class); - AuthenticationEntryPoint authenticationEntryPoint = exceptionConf == null ? null - : exceptionConf.getAuthenticationEntryPoint(http); + AuthenticationEntryPoint authenticationEntryPoint = (exceptionConf != null) + ? exceptionConf.getAuthenticationEntryPoint(http) : null; this.securityContextRequestFilter.setAuthenticationEntryPoint(authenticationEntryPoint); LogoutConfigurer logoutConf = http.getConfigurer(LogoutConfigurer.class); - List logoutHandlers = logoutConf == null ? null : logoutConf.getLogoutHandlers(); + List logoutHandlers = (logoutConf != null) ? logoutConf.getLogoutHandlers() : null; this.securityContextRequestFilter.setLogoutHandlers(logoutHandlers); AuthenticationTrustResolver trustResolver = http.getSharedObject(AuthenticationTrustResolver.class); if (trustResolver != null) { diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurer.java index c2484701e8..59146667e4 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurer.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurer.java @@ -451,7 +451,7 @@ public final class SessionManagementConfigurer> } SessionCreationPolicy sessionPolicy = getBuilder().getSharedObject(SessionCreationPolicy.class); - return sessionPolicy == null ? SessionCreationPolicy.IF_REQUIRED : sessionPolicy; + return (sessionPolicy != null) ? sessionPolicy : SessionCreationPolicy.IF_REQUIRED; } /** diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/ImplicitGrantConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/ImplicitGrantConfigurer.java index 9fd1e1ead2..51d151c9ed 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/ImplicitGrantConfigurer.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/ImplicitGrantConfigurer.java @@ -98,7 +98,7 @@ public final class ImplicitGrantConfigurer> } private String getAuthorizationRequestBaseUri() { - return this.authorizationRequestBaseUri != null ? this.authorizationRequestBaseUri + return (this.authorizationRequestBaseUri != null) ? this.authorizationRequestBaseUri : OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI; } diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/OAuth2LoginConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/OAuth2LoginConfigurer.java index 1d111b866a..bab025eff0 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/OAuth2LoginConfigurer.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/OAuth2LoginConfigurer.java @@ -500,7 +500,7 @@ public final class OAuth2LoginConfigurer> return Collections.emptyMap(); } - String authorizationRequestBaseUri = this.authorizationEndpointConfig.authorizationRequestBaseUri != null + String authorizationRequestBaseUri = (this.authorizationEndpointConfig.authorizationRequestBaseUri != null) ? this.authorizationEndpointConfig.authorizationRequestBaseUri : OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI; Map loginUrlToClientName = new HashMap<>(); diff --git a/config/src/main/java/org/springframework/security/config/http/FilterInvocationSecurityMetadataSourceParser.java b/config/src/main/java/org/springframework/security/config/http/FilterInvocationSecurityMetadataSourceParser.java index 6dad4e1ca0..f0dc125778 100644 --- a/config/src/main/java/org/springframework/security/config/http/FilterInvocationSecurityMetadataSourceParser.java +++ b/config/src/main/java/org/springframework/security/config/http/FilterInvocationSecurityMetadataSourceParser.java @@ -107,8 +107,8 @@ public class FilterInvocationSecurityMetadataSourceParser implements BeanDefinit if (useExpressions) { Element expressionHandlerElt = DomUtils.getChildElementByTagName(httpElt, Elements.EXPRESSION_HANDLER); - String expressionHandlerRef = expressionHandlerElt == null ? null - : expressionHandlerElt.getAttribute("ref"); + String expressionHandlerRef = (expressionHandlerElt != null) ? expressionHandlerElt.getAttribute("ref") + : null; if (StringUtils.hasText(expressionHandlerRef)) { logger.info( diff --git a/config/src/main/java/org/springframework/security/config/http/FormLoginBeanDefinitionParser.java b/config/src/main/java/org/springframework/security/config/http/FormLoginBeanDefinitionParser.java index bb3d74138b..c39c6a303a 100644 --- a/config/src/main/java/org/springframework/security/config/http/FormLoginBeanDefinitionParser.java +++ b/config/src/main/java/org/springframework/security/config/http/FormLoginBeanDefinitionParser.java @@ -168,7 +168,7 @@ public class FormLoginBeanDefinitionParser { BeanDefinitionBuilder entryPointBuilder = BeanDefinitionBuilder .rootBeanDefinition(LoginUrlAuthenticationEntryPoint.class); entryPointBuilder.getRawBeanDefinition().setSource(source); - entryPointBuilder.addConstructorArgValue(this.loginPage != null ? this.loginPage : DEF_LOGIN_PAGE); + entryPointBuilder.addConstructorArgValue((this.loginPage != null) ? this.loginPage : DEF_LOGIN_PAGE); entryPointBuilder.addPropertyValue("portMapper", this.portMapper); entryPointBuilder.addPropertyValue("portResolver", this.portResolver); this.entryPointBean = (RootBeanDefinition) entryPointBuilder.getBeanDefinition(); diff --git a/config/src/main/java/org/springframework/security/config/http/HeadersBeanDefinitionParser.java b/config/src/main/java/org/springframework/security/config/http/HeadersBeanDefinitionParser.java index d1a4d4c552..c4f96eba3a 100644 --- a/config/src/main/java/org/springframework/security/config/http/HeadersBeanDefinitionParser.java +++ b/config/src/main/java/org/springframework/security/config/http/HeadersBeanDefinitionParser.java @@ -177,8 +177,8 @@ public class HeadersBeanDefinitionParser implements BeanDefinitionParser { } private void parseCacheControlElement(boolean addIfNotPresent, Element element) { - Element cacheControlElement = element == null ? null - : DomUtils.getChildElementByTagName(element, CACHE_CONTROL_ELEMENT); + Element cacheControlElement = (element != null) + ? DomUtils.getChildElementByTagName(element, CACHE_CONTROL_ELEMENT) : null; boolean disabled = "true".equals(getAttribute(cacheControlElement, ATT_DISABLED, "false")); if (disabled) { return; @@ -195,7 +195,7 @@ public class HeadersBeanDefinitionParser implements BeanDefinitionParser { } private void parseHstsElement(boolean addIfNotPresent, Element element, ParserContext context) { - Element hstsElement = element == null ? null : DomUtils.getChildElementByTagName(element, HSTS_ELEMENT); + Element hstsElement = (element != null) ? DomUtils.getChildElementByTagName(element, HSTS_ELEMENT) : null; if (addIfNotPresent || hstsElement != null) { addHsts(addIfNotPresent, hstsElement, context); } @@ -244,7 +244,7 @@ public class HeadersBeanDefinitionParser implements BeanDefinitionParser { } private void parseHpkpElement(boolean addIfNotPresent, Element element, ParserContext context) { - Element hpkpElement = element == null ? null : DomUtils.getChildElementByTagName(element, HPKP_ELEMENT); + Element hpkpElement = (element != null) ? DomUtils.getChildElementByTagName(element, HPKP_ELEMENT) : null; if (addIfNotPresent || hpkpElement != null) { addHpkp(addIfNotPresent, hpkpElement, context); } @@ -342,8 +342,8 @@ public class HeadersBeanDefinitionParser implements BeanDefinitionParser { } private void parseReferrerPolicyElement(Element element, ParserContext context) { - Element referrerPolicyElement = (element == null) ? null - : DomUtils.getChildElementByTagName(element, REFERRER_POLICY_ELEMENT); + Element referrerPolicyElement = (element != null) + ? DomUtils.getChildElementByTagName(element, REFERRER_POLICY_ELEMENT) : null; if (referrerPolicyElement != null) { addReferrerPolicy(referrerPolicyElement, context); } @@ -361,8 +361,8 @@ public class HeadersBeanDefinitionParser implements BeanDefinitionParser { } private void parseFeaturePolicyElement(Element element, ParserContext context) { - Element featurePolicyElement = (element == null) ? null - : DomUtils.getChildElementByTagName(element, FEATURE_POLICY_ELEMENT); + Element featurePolicyElement = (element != null) + ? DomUtils.getChildElementByTagName(element, FEATURE_POLICY_ELEMENT) : null; if (featurePolicyElement != null) { addFeaturePolicy(featurePolicyElement, context); } @@ -390,8 +390,8 @@ public class HeadersBeanDefinitionParser implements BeanDefinitionParser { } private void parseHeaderElements(Element element) { - List headerElts = element == null ? Collections.emptyList() - : DomUtils.getChildElementsByTagName(element, GENERIC_HEADER_ELEMENT); + List headerElts = (element != null) + ? DomUtils.getChildElementsByTagName(element, GENERIC_HEADER_ELEMENT) : Collections.emptyList(); for (Element headerElt : headerElts) { String headerFactoryRef = headerElt.getAttribute(ATT_REF); if (StringUtils.hasText(headerFactoryRef)) { @@ -407,8 +407,8 @@ public class HeadersBeanDefinitionParser implements BeanDefinitionParser { } private void parseContentTypeOptionsElement(boolean addIfNotPresent, Element element) { - Element contentTypeElt = element == null ? null - : DomUtils.getChildElementByTagName(element, CONTENT_TYPE_ELEMENT); + Element contentTypeElt = (element != null) ? DomUtils.getChildElementByTagName(element, CONTENT_TYPE_ELEMENT) + : null; boolean disabled = "true".equals(getAttribute(contentTypeElt, ATT_DISABLED, "false")); if (disabled) { return; @@ -504,7 +504,7 @@ public class HeadersBeanDefinitionParser implements BeanDefinitionParser { } private void parseXssElement(boolean addIfNotPresent, Element element, ParserContext parserContext) { - Element xssElt = element == null ? null : DomUtils.getChildElementByTagName(element, XSS_ELEMENT); + Element xssElt = (element != null) ? DomUtils.getChildElementByTagName(element, XSS_ELEMENT) : null; BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(XXssProtectionHeaderWriter.class); if (xssElt != null) { boolean disabled = "true".equals(getAttribute(xssElt, ATT_DISABLED, "false")); diff --git a/config/src/main/java/org/springframework/security/config/http/OAuth2ClientBeanDefinitionParser.java b/config/src/main/java/org/springframework/security/config/http/OAuth2ClientBeanDefinitionParser.java index 4807a4bb6a..9122d28691 100644 --- a/config/src/main/java/org/springframework/security/config/http/OAuth2ClientBeanDefinitionParser.java +++ b/config/src/main/java/org/springframework/security/config/http/OAuth2ClientBeanDefinitionParser.java @@ -83,7 +83,7 @@ final class OAuth2ClientBeanDefinitionParser implements BeanDefinitionParser { BeanDefinitionBuilder authorizationRequestRedirectFilterBuilder = BeanDefinitionBuilder .rootBeanDefinition(OAuth2AuthorizationRequestRedirectFilter.class); - String authorizationRequestResolverRef = authorizationCodeGrantElt != null + String authorizationRequestResolverRef = (authorizationCodeGrantElt != null) ? authorizationCodeGrantElt.getAttribute(ATT_AUTHORIZATION_REQUEST_RESOLVER_REF) : null; if (!StringUtils.isEmpty(authorizationRequestResolverRef)) { authorizationRequestRedirectFilterBuilder.addConstructorArgReference(authorizationRequestResolverRef); @@ -112,7 +112,7 @@ final class OAuth2ClientBeanDefinitionParser implements BeanDefinitionParser { private BeanMetadataElement getAuthorizationRequestRepository(Element element) { BeanMetadataElement authorizationRequestRepository; - String authorizationRequestRepositoryRef = element != null + String authorizationRequestRepositoryRef = (element != null) ? element.getAttribute(ATT_AUTHORIZATION_REQUEST_REPOSITORY_REF) : null; if (!StringUtils.isEmpty(authorizationRequestRepositoryRef)) { authorizationRequestRepository = new RuntimeBeanReference(authorizationRequestRepositoryRef); @@ -127,7 +127,7 @@ final class OAuth2ClientBeanDefinitionParser implements BeanDefinitionParser { private BeanMetadataElement getAccessTokenResponseClient(Element element) { BeanMetadataElement accessTokenResponseClient; - String accessTokenResponseClientRef = element != null + String accessTokenResponseClientRef = (element != null) ? element.getAttribute(ATT_ACCESS_TOKEN_RESPONSE_CLIENT_REF) : null; if (!StringUtils.isEmpty(accessTokenResponseClientRef)) { accessTokenResponseClient = new RuntimeBeanReference(accessTokenResponseClientRef); diff --git a/config/src/main/java/org/springframework/security/config/method/GlobalMethodSecurityBeanDefinitionParser.java b/config/src/main/java/org/springframework/security/config/method/GlobalMethodSecurityBeanDefinitionParser.java index 62b0ed5286..fde8ab1571 100644 --- a/config/src/main/java/org/springframework/security/config/method/GlobalMethodSecurityBeanDefinitionParser.java +++ b/config/src/main/java/org/springframework/security/config/method/GlobalMethodSecurityBeanDefinitionParser.java @@ -178,8 +178,8 @@ public class GlobalMethodSecurityBeanDefinitionParser implements BeanDefinitionP } else { // The default expression-based system - String expressionHandlerRef = expressionHandlerElt == null ? null - : expressionHandlerElt.getAttribute("ref"); + String expressionHandlerRef = (expressionHandlerElt != null) ? expressionHandlerElt.getAttribute("ref") + : null; if (StringUtils.hasText(expressionHandlerRef)) { this.logger.info( diff --git a/config/src/main/java/org/springframework/security/config/oauth2/client/ClientRegistrationsBeanDefinitionParser.java b/config/src/main/java/org/springframework/security/config/oauth2/client/ClientRegistrationsBeanDefinitionParser.java index a8c3ff9473..8b0a0011f2 100644 --- a/config/src/main/java/org/springframework/security/config/oauth2/client/ClientRegistrationsBeanDefinitionParser.java +++ b/config/src/main/java/org/springframework/security/config/oauth2/client/ClientRegistrationsBeanDefinitionParser.java @@ -168,7 +168,7 @@ public final class ClientRegistrationsBeanDefinitionParser implements BeanDefini private static ClientRegistration.Builder getBuilderFromIssuerIfPossible(String registrationId, String configuredProviderId, Map> providers) { - String providerId = configuredProviderId != null ? configuredProviderId : registrationId; + String providerId = (configuredProviderId != null) ? configuredProviderId : registrationId; if (providers.containsKey(providerId)) { Map provider = providers.get(providerId); String issuer = provider.get(ATT_ISSUER_URI); @@ -188,7 +188,7 @@ public final class ClientRegistrationsBeanDefinitionParser implements BeanDefini if (provider == null && !providers.containsKey(providerId)) { return null; } - ClientRegistration.Builder builder = provider != null ? provider.getBuilder(registrationId) + ClientRegistration.Builder builder = (provider != null) ? provider.getBuilder(registrationId) : ClientRegistration.withRegistrationId(registrationId); if (providers.containsKey(providerId)) { return getBuilder(builder, providers.get(providerId)); @@ -251,7 +251,7 @@ public final class ClientRegistrationsBeanDefinitionParser implements BeanDefini } private static String getErrorMessage(String configuredProviderId, String registrationId) { - return configuredProviderId != null ? "Unknown provider ID '" + configuredProviderId + "'" + return (configuredProviderId != null) ? "Unknown provider ID '" + configuredProviderId + "'" : "Provider ID must be specified for client registration '" + registrationId + "'"; } diff --git a/config/src/main/java/org/springframework/security/config/web/server/ServerHttpSecurity.java b/config/src/main/java/org/springframework/security/config/web/server/ServerHttpSecurity.java index f9247744c6..507be8e960 100644 --- a/config/src/main/java/org/springframework/security/config/web/server/ServerHttpSecurity.java +++ b/config/src/main/java/org/springframework/security/config/web/server/ServerHttpSecurity.java @@ -1467,8 +1467,8 @@ public class ServerHttpSecurity { } private WebFilter securityContextRepositoryWebFilter() { - ServerSecurityContextRepository repository = this.securityContextRepository == null - ? new WebSessionServerSecurityContextRepository() : this.securityContextRepository; + ServerSecurityContextRepository repository = (this.securityContextRepository != null) + ? this.securityContextRepository : new WebSessionServerSecurityContextRepository(); WebFilter result = new ReactorContextWebFilter(repository); return new OrderedWebFilter(result, SecurityWebFiltersOrder.REACTOR_CONTEXT.getOrder()); } diff --git a/config/src/main/java/org/springframework/security/config/websocket/WebSocketMessageBrokerSecurityBeanDefinitionParser.java b/config/src/main/java/org/springframework/security/config/websocket/WebSocketMessageBrokerSecurityBeanDefinitionParser.java index 7d7426ecbc..a5316adec5 100644 --- a/config/src/main/java/org/springframework/security/config/websocket/WebSocketMessageBrokerSecurityBeanDefinitionParser.java +++ b/config/src/main/java/org/springframework/security/config/websocket/WebSocketMessageBrokerSecurityBeanDefinitionParser.java @@ -121,7 +121,7 @@ public final class WebSocketMessageBrokerSecurityBeanDefinitionParser implements String id = element.getAttribute(ID_ATTR); Element expressionHandlerElt = DomUtils.getChildElementByTagName(element, Elements.EXPRESSION_HANDLER); - String expressionHandlerRef = expressionHandlerElt == null ? null : expressionHandlerElt.getAttribute("ref"); + String expressionHandlerRef = (expressionHandlerElt != null) ? expressionHandlerElt.getAttribute("ref") : null; boolean expressionHandlerDefined = StringUtils.hasText(expressionHandlerRef); boolean sameOriginDisabled = Boolean.parseBoolean(element.getAttribute(DISABLED_ATTR)); @@ -252,7 +252,7 @@ public final class WebSocketMessageBrokerSecurityBeanDefinitionParser implements if (!registry.containsBeanDefinition(PATH_MATCHER_BEAN_NAME)) { PropertyValue pathMatcherProp = bd.getPropertyValues().getPropertyValue("pathMatcher"); - Object pathMatcher = pathMatcherProp == null ? null : pathMatcherProp.getValue(); + Object pathMatcher = (pathMatcherProp != null) ? pathMatcherProp.getValue() : null; if (pathMatcher instanceof BeanReference) { registry.registerAlias(((BeanReference) pathMatcher).getBeanName(), PATH_MATCHER_BEAN_NAME); } diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configuration/OAuth2ClientConfigurationTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configuration/OAuth2ClientConfigurationTests.java index 1b6955367d..bd872e58e4 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configuration/OAuth2ClientConfigurationTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configuration/OAuth2ClientConfigurationTests.java @@ -237,7 +237,7 @@ public class OAuth2ClientConfigurationTests { @GetMapping("/authorized-client") String authorizedClient( @RegisteredOAuth2AuthorizedClient("client1") OAuth2AuthorizedClient authorizedClient) { - return authorizedClient != null ? "resolved" : "not-resolved"; + return (authorizedClient != null) ? "resolved" : "not-resolved"; } } @@ -405,7 +405,7 @@ public class OAuth2ClientConfigurationTests { @GetMapping("/authorized-client") String authorizedClient( @RegisteredOAuth2AuthorizedClient("client1") OAuth2AuthorizedClient authorizedClient) { - return authorizedClient != null ? "resolved" : "not-resolved"; + return (authorizedClient != null) ? "resolved" : "not-resolved"; } } diff --git a/config/src/test/java/org/springframework/security/config/http/OAuth2ClientBeanDefinitionParserTests.java b/config/src/test/java/org/springframework/security/config/http/OAuth2ClientBeanDefinitionParserTests.java index 5d4a3568d4..0b0842641d 100644 --- a/config/src/test/java/org/springframework/security/config/http/OAuth2ClientBeanDefinitionParserTests.java +++ b/config/src/test/java/org/springframework/security/config/http/OAuth2ClientBeanDefinitionParserTests.java @@ -229,7 +229,7 @@ public class OAuth2ClientBeanDefinitionParserTests { @GetMapping("/authorized-client") String authorizedClient(Model model, @RegisteredOAuth2AuthorizedClient("google") OAuth2AuthorizedClient authorizedClient) { - return authorizedClient != null ? "resolved" : "not-resolved"; + return (authorizedClient != null) ? "resolved" : "not-resolved"; } } diff --git a/config/src/test/java/org/springframework/security/config/http/OAuth2LoginBeanDefinitionParserTests.java b/config/src/test/java/org/springframework/security/config/http/OAuth2LoginBeanDefinitionParserTests.java index 343c4d6469..190fd7e704 100644 --- a/config/src/test/java/org/springframework/security/config/http/OAuth2LoginBeanDefinitionParserTests.java +++ b/config/src/test/java/org/springframework/security/config/http/OAuth2LoginBeanDefinitionParserTests.java @@ -523,7 +523,7 @@ public class OAuth2LoginBeanDefinitionParserTests { @GetMapping("/authorized-client") String authorizedClient(Model model, @RegisteredOAuth2AuthorizedClient("google") OAuth2AuthorizedClient authorizedClient) { - return authorizedClient != null ? "resolved" : "not-resolved"; + return (authorizedClient != null) ? "resolved" : "not-resolved"; } } diff --git a/config/src/test/java/org/springframework/security/htmlunit/server/HtmlUnitWebTestClient.java b/config/src/test/java/org/springframework/security/htmlunit/server/HtmlUnitWebTestClient.java index 53c2b86913..4f673aa2ef 100644 --- a/config/src/test/java/org/springframework/security/htmlunit/server/HtmlUnitWebTestClient.java +++ b/config/src/test/java/org/springframework/security/htmlunit/server/HtmlUnitWebTestClient.java @@ -93,7 +93,7 @@ final class HtmlUnitWebTestClient { contentType = encodingType.getName(); } } - MediaType mediaType = contentType == null ? MediaType.ALL : MediaType.parseMediaType(contentType); + MediaType mediaType = (contentType != null) ? MediaType.parseMediaType(contentType) : MediaType.ALL; request.contentType(mediaType); } diff --git a/core/src/main/java/org/springframework/security/access/expression/method/AbstractExpressionBasedMethodConfigAttribute.java b/core/src/main/java/org/springframework/security/access/expression/method/AbstractExpressionBasedMethodConfigAttribute.java index a81fee098f..722505f22a 100644 --- a/core/src/main/java/org/springframework/security/access/expression/method/AbstractExpressionBasedMethodConfigAttribute.java +++ b/core/src/main/java/org/springframework/security/access/expression/method/AbstractExpressionBasedMethodConfigAttribute.java @@ -47,16 +47,16 @@ abstract class AbstractExpressionBasedMethodConfigAttribute implements ConfigAtt Assert.isTrue(filterExpression != null || authorizeExpression != null, "Filter and authorization Expressions cannot both be null"); SpelExpressionParser parser = new SpelExpressionParser(); - this.filterExpression = filterExpression == null ? null : parser.parseExpression(filterExpression); - this.authorizeExpression = authorizeExpression == null ? null : parser.parseExpression(authorizeExpression); + this.filterExpression = (filterExpression != null) ? parser.parseExpression(filterExpression) : null; + this.authorizeExpression = (authorizeExpression != null) ? parser.parseExpression(authorizeExpression) : null; } AbstractExpressionBasedMethodConfigAttribute(Expression filterExpression, Expression authorizeExpression) throws ParseException { Assert.isTrue(filterExpression != null || authorizeExpression != null, "Filter and authorization Expressions cannot both be null"); - this.filterExpression = filterExpression == null ? null : filterExpression; - this.authorizeExpression = authorizeExpression == null ? null : authorizeExpression; + this.filterExpression = (filterExpression != null) ? filterExpression : null; + this.authorizeExpression = (authorizeExpression != null) ? authorizeExpression : null; } Expression getFilterExpression() { diff --git a/core/src/main/java/org/springframework/security/access/expression/method/ExpressionBasedAnnotationAttributeFactory.java b/core/src/main/java/org/springframework/security/access/expression/method/ExpressionBasedAnnotationAttributeFactory.java index 56c61f1f58..d6fb761966 100644 --- a/core/src/main/java/org/springframework/security/access/expression/method/ExpressionBasedAnnotationAttributeFactory.java +++ b/core/src/main/java/org/springframework/security/access/expression/method/ExpressionBasedAnnotationAttributeFactory.java @@ -49,10 +49,10 @@ public class ExpressionBasedAnnotationAttributeFactory implements PrePostInvocat try { // TODO: Optimization of permitAll ExpressionParser parser = getParser(); - Expression preAuthorizeExpression = preAuthorizeAttribute == null ? parser.parseExpression("permitAll") - : parser.parseExpression(preAuthorizeAttribute); - Expression preFilterExpression = preFilterAttribute == null ? null - : parser.parseExpression(preFilterAttribute); + Expression preAuthorizeExpression = (preAuthorizeAttribute != null) + ? parser.parseExpression(preAuthorizeAttribute) : parser.parseExpression("permitAll"); + Expression preFilterExpression = (preFilterAttribute != null) ? parser.parseExpression(preFilterAttribute) + : null; return new PreInvocationExpressionAttribute(preFilterExpression, filterObject, preAuthorizeExpression); } catch (ParseException ex) { @@ -65,11 +65,10 @@ public class ExpressionBasedAnnotationAttributeFactory implements PrePostInvocat String postAuthorizeAttribute) { try { ExpressionParser parser = getParser(); - Expression postAuthorizeExpression = postAuthorizeAttribute == null ? null - : parser.parseExpression(postAuthorizeAttribute); - Expression postFilterExpression = postFilterAttribute == null ? null - : parser.parseExpression(postFilterAttribute); - + Expression postAuthorizeExpression = (postAuthorizeAttribute != null) + ? parser.parseExpression(postAuthorizeAttribute) : null; + Expression postFilterExpression = (postFilterAttribute != null) + ? parser.parseExpression(postFilterAttribute) : null; if (postFilterExpression != null || postAuthorizeExpression != null) { return new PostInvocationExpressionAttribute(postFilterExpression, postAuthorizeExpression); } diff --git a/core/src/main/java/org/springframework/security/access/expression/method/PostInvocationExpressionAttribute.java b/core/src/main/java/org/springframework/security/access/expression/method/PostInvocationExpressionAttribute.java index d85c22b21a..08d9c6f2b8 100644 --- a/core/src/main/java/org/springframework/security/access/expression/method/PostInvocationExpressionAttribute.java +++ b/core/src/main/java/org/springframework/security/access/expression/method/PostInvocationExpressionAttribute.java @@ -41,8 +41,8 @@ class PostInvocationExpressionAttribute extends AbstractExpressionBasedMethodCon StringBuilder sb = new StringBuilder(); Expression authorize = getAuthorizeExpression(); Expression filter = getFilterExpression(); - sb.append("[authorize: '").append(authorize == null ? "null" : authorize.getExpressionString()); - sb.append("', filter: '").append(filter == null ? "null" : filter.getExpressionString()).append("']"); + sb.append("[authorize: '").append((authorize != null) ? authorize.getExpressionString() : "null"); + sb.append("', filter: '").append((filter != null) ? filter.getExpressionString() : "null").append("']"); return sb.toString(); } diff --git a/core/src/main/java/org/springframework/security/access/expression/method/PreInvocationExpressionAttribute.java b/core/src/main/java/org/springframework/security/access/expression/method/PreInvocationExpressionAttribute.java index fdaeb4bf21..5f5ffc56cd 100644 --- a/core/src/main/java/org/springframework/security/access/expression/method/PreInvocationExpressionAttribute.java +++ b/core/src/main/java/org/springframework/security/access/expression/method/PreInvocationExpressionAttribute.java @@ -57,8 +57,8 @@ class PreInvocationExpressionAttribute extends AbstractExpressionBasedMethodConf StringBuilder sb = new StringBuilder(); Expression authorize = getAuthorizeExpression(); Expression filter = getFilterExpression(); - sb.append("[authorize: '").append(authorize == null ? "null" : authorize.getExpressionString()); - sb.append("', filter: '").append(filter == null ? "null" : filter.getExpressionString()); + sb.append("[authorize: '").append((authorize != null) ? authorize.getExpressionString() : "null"); + sb.append("', filter: '").append((filter != null) ? filter.getExpressionString() : "null"); sb.append("', filterTarget: '").append(this.filterTarget).append("']"); return sb.toString(); } diff --git a/core/src/main/java/org/springframework/security/access/intercept/RunAsUserToken.java b/core/src/main/java/org/springframework/security/access/intercept/RunAsUserToken.java index ecd683b892..31b145f84c 100644 --- a/core/src/main/java/org/springframework/security/access/intercept/RunAsUserToken.java +++ b/core/src/main/java/org/springframework/security/access/intercept/RunAsUserToken.java @@ -73,7 +73,7 @@ public class RunAsUserToken extends AbstractAuthenticationToken { @Override public String toString() { StringBuilder sb = new StringBuilder(super.toString()); - String className = this.originalAuthentication == null ? null : this.originalAuthentication.getName(); + String className = (this.originalAuthentication != null) ? this.originalAuthentication.getName() : null; sb.append("; Original Class: ").append(className); return sb.toString(); diff --git a/core/src/main/java/org/springframework/security/access/method/AbstractMethodSecurityMetadataSource.java b/core/src/main/java/org/springframework/security/access/method/AbstractMethodSecurityMetadataSource.java index 3b3a9809b4..9fc0775825 100644 --- a/core/src/main/java/org/springframework/security/access/method/AbstractMethodSecurityMetadataSource.java +++ b/core/src/main/java/org/springframework/security/access/method/AbstractMethodSecurityMetadataSource.java @@ -44,7 +44,7 @@ public abstract class AbstractMethodSecurityMetadataSource implements MethodSecu Class targetClass = null; if (target != null) { - targetClass = target instanceof Class ? (Class) target + targetClass = (target instanceof Class) ? (Class) target : AopProxyUtils.ultimateTargetClass(target); } Collection attrs = getAttributes(mi.getMethod(), targetClass); diff --git a/core/src/main/java/org/springframework/security/access/method/DelegatingMethodSecurityMetadataSource.java b/core/src/main/java/org/springframework/security/access/method/DelegatingMethodSecurityMetadataSource.java index 247f325ff9..583d140b31 100644 --- a/core/src/main/java/org/springframework/security/access/method/DelegatingMethodSecurityMetadataSource.java +++ b/core/src/main/java/org/springframework/security/access/method/DelegatingMethodSecurityMetadataSource.java @@ -122,12 +122,12 @@ public final class DelegatingMethodSecurityMetadataSource extends AbstractMethod @Override public int hashCode() { - return this.method.hashCode() * 21 + (this.targetClass != null ? this.targetClass.hashCode() : 0); + return this.method.hashCode() * 21 + ((this.targetClass != null) ? this.targetClass.hashCode() : 0); } @Override public String toString() { - return "CacheKey[" + (this.targetClass == null ? "-" : this.targetClass.getName()) + "; " + this.method + return "CacheKey[" + ((this.targetClass != null) ? this.targetClass.getName() : "-") + "; " + this.method + "]"; } diff --git a/core/src/main/java/org/springframework/security/access/prepost/PrePostAdviceReactiveMethodInterceptor.java b/core/src/main/java/org/springframework/security/access/prepost/PrePostAdviceReactiveMethodInterceptor.java index 9bd9efd203..0fc6e502a2 100644 --- a/core/src/main/java/org/springframework/security/access/prepost/PrePostAdviceReactiveMethodInterceptor.java +++ b/core/src/main/java/org/springframework/security/access/prepost/PrePostAdviceReactiveMethodInterceptor.java @@ -93,17 +93,17 @@ public class PrePostAdviceReactiveMethodInterceptor implements MethodInterceptor if (Mono.class.isAssignableFrom(returnType)) { return toInvoke.flatMap((auth) -> PrePostAdviceReactiveMethodInterceptor.>proceed(invocation) - .map((r) -> attr == null ? r : this.postAdvice.after(auth, invocation, attr, r))); + .map((r) -> (attr != null) ? this.postAdvice.after(auth, invocation, attr, r) : r)); } if (Flux.class.isAssignableFrom(returnType)) { return toInvoke.flatMapMany((auth) -> PrePostAdviceReactiveMethodInterceptor.>proceed(invocation) - .map((r) -> attr == null ? r : this.postAdvice.after(auth, invocation, attr, r))); + .map((r) -> (attr != null) ? this.postAdvice.after(auth, invocation, attr, r) : r)); } return toInvoke.flatMapMany( (auth) -> Flux.from(PrePostAdviceReactiveMethodInterceptor.>proceed(invocation)) - .map((r) -> attr == null ? r : this.postAdvice.after(auth, invocation, attr, r))); + .map((r) -> (attr != null) ? this.postAdvice.after(auth, invocation, attr, r) : r)); } private static > T proceed(final MethodInvocation invocation) { diff --git a/core/src/main/java/org/springframework/security/access/prepost/PrePostAnnotationSecurityMetadataSource.java b/core/src/main/java/org/springframework/security/access/prepost/PrePostAnnotationSecurityMetadataSource.java index 02dfcee031..ff12befce0 100644 --- a/core/src/main/java/org/springframework/security/access/prepost/PrePostAnnotationSecurityMetadataSource.java +++ b/core/src/main/java/org/springframework/security/access/prepost/PrePostAnnotationSecurityMetadataSource.java @@ -76,11 +76,11 @@ public class PrePostAnnotationSecurityMetadataSource extends AbstractMethodSecur return Collections.emptyList(); } - String preFilterAttribute = preFilter == null ? null : preFilter.value(); - String filterObject = preFilter == null ? null : preFilter.filterTarget(); - String preAuthorizeAttribute = preAuthorize == null ? null : preAuthorize.value(); - String postFilterAttribute = postFilter == null ? null : postFilter.value(); - String postAuthorizeAttribute = postAuthorize == null ? null : postAuthorize.value(); + String preFilterAttribute = (preFilter != null) ? preFilter.value() : null; + String filterObject = (preFilter != null) ? preFilter.filterTarget() : null; + String preAuthorizeAttribute = (preAuthorize != null) ? preAuthorize.value() : null; + String postFilterAttribute = (postFilter != null) ? postFilter.value() : null; + String postAuthorizeAttribute = (postAuthorize != null) ? postAuthorize.value() : null; ArrayList attrs = new ArrayList<>(2); diff --git a/core/src/main/java/org/springframework/security/authentication/DefaultAuthenticationEventPublisher.java b/core/src/main/java/org/springframework/security/authentication/DefaultAuthenticationEventPublisher.java index 23a6dd5f25..6e9049f7be 100644 --- a/core/src/main/java/org/springframework/security/authentication/DefaultAuthenticationEventPublisher.java +++ b/core/src/main/java/org/springframework/security/authentication/DefaultAuthenticationEventPublisher.java @@ -129,7 +129,7 @@ public class DefaultAuthenticationEventPublisher private Constructor getEventConstructor(AuthenticationException exception) { Constructor eventConstructor = this.exceptionMappings .get(exception.getClass().getName()); - return (eventConstructor == null ? this.defaultAuthenticationFailureEventConstructor : eventConstructor); + return (eventConstructor != null) ? eventConstructor : this.defaultAuthenticationFailureEventConstructor; } @Override diff --git a/core/src/main/java/org/springframework/security/authentication/jaas/memory/InMemoryConfiguration.java b/core/src/main/java/org/springframework/security/authentication/jaas/memory/InMemoryConfiguration.java index 9ea78bfd90..8aa767aaa7 100644 --- a/core/src/main/java/org/springframework/security/authentication/jaas/memory/InMemoryConfiguration.java +++ b/core/src/main/java/org/springframework/security/authentication/jaas/memory/InMemoryConfiguration.java @@ -80,7 +80,7 @@ public class InMemoryConfiguration extends Configuration { @Override public AppConfigurationEntry[] getAppConfigurationEntry(String name) { AppConfigurationEntry[] mappedResult = this.mappedConfigurations.get(name); - return mappedResult == null ? this.defaultConfiguration : mappedResult; + return (mappedResult != null) ? mappedResult : this.defaultConfiguration; } /** diff --git a/core/src/main/java/org/springframework/security/authentication/rcp/RemoteAuthenticationProvider.java b/core/src/main/java/org/springframework/security/authentication/rcp/RemoteAuthenticationProvider.java index c7ea764196..d68867bc7a 100644 --- a/core/src/main/java/org/springframework/security/authentication/rcp/RemoteAuthenticationProvider.java +++ b/core/src/main/java/org/springframework/security/authentication/rcp/RemoteAuthenticationProvider.java @@ -63,7 +63,7 @@ public class RemoteAuthenticationProvider implements AuthenticationProvider, Ini public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = authentication.getPrincipal().toString(); Object credentials = authentication.getCredentials(); - String password = credentials == null ? null : credentials.toString(); + String password = (credentials != null) ? credentials.toString() : null; Collection authorities = this.remoteAuthenticationManager .attemptAuthentication(username, password); diff --git a/core/src/main/java/org/springframework/security/concurrent/DelegatingSecurityContextCallable.java b/core/src/main/java/org/springframework/security/concurrent/DelegatingSecurityContextCallable.java index 977f1fb735..ea7a1a9849 100644 --- a/core/src/main/java/org/springframework/security/concurrent/DelegatingSecurityContextCallable.java +++ b/core/src/main/java/org/springframework/security/concurrent/DelegatingSecurityContextCallable.java @@ -113,8 +113,8 @@ public final class DelegatingSecurityContextCallable implements Callable { * @return */ public static Callable create(Callable delegate, SecurityContext securityContext) { - return securityContext == null ? new DelegatingSecurityContextCallable<>(delegate) - : new DelegatingSecurityContextCallable<>(delegate, securityContext); + return (securityContext != null) ? new DelegatingSecurityContextCallable<>(delegate, securityContext) + : new DelegatingSecurityContextCallable<>(delegate); } } diff --git a/core/src/main/java/org/springframework/security/concurrent/DelegatingSecurityContextRunnable.java b/core/src/main/java/org/springframework/security/concurrent/DelegatingSecurityContextRunnable.java index 6a4182dc3f..80def0d9cf 100644 --- a/core/src/main/java/org/springframework/security/concurrent/DelegatingSecurityContextRunnable.java +++ b/core/src/main/java/org/springframework/security/concurrent/DelegatingSecurityContextRunnable.java @@ -111,8 +111,8 @@ public final class DelegatingSecurityContextRunnable implements Runnable { */ public static Runnable create(Runnable delegate, SecurityContext securityContext) { Assert.notNull(delegate, "delegate cannot be null"); - return securityContext == null ? new DelegatingSecurityContextRunnable(delegate) - : new DelegatingSecurityContextRunnable(delegate, securityContext); + return (securityContext != null) ? new DelegatingSecurityContextRunnable(delegate, securityContext) + : new DelegatingSecurityContextRunnable(delegate); } } diff --git a/core/src/main/java/org/springframework/security/core/SpringSecurityCoreVersion.java b/core/src/main/java/org/springframework/security/core/SpringSecurityCoreVersion.java index 0fa679be95..d8c6fadf92 100644 --- a/core/src/main/java/org/springframework/security/core/SpringSecurityCoreVersion.java +++ b/core/src/main/java/org/springframework/security/core/SpringSecurityCoreVersion.java @@ -55,7 +55,7 @@ public final class SpringSecurityCoreVersion { public static String getVersion() { Package pkg = SpringSecurityCoreVersion.class.getPackage(); - return (pkg != null ? pkg.getImplementationVersion() : null); + return (pkg != null) ? pkg.getImplementationVersion() : null; } /** diff --git a/core/src/main/java/org/springframework/security/core/authority/mapping/SimpleAttributes2GrantedAuthoritiesMapper.java b/core/src/main/java/org/springframework/security/core/authority/mapping/SimpleAttributes2GrantedAuthoritiesMapper.java index 770e0e6d8f..c07137bb8f 100755 --- a/core/src/main/java/org/springframework/security/core/authority/mapping/SimpleAttributes2GrantedAuthoritiesMapper.java +++ b/core/src/main/java/org/springframework/security/core/authority/mapping/SimpleAttributes2GrantedAuthoritiesMapper.java @@ -109,7 +109,7 @@ public class SimpleAttributes2GrantedAuthoritiesMapper } private String getAttributePrefix() { - return this.attributePrefix == null ? "" : this.attributePrefix; + return (this.attributePrefix != null) ? this.attributePrefix : ""; } public void setAttributePrefix(String string) { diff --git a/core/src/main/java/org/springframework/security/core/userdetails/MapReactiveUserDetailsService.java b/core/src/main/java/org/springframework/security/core/userdetails/MapReactiveUserDetailsService.java index 6d543134bb..2b465afda5 100644 --- a/core/src/main/java/org/springframework/security/core/userdetails/MapReactiveUserDetailsService.java +++ b/core/src/main/java/org/springframework/security/core/userdetails/MapReactiveUserDetailsService.java @@ -67,7 +67,7 @@ public class MapReactiveUserDetailsService implements ReactiveUserDetailsService public Mono findByUsername(String username) { String key = getKey(username); UserDetails result = this.users.get(key); - return result == null ? Mono.empty() : Mono.just(User.withUserDetails(result).build()); + return (result != null) ? Mono.just(User.withUserDetails(result).build()) : Mono.empty(); } @Override diff --git a/core/src/main/java/org/springframework/security/core/userdetails/cache/SpringCacheBasedUserCache.java b/core/src/main/java/org/springframework/security/core/userdetails/cache/SpringCacheBasedUserCache.java index 6b4bdbdfd5..50f4b46464 100644 --- a/core/src/main/java/org/springframework/security/core/userdetails/cache/SpringCacheBasedUserCache.java +++ b/core/src/main/java/org/springframework/security/core/userdetails/cache/SpringCacheBasedUserCache.java @@ -43,7 +43,7 @@ public class SpringCacheBasedUserCache implements UserCache { @Override public UserDetails getUserFromCache(String username) { - Cache.ValueWrapper element = username != null ? this.cache.get(username) : null; + Cache.ValueWrapper element = (username != null) ? this.cache.get(username) : null; if (logger.isDebugEnabled()) { logger.debug("Cache hit: " + (element != null) + "; username: " + username); diff --git a/core/src/main/java/org/springframework/security/util/SimpleMethodInvocation.java b/core/src/main/java/org/springframework/security/util/SimpleMethodInvocation.java index 5a890f4dd9..37977d3881 100644 --- a/core/src/main/java/org/springframework/security/util/SimpleMethodInvocation.java +++ b/core/src/main/java/org/springframework/security/util/SimpleMethodInvocation.java @@ -37,7 +37,7 @@ public class SimpleMethodInvocation implements MethodInvocation { public SimpleMethodInvocation(Object targetObject, Method method, Object... arguments) { this.targetObject = targetObject; this.method = method; - this.arguments = arguments == null ? new Object[0] : arguments; + this.arguments = (arguments != null) ? arguments : new Object[0]; } public SimpleMethodInvocation() { diff --git a/crypto/src/main/java/org/springframework/security/crypto/bcrypt/BCryptPasswordEncoder.java b/crypto/src/main/java/org/springframework/security/crypto/bcrypt/BCryptPasswordEncoder.java index a60b2a89a7..43311f6f03 100644 --- a/crypto/src/main/java/org/springframework/security/crypto/bcrypt/BCryptPasswordEncoder.java +++ b/crypto/src/main/java/org/springframework/security/crypto/bcrypt/BCryptPasswordEncoder.java @@ -97,7 +97,7 @@ public class BCryptPasswordEncoder implements PasswordEncoder { throw new IllegalArgumentException("Bad strength"); } this.version = version; - this.strength = strength == -1 ? 10 : strength; + this.strength = (strength == -1) ? 10 : strength; this.random = random; } diff --git a/crypto/src/main/java/org/springframework/security/crypto/codec/Base64.java b/crypto/src/main/java/org/springframework/security/crypto/codec/Base64.java index 234882ceab..998b4df10e 100644 --- a/crypto/src/main/java/org/springframework/security/crypto/codec/Base64.java +++ b/crypto/src/main/java/org/springframework/security/crypto/codec/Base64.java @@ -333,9 +333,9 @@ public final class Base64 { // significant bytes passed in the array. // We have to shift left 24 in order to flush out the 1's that appear // when Java treats a value as negative that is cast from a byte to an int. - int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0) - | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0) - | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0); + int inBuff = ((numSigBytes > 0) ? ((source[srcOffset] << 24) >>> 8) : 0) + | ((numSigBytes > 1) ? ((source[srcOffset + 1] << 24) >>> 16) : 0) + | ((numSigBytes > 2) ? ((source[srcOffset + 2] << 24) >>> 24) : 0); switch (numSigBytes) { case 3: @@ -404,8 +404,10 @@ public final class Base64 { // Try to determine more precisely how big the array needs to be. // If we get it right, we don't have to do an array copy, and // we save a bunch of memory. - int encLen = (len / 3) * 4 + (len % 3 > 0 ? 4 : 0); // Bytes needed for actual - // encoding + + // Bytes needed for actual encoding + int encLen = (len / 3) * 4 + ((len % 3 > 0) ? 4 : 0); + if (breakLines) { encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters } diff --git a/crypto/src/main/java/org/springframework/security/crypto/encrypt/AesBytesEncryptor.java b/crypto/src/main/java/org/springframework/security/crypto/encrypt/AesBytesEncryptor.java index bf7506bddf..bed724b6af 100644 --- a/crypto/src/main/java/org/springframework/security/crypto/encrypt/AesBytesEncryptor.java +++ b/crypto/src/main/java/org/springframework/security/crypto/encrypt/AesBytesEncryptor.java @@ -71,7 +71,7 @@ public final class AesBytesEncryptor implements BytesEncryptor { } public AlgorithmParameterSpec getParameterSpec(byte[] iv) { - return this == CBC ? new IvParameterSpec(iv) : new GCMParameterSpec(128, iv); + return (this != CBC) ? new GCMParameterSpec(128, iv) : new IvParameterSpec(iv); } public Cipher createCipher() { @@ -110,7 +110,7 @@ public final class AesBytesEncryptor implements BytesEncryptor { this.alg = alg; this.encryptor = alg.createCipher(); this.decryptor = alg.createCipher(); - this.ivGenerator = ivGenerator != null ? ivGenerator : alg.defaultIvGenerator(); + this.ivGenerator = (ivGenerator != null) ? ivGenerator : alg.defaultIvGenerator(); } @Override @@ -119,7 +119,7 @@ public final class AesBytesEncryptor implements BytesEncryptor { byte[] iv = this.ivGenerator.generateKey(); CipherUtils.initCipher(this.encryptor, Cipher.ENCRYPT_MODE, this.secretKey, this.alg.getParameterSpec(iv)); byte[] encrypted = CipherUtils.doFinal(this.encryptor, bytes); - return this.ivGenerator != NULL_IV_GENERATOR ? EncodingUtils.concatenate(iv, encrypted) : encrypted; + return (this.ivGenerator != NULL_IV_GENERATOR) ? EncodingUtils.concatenate(iv, encrypted) : encrypted; } } @@ -129,12 +129,12 @@ public final class AesBytesEncryptor implements BytesEncryptor { byte[] iv = iv(encryptedBytes); CipherUtils.initCipher(this.decryptor, Cipher.DECRYPT_MODE, this.secretKey, this.alg.getParameterSpec(iv)); return CipherUtils.doFinal(this.decryptor, - this.ivGenerator != NULL_IV_GENERATOR ? encrypted(encryptedBytes, iv.length) : encryptedBytes); + (this.ivGenerator != NULL_IV_GENERATOR) ? encrypted(encryptedBytes, iv.length) : encryptedBytes); } } private byte[] iv(byte[] encrypted) { - return this.ivGenerator != NULL_IV_GENERATOR + return (this.ivGenerator != NULL_IV_GENERATOR) ? EncodingUtils.subArray(encrypted, 0, this.ivGenerator.getKeyLength()) : NULL_IV_GENERATOR.generateKey(); } diff --git a/crypto/src/main/java/org/springframework/security/crypto/encrypt/BouncyCastleAesCbcBytesEncryptor.java b/crypto/src/main/java/org/springframework/security/crypto/encrypt/BouncyCastleAesCbcBytesEncryptor.java index 26b0f310a5..84181d885b 100644 --- a/crypto/src/main/java/org/springframework/security/crypto/encrypt/BouncyCastleAesCbcBytesEncryptor.java +++ b/crypto/src/main/java/org/springframework/security/crypto/encrypt/BouncyCastleAesCbcBytesEncryptor.java @@ -54,7 +54,7 @@ public class BouncyCastleAesCbcBytesEncryptor extends BouncyCastleAesBytesEncryp new CBCBlockCipher(new org.bouncycastle.crypto.engines.AESFastEngine()), new PKCS7Padding()); blockCipher.init(true, new ParametersWithIV(this.secretKey, iv)); byte[] encrypted = process(blockCipher, bytes); - return iv != null ? EncodingUtils.concatenate(iv, encrypted) : encrypted; + return (iv != null) ? EncodingUtils.concatenate(iv, encrypted) : encrypted; } @Override diff --git a/crypto/src/main/java/org/springframework/security/crypto/encrypt/BouncyCastleAesGcmBytesEncryptor.java b/crypto/src/main/java/org/springframework/security/crypto/encrypt/BouncyCastleAesGcmBytesEncryptor.java index b9d954691c..044d6a2a77 100644 --- a/crypto/src/main/java/org/springframework/security/crypto/encrypt/BouncyCastleAesGcmBytesEncryptor.java +++ b/crypto/src/main/java/org/springframework/security/crypto/encrypt/BouncyCastleAesGcmBytesEncryptor.java @@ -52,7 +52,7 @@ public class BouncyCastleAesGcmBytesEncryptor extends BouncyCastleAesBytesEncryp blockCipher.init(true, new AEADParameters(this.secretKey, 128, iv, null)); byte[] encrypted = process(blockCipher, bytes); - return iv != null ? EncodingUtils.concatenate(iv, encrypted) : encrypted; + return (iv != null) ? EncodingUtils.concatenate(iv, encrypted) : encrypted; } @Override diff --git a/crypto/src/main/java/org/springframework/security/crypto/password/LdapShaPasswordEncoder.java b/crypto/src/main/java/org/springframework/security/crypto/password/LdapShaPasswordEncoder.java index 8e0a7ec7de..808e908c05 100644 --- a/crypto/src/main/java/org/springframework/security/crypto/password/LdapShaPasswordEncoder.java +++ b/crypto/src/main/java/org/springframework/security/crypto/password/LdapShaPasswordEncoder.java @@ -146,7 +146,7 @@ public class LdapShaPasswordEncoder implements PasswordEncoder { */ @Override public boolean matches(CharSequence rawPassword, String encodedPassword) { - return matches(rawPassword == null ? null : rawPassword.toString(), encodedPassword); + return matches((rawPassword != null) ? rawPassword.toString() : null, encodedPassword); } private boolean matches(String rawPassword, String encodedPassword) { diff --git a/etc/checkstyle/checkstyle-suppressions.xml b/etc/checkstyle/checkstyle-suppressions.xml index 1a11e02cca..ec81d6574e 100644 --- a/etc/checkstyle/checkstyle-suppressions.xml +++ b/etc/checkstyle/checkstyle-suppressions.xml @@ -3,7 +3,6 @@ "-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN" "https://checkstyle.org/dtds/suppressions_1_2.dtd"> - diff --git a/itest/context/src/integration-test/java/org/springframework/security/performance/FilterChainPerformanceTests.java b/itest/context/src/integration-test/java/org/springframework/security/performance/FilterChainPerformanceTests.java index 782668e307..eb0f760253 100644 --- a/itest/context/src/integration-test/java/org/springframework/security/performance/FilterChainPerformanceTests.java +++ b/itest/context/src/integration-test/java/org/springframework/security/performance/FilterChainPerformanceTests.java @@ -128,7 +128,7 @@ public class FilterChainPerformanceTests { public void provideDataOnScalingWithNumberOfAuthoritiesUserHas() throws Exception { StopWatch sw = new StopWatch("Scaling with nAuthorities"); for (int user = 0; user < N_AUTHORITIES / 10; user++) { - int nAuthorities = user == 0 ? 1 : user * 10; + int nAuthorities = (user != 0) ? user * 10 : 1; SecurityContextHolder.getContext().setAuthentication( new UsernamePasswordAuthenticationToken("bob", "bobspassword", createRoles(nAuthorities))); this.session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, diff --git a/ldap/src/main/java/org/springframework/security/ldap/SpringSecurityLdapTemplate.java b/ldap/src/main/java/org/springframework/security/ldap/SpringSecurityLdapTemplate.java index 7c21ead437..ce0b69e61b 100644 --- a/ldap/src/main/java/org/springframework/security/ldap/SpringSecurityLdapTemplate.java +++ b/ldap/src/main/java/org/springframework/security/ldap/SpringSecurityLdapTemplate.java @@ -214,7 +214,7 @@ public class SpringSecurityLdapTemplate extends LdapTemplate { SearchControls ctls = new SearchControls(); ctls.setSearchScope(this.searchControls.getSearchScope()); - ctls.setReturningAttributes(attributeNames != null && attributeNames.length > 0 ? attributeNames : null); + ctls.setReturningAttributes((attributeNames != null && attributeNames.length > 0) ? attributeNames : null); search(base, formattedFilter, ctls, roleMapper); diff --git a/ldap/src/main/java/org/springframework/security/ldap/authentication/ad/ActiveDirectoryLdapAuthenticationProvider.java b/ldap/src/main/java/org/springframework/security/ldap/authentication/ad/ActiveDirectoryLdapAuthenticationProvider.java index f8d658ff4c..40b82b5d01 100644 --- a/ldap/src/main/java/org/springframework/security/ldap/authentication/ad/ActiveDirectoryLdapAuthenticationProvider.java +++ b/ldap/src/main/java/org/springframework/security/ldap/authentication/ad/ActiveDirectoryLdapAuthenticationProvider.java @@ -153,7 +153,7 @@ public final class ActiveDirectoryLdapAuthenticationProvider extends AbstractLda Assert.isTrue(StringUtils.hasText(url), "Url cannot be empty"); this.domain = StringUtils.hasText(domain) ? domain.toLowerCase() : null; this.url = url; - this.rootDn = this.domain == null ? null : rootDnFromDomain(this.domain); + this.rootDn = (this.domain != null) ? rootDnFromDomain(this.domain) : null; } @Override @@ -336,7 +336,7 @@ public final class ActiveDirectoryLdapAuthenticationProvider extends AbstractLda searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); String bindPrincipal = createBindPrincipal(username); - String searchRoot = this.rootDn != null ? this.rootDn : searchRootFromPrincipal(bindPrincipal); + String searchRoot = (this.rootDn != null) ? this.rootDn : searchRootFromPrincipal(bindPrincipal); try { return SpringSecurityLdapTemplate.searchForSingleEntryInternal(context, searchControls, searchRoot, diff --git a/ldap/src/main/java/org/springframework/security/ldap/search/FilterBasedLdapUserSearch.java b/ldap/src/main/java/org/springframework/security/ldap/search/FilterBasedLdapUserSearch.java index 22bb16229d..6475ae7546 100644 --- a/ldap/src/main/java/org/springframework/security/ldap/search/FilterBasedLdapUserSearch.java +++ b/ldap/src/main/java/org/springframework/security/ldap/search/FilterBasedLdapUserSearch.java @@ -165,7 +165,7 @@ public class FilterBasedLdapUserSearch implements LdapUserSearch { sb.append("[ searchFilter: '").append(this.searchFilter).append("', "); sb.append("searchBase: '").append(this.searchBase).append("'"); sb.append(", scope: ").append( - this.searchControls.getSearchScope() == SearchControls.SUBTREE_SCOPE ? "subtree" : "single-level, "); + (this.searchControls.getSearchScope() != SearchControls.SUBTREE_SCOPE) ? "single-level, " : "subtree"); sb.append(", searchTimeLimit: ").append(this.searchControls.getTimeLimit()); sb.append(", derefLinkFlag: ").append(this.searchControls.getDerefLinkFlag()).append(" ]"); return sb.toString(); diff --git a/ldap/src/main/java/org/springframework/security/ldap/userdetails/LdapAuthority.java b/ldap/src/main/java/org/springframework/security/ldap/userdetails/LdapAuthority.java index a78c1ef47c..e60b6c8f2c 100644 --- a/ldap/src/main/java/org/springframework/security/ldap/userdetails/LdapAuthority.java +++ b/ldap/src/main/java/org/springframework/security/ldap/userdetails/LdapAuthority.java @@ -140,7 +140,7 @@ public class LdapAuthority implements GrantedAuthority { @Override public int hashCode() { int result = this.dn.hashCode(); - result = 31 * result + (this.role != null ? this.role.hashCode() : 0); + result = 31 * result + ((this.role != null) ? this.role.hashCode() : 0); return result; } diff --git a/ldap/src/main/java/org/springframework/security/ldap/userdetails/NestedLdapAuthoritiesPopulator.java b/ldap/src/main/java/org/springframework/security/ldap/userdetails/NestedLdapAuthoritiesPopulator.java index 8fc0a4c76e..0507597bf0 100644 --- a/ldap/src/main/java/org/springframework/security/ldap/userdetails/NestedLdapAuthoritiesPopulator.java +++ b/ldap/src/main/java/org/springframework/security/ldap/userdetails/NestedLdapAuthoritiesPopulator.java @@ -216,7 +216,7 @@ public class NestedLdapAuthoritiesPopulator extends DefaultLdapAuthoritiesPopula // this prevents a forever loop for a misconfigured ldap directory circular = circular | (!authorities.add(new LdapAuthority(role, dn, record))); } - String roleName = roles.size() > 0 ? roles.iterator().next() : dn; + String roleName = (roles.size() > 0) ? roles.iterator().next() : dn; if (!circular) { performNestedSearch(dn, roleName, authorities, (depth - 1)); } diff --git a/messaging/src/main/java/org/springframework/security/messaging/handler/invocation/reactive/AuthenticationPrincipalArgumentResolver.java b/messaging/src/main/java/org/springframework/security/messaging/handler/invocation/reactive/AuthenticationPrincipalArgumentResolver.java index 4f5b14bd5a..237b79cc13 100644 --- a/messaging/src/main/java/org/springframework/security/messaging/handler/invocation/reactive/AuthenticationPrincipalArgumentResolver.java +++ b/messaging/src/main/java/org/springframework/security/messaging/handler/invocation/reactive/AuthenticationPrincipalArgumentResolver.java @@ -128,7 +128,7 @@ public class AuthenticationPrincipalArgumentResolver implements HandlerMethodArg return ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication).flatMap((a) -> { Object p = resolvePrincipal(parameter, a.getPrincipal()); Mono principal = Mono.justOrEmpty(p); - return adapter == null ? principal : Mono.just(adapter.fromPublisher(principal)); + return (adapter != null) ? Mono.just(adapter.fromPublisher(principal)) : principal; }); } diff --git a/messaging/src/main/java/org/springframework/security/messaging/handler/invocation/reactive/CurrentSecurityContextArgumentResolver.java b/messaging/src/main/java/org/springframework/security/messaging/handler/invocation/reactive/CurrentSecurityContextArgumentResolver.java index 21165e9363..4b835e3f97 100644 --- a/messaging/src/main/java/org/springframework/security/messaging/handler/invocation/reactive/CurrentSecurityContextArgumentResolver.java +++ b/messaging/src/main/java/org/springframework/security/messaging/handler/invocation/reactive/CurrentSecurityContextArgumentResolver.java @@ -127,7 +127,7 @@ public class CurrentSecurityContextArgumentResolver implements HandlerMethodArgu return ReactiveSecurityContextHolder.getContext().flatMap((securityContext) -> { Object sc = resolveSecurityContext(parameter, securityContext); Mono result = Mono.justOrEmpty(sc); - return adapter == null ? result : Mono.just(adapter.fromPublisher(result)); + return (adapter != null) ? Mono.just(adapter.fromPublisher(result)) : result; }); } diff --git a/messaging/src/main/java/org/springframework/security/messaging/util/matcher/SimpDestinationMessageMatcher.java b/messaging/src/main/java/org/springframework/security/messaging/util/matcher/SimpDestinationMessageMatcher.java index 12aea1f659..39a52b3beb 100644 --- a/messaging/src/main/java/org/springframework/security/messaging/util/matcher/SimpDestinationMessageMatcher.java +++ b/messaging/src/main/java/org/springframework/security/messaging/util/matcher/SimpDestinationMessageMatcher.java @@ -113,7 +113,7 @@ public final class SimpDestinationMessageMatcher implements MessageMatcher extractPathVariables(Message message) { final String destination = SimpMessageHeaderAccessor.getDestination(message.getHeaders()); - return destination != null ? this.matcher.extractUriTemplateVariables(this.pattern, destination) + return (destination != null) ? this.matcher.extractUriTemplateVariables(this.pattern, destination) : Collections.emptyMap(); } diff --git a/messaging/src/main/java/org/springframework/security/messaging/web/csrf/CsrfChannelInterceptor.java b/messaging/src/main/java/org/springframework/security/messaging/web/csrf/CsrfChannelInterceptor.java index 9fc3169b81..e9b26e7f2f 100644 --- a/messaging/src/main/java/org/springframework/security/messaging/web/csrf/CsrfChannelInterceptor.java +++ b/messaging/src/main/java/org/springframework/security/messaging/web/csrf/CsrfChannelInterceptor.java @@ -48,8 +48,8 @@ public final class CsrfChannelInterceptor extends ChannelInterceptorAdapter { } Map sessionAttributes = SimpMessageHeaderAccessor.getSessionAttributes(message.getHeaders()); - CsrfToken expectedToken = sessionAttributes == null ? null - : (CsrfToken) sessionAttributes.get(CsrfToken.class.getName()); + CsrfToken expectedToken = (sessionAttributes != null) + ? (CsrfToken) sessionAttributes.get(CsrfToken.class.getName()) : null; if (expectedToken == null) { throw new MissingCsrfTokenException(null); diff --git a/messaging/src/test/java/org/springframework/security/messaging/handler/invocation/ResolvableMethod.java b/messaging/src/test/java/org/springframework/security/messaging/handler/invocation/ResolvableMethod.java index 2dde084f5d..a22a63ee0a 100644 --- a/messaging/src/test/java/org/springframework/security/messaging/handler/invocation/ResolvableMethod.java +++ b/messaging/src/test/java/org/springframework/security/messaging/handler/invocation/ResolvableMethod.java @@ -220,10 +220,10 @@ public final class ResolvableMethod { private String formatParameter(Parameter param) { Annotation[] anns = param.getAnnotations(); - return (anns.length > 0 + return (anns.length > 0) ? Arrays.stream(anns).map(this::formatAnnotation).collect(Collectors.joining(",", "[", "]")) + " " + param - : param.toString()); + : param.toString(); } private String formatAnnotation(Annotation annotation) { @@ -591,9 +591,9 @@ public final class ResolvableMethod { */ @SafeVarargs public final ArgResolver annotNotPresent(Class... annotationTypes) { - this.filters.add((param) -> (annotationTypes.length > 0 + this.filters.add((param) -> (annotationTypes.length > 0) ? Arrays.stream(annotationTypes).noneMatch(param::hasParameterAnnotation) - : param.getParameterAnnotations().length == 0)); + : param.getParameterAnnotations().length == 0); return this; } diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeAuthenticationToken.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeAuthenticationToken.java index 574b0b4900..9d5fe681b6 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeAuthenticationToken.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeAuthenticationToken.java @@ -114,7 +114,7 @@ public class OAuth2AuthorizationCodeAuthenticationToken extends AbstractAuthenti @Override public Object getCredentials() { - return this.accessToken != null ? this.accessToken.getTokenValue() + return (this.accessToken != null) ? this.accessToken.getTokenValue() : this.authorizationExchange.getAuthorizationResponse().getCode(); } diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/NimbusAuthorizationCodeTokenResponseClient.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/NimbusAuthorizationCodeTokenResponseClient.java index c4ae9d881b..83c38dbe43 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/NimbusAuthorizationCodeTokenResponseClient.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/NimbusAuthorizationCodeTokenResponseClient.java @@ -128,9 +128,9 @@ public class NimbusAuthorizationCodeTokenResponseClient } else { oauth2Error = new OAuth2Error( - errorObject.getCode() != null ? errorObject.getCode() : OAuth2ErrorCodes.SERVER_ERROR, + (errorObject.getCode() != null) ? errorObject.getCode() : OAuth2ErrorCodes.SERVER_ERROR, errorObject.getDescription(), - errorObject.getURI() != null ? errorObject.getURI().toString() : null); + (errorObject.getURI() != null) ? errorObject.getURI().toString() : null); } throw new OAuth2AuthorizationException(oauth2Error); } diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/OAuth2RefreshTokenGrantRequest.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/OAuth2RefreshTokenGrantRequest.java index c24defbdb3..5bb5d12758 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/OAuth2RefreshTokenGrantRequest.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/OAuth2RefreshTokenGrantRequest.java @@ -75,7 +75,7 @@ public class OAuth2RefreshTokenGrantRequest extends AbstractOAuth2AuthorizationG this.accessToken = accessToken; this.refreshToken = refreshToken; this.scopes = Collections - .unmodifiableSet(scopes != null ? new LinkedHashSet<>(scopes) : Collections.emptySet()); + .unmodifiableSet((scopes != null) ? new LinkedHashSet<>(scopes) : Collections.emptySet()); } /** diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/http/OAuth2ErrorResponseErrorHandler.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/http/OAuth2ErrorResponseErrorHandler.java index 1b5135a56f..95464eeb74 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/http/OAuth2ErrorResponseErrorHandler.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/http/OAuth2ErrorResponseErrorHandler.java @@ -80,10 +80,10 @@ public class OAuth2ErrorResponseErrorHandler implements ResponseErrorHandler { return null; } - String errorCode = bearerTokenError.getCode() != null ? bearerTokenError.getCode() + String errorCode = (bearerTokenError.getCode() != null) ? bearerTokenError.getCode() : OAuth2ErrorCodes.SERVER_ERROR; String errorDescription = bearerTokenError.getDescription(); - String errorUri = bearerTokenError.getURI() != null ? bearerTokenError.getURI().toString() : null; + String errorUri = (bearerTokenError.getURI() != null) ? bearerTokenError.getURI().toString() : null; return new OAuth2Error(errorCode, errorDescription, errorUri); } diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcReactiveOAuth2UserService.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcReactiveOAuth2UserService.java index eb8f0a0fae..fced8acd0a 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcReactiveOAuth2UserService.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcReactiveOAuth2UserService.java @@ -138,7 +138,7 @@ public class OidcReactiveOAuth2UserService implements ReactiveOAuth2UserService< private Map convertClaims(Map claims, ClientRegistration clientRegistration) { Converter, Map> claimTypeConverter = this.claimTypeConverterFactory .apply(clientRegistration); - return claimTypeConverter != null ? claimTypeConverter.convert(claims) + return (claimTypeConverter != null) ? claimTypeConverter.convert(claims) : DEFAULT_CLAIM_TYPE_CONVERTER.convert(claims); } diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/registration/ClientRegistration.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/registration/ClientRegistration.java index 584e44a896..353049076a 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/registration/ClientRegistration.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/registration/ClientRegistration.java @@ -368,7 +368,7 @@ public final class ClientRegistration implements Serializable { this.clientAuthenticationMethod = clientRegistration.clientAuthenticationMethod; this.authorizationGrantType = clientRegistration.authorizationGrantType; this.redirectUri = clientRegistration.redirectUri; - this.scopes = clientRegistration.scopes == null ? null : new HashSet<>(clientRegistration.scopes); + this.scopes = (clientRegistration.scopes != null) ? new HashSet<>(clientRegistration.scopes) : null; this.authorizationUri = clientRegistration.providerDetails.authorizationUri; this.tokenUri = clientRegistration.providerDetails.tokenUri; this.userInfoUri = clientRegistration.providerDetails.userInfoEndpoint.uri; diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizationRequestResolver.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizationRequestResolver.java index 167455f05c..a333239355 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizationRequestResolver.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizationRequestResolver.java @@ -224,22 +224,22 @@ public final class DefaultOAuth2AuthorizationRequestResolver implements OAuth2Au UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(UrlUtils.buildFullRequestUrl(request)) .replacePath(request.getContextPath()).replaceQuery(null).fragment(null).build(); String scheme = uriComponents.getScheme(); - uriVariables.put("baseScheme", scheme == null ? "" : scheme); + uriVariables.put("baseScheme", (scheme != null) ? scheme : ""); String host = uriComponents.getHost(); - uriVariables.put("baseHost", host == null ? "" : host); + uriVariables.put("baseHost", (host != null) ? host : ""); // following logic is based on HierarchicalUriComponents#toUriString() int port = uriComponents.getPort(); - uriVariables.put("basePort", port == -1 ? "" : ":" + port); + uriVariables.put("basePort", (port == -1) ? "" : ":" + port); String path = uriComponents.getPath(); if (StringUtils.hasLength(path)) { if (path.charAt(0) != PATH_DELIMITER) { path = PATH_DELIMITER + path; } } - uriVariables.put("basePath", path == null ? "" : path); + uriVariables.put("basePath", (path != null) ? path : ""); uriVariables.put("baseUrl", uriComponents.toUriString()); - uriVariables.put("action", action == null ? "" : action); + uriVariables.put("action", (action != null) ? action : ""); return UriComponentsBuilder.fromUriString(clientRegistration.getRedirectUri()).buildAndExpand(uriVariables) .toUriString(); diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/DefaultReactiveOAuth2AuthorizedClientManager.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/DefaultReactiveOAuth2AuthorizedClientManager.java index c1970512ff..7ee459ad6a 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/DefaultReactiveOAuth2AuthorizedClientManager.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/DefaultReactiveOAuth2AuthorizedClientManager.java @@ -151,7 +151,7 @@ public final class DefaultReactiveOAuth2AuthorizedClientManager implements React (authorizationContext) -> authorize(authorizationContext, principal, serverWebExchange)) // Default to the existing authorizedClient if the // client was not re-authorized - .defaultIfEmpty(authorizeRequest.getAuthorizedClient() != null + .defaultIfEmpty((authorizeRequest.getAuthorizedClient() != null) ? authorizeRequest.getAuthorizedClient() : authorizedClient)) .switchIfEmpty(Mono.defer(() -> // Authorize diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/HttpSessionOAuth2AuthorizationRequestRepository.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/HttpSessionOAuth2AuthorizationRequestRepository.java index 3a19443be0..df26460b4c 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/HttpSessionOAuth2AuthorizationRequestRepository.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/HttpSessionOAuth2AuthorizationRequestRepository.java @@ -115,8 +115,8 @@ public final class HttpSessionOAuth2AuthorizationRequestRepository */ private Map getAuthorizationRequests(HttpServletRequest request) { HttpSession session = request.getSession(false); - Map authorizationRequests = session == null ? null - : (Map) session.getAttribute(this.sessionAttributeName); + Map authorizationRequests = (session != null) + ? (Map) session.getAttribute(this.sessionAttributeName) : null; if (authorizationRequests == null) { return new HashMap<>(); } diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/HttpSessionOAuth2AuthorizedClientRepository.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/HttpSessionOAuth2AuthorizedClientRepository.java index 67d22bff29..e0b65a6398 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/HttpSessionOAuth2AuthorizedClientRepository.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/HttpSessionOAuth2AuthorizedClientRepository.java @@ -84,8 +84,8 @@ public final class HttpSessionOAuth2AuthorizedClientRepository implements OAuth2 @SuppressWarnings("unchecked") private Map getAuthorizedClients(HttpServletRequest request) { HttpSession session = request.getSession(false); - Map authorizedClients = session == null ? null - : (Map) session.getAttribute(this.sessionAttributeName); + Map authorizedClients = (session != null) + ? (Map) session.getAttribute(this.sessionAttributeName) : null; if (authorizedClients == null) { authorizedClients = new HashMap<>(); } diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationCodeGrantFilter.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationCodeGrantFilter.java index df524e71a8..f86c761178 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationCodeGrantFilter.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationCodeGrantFilter.java @@ -244,7 +244,7 @@ public class OAuth2AuthorizationCodeGrantFilter extends OncePerRequestFilter { } Authentication currentAuthentication = SecurityContextHolder.getContext().getAuthentication(); - String principalName = currentAuthentication != null ? currentAuthentication.getName() : "anonymousUser"; + String principalName = (currentAuthentication != null) ? currentAuthentication.getName() : "anonymousUser"; OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient( authenticationResult.getClientRegistration(), principalName, authenticationResult.getAccessToken(), diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunction.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunction.java index b4a8fd8c6e..6e9b5f09f4 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunction.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunction.java @@ -572,7 +572,7 @@ public final class ServerOAuth2AuthorizedClientExchangeFilterFunction implements .build()).flatMap((authorizationContext) -> authorize(authorizationContext, principal)) // Default to the existing authorizedClient if the client // was not re-authorized - .defaultIfEmpty(authorizeRequest.getAuthorizedClient() != null + .defaultIfEmpty((authorizeRequest.getAuthorizedClient() != null) ? authorizeRequest.getAuthorizedClient() : authorizedClient)) .switchIfEmpty(Mono.defer(() -> // Authorize diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/server/DefaultServerOAuth2AuthorizationRequestResolver.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/server/DefaultServerOAuth2AuthorizationRequestResolver.java index b8d725a59e..af0df46d5c 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/server/DefaultServerOAuth2AuthorizationRequestResolver.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/server/DefaultServerOAuth2AuthorizationRequestResolver.java @@ -217,19 +217,19 @@ public class DefaultServerOAuth2AuthorizationRequestResolver implements ServerOA UriComponents uriComponents = UriComponentsBuilder.fromUri(request.getURI()) .replacePath(request.getPath().contextPath().value()).replaceQuery(null).fragment(null).build(); String scheme = uriComponents.getScheme(); - uriVariables.put("baseScheme", scheme == null ? "" : scheme); + uriVariables.put("baseScheme", (scheme != null) ? scheme : ""); String host = uriComponents.getHost(); - uriVariables.put("baseHost", host == null ? "" : host); + uriVariables.put("baseHost", (host != null) ? host : ""); // following logic is based on HierarchicalUriComponents#toUriString() int port = uriComponents.getPort(); - uriVariables.put("basePort", port == -1 ? "" : ":" + port); + uriVariables.put("basePort", (port == -1) ? "" : ":" + port); String path = uriComponents.getPath(); if (StringUtils.hasLength(path)) { if (path.charAt(0) != PATH_DELIMITER) { path = PATH_DELIMITER + path; } } - uriVariables.put("basePath", path == null ? "" : path); + uriVariables.put("basePath", (path != null) ? path : ""); uriVariables.put("baseUrl", uriComponents.toUriString()); String action = ""; diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/server/WebSessionServerOAuth2AuthorizedClientRepository.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/server/WebSessionServerOAuth2AuthorizedClientRepository.java index ab410f866f..040419a076 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/server/WebSessionServerOAuth2AuthorizedClientRepository.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/server/WebSessionServerOAuth2AuthorizedClientRepository.java @@ -85,8 +85,8 @@ public final class WebSessionServerOAuth2AuthorizedClientRepository implements S @SuppressWarnings("unchecked") private Map getAuthorizedClients(WebSession session) { - Map authorizedClients = session == null ? null - : (Map) session.getAttribute(this.sessionAttributeName); + Map authorizedClients = (session != null) + ? (Map) session.getAttribute(this.sessionAttributeName) : null; if (authorizedClients == null) { authorizedClients = new HashMap<>(); } diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthenticationExceptionMixinTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthenticationExceptionMixinTests.java index 539c46feed..6bfcc4f2a9 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthenticationExceptionMixinTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthenticationExceptionMixinTests.java @@ -129,7 +129,7 @@ public class OAuth2AuthenticationExceptionMixinTests { } private String jsonStringOrNull(String input) { - return input != null ? "\"" + input + "\"" : "null"; + return (input != null) ? "\"" + input + "\"" : "null"; } } diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthenticationTokenMixinTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthenticationTokenMixinTests.java index 42c4c66a25..6e7583df26 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthenticationTokenMixinTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthenticationTokenMixinTests.java @@ -169,7 +169,7 @@ public class OAuth2AuthenticationTokenMixinTests { } private static String asJson(OAuth2AuthenticationToken authentication) { - String principalJson = authentication.getPrincipal() instanceof DefaultOidcUser + String principalJson = (authentication.getPrincipal() instanceof DefaultOidcUser) ? asJson((DefaultOidcUser) authentication.getPrincipal()) : asJson((DefaultOAuth2User) authentication.getPrincipal()); // @formatter:off @@ -224,8 +224,8 @@ public class OAuth2AuthenticationTokenMixinTests { simpleAuthorities.add((SimpleGrantedAuthority) authority); } } - String authoritiesJson = oidcUserAuthority != null ? asJson(oidcUserAuthority) - : oauth2UserAuthority != null ? asJson(oauth2UserAuthority) : ""; + String authoritiesJson = (oidcUserAuthority != null) ? asJson(oidcUserAuthority) + : (oauth2UserAuthority != null) ? asJson(oauth2UserAuthority) : ""; if (!simpleAuthorities.isEmpty()) { if (!StringUtils.isEmpty(authoritiesJson)) { authoritiesJson += ","; diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthorizationRequestMixinTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthorizationRequestMixinTests.java index e7e3bd7919..326a56c3fa 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthorizationRequestMixinTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthorizationRequestMixinTests.java @@ -165,7 +165,7 @@ public class OAuth2AuthorizationRequestMixinTests { " \"java.util.Collections$UnmodifiableSet\",\n" + " [" + scopes + "]\n" + " ],\n" + - " \"state\": " + (authorizationRequest.getState() != null ? "\"" + authorizationRequest.getState() + "\"" : "null") + ",\n" + + " \"state\": " + ((authorizationRequest.getState() != null) ? "\"" + authorizationRequest.getState() + "\"" : "null") + ",\n" + " \"additionalParameters\": {\n" + " " + additionalParameters + "\n" + " },\n" + diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthorizedClientMixinTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthorizedClientMixinTests.java index 1fe9558934..b829abc651 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthorizedClientMixinTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthorizedClientMixinTests.java @@ -241,14 +241,14 @@ public class OAuth2AuthorizedClientMixinTests { " \"tokenUri\": \"" + providerDetails.getTokenUri() + "\",\n" + " \"userInfoEndpoint\": {\n" + " \"@class\": \"org.springframework.security.oauth2.client.registration.ClientRegistration$ProviderDetails$UserInfoEndpoint\",\n" + - " \"uri\": " + (userInfoEndpoint.getUri() != null ? "\"" + userInfoEndpoint.getUri() + "\"" : null) + ",\n" + + " \"uri\": " + ((userInfoEndpoint.getUri() != null) ? "\"" + userInfoEndpoint.getUri() + "\"" : null) + ",\n" + " \"authenticationMethod\": {\n" + " \"value\": \"" + userInfoEndpoint.getAuthenticationMethod().getValue() + "\"\n" + " },\n" + - " \"userNameAttributeName\": " + (userInfoEndpoint.getUserNameAttributeName() != null ? "\"" + userInfoEndpoint.getUserNameAttributeName() + "\"" : null) + "\n" + + " \"userNameAttributeName\": " + ((userInfoEndpoint.getUserNameAttributeName() != null) ? "\"" + userInfoEndpoint.getUserNameAttributeName() + "\"" : null) + "\n" + " },\n" + - " \"jwkSetUri\": " + (providerDetails.getJwkSetUri() != null ? "\"" + providerDetails.getJwkSetUri() + "\"" : null) + ",\n" + - " \"issuerUri\": " + (providerDetails.getIssuerUri() != null ? "\"" + providerDetails.getIssuerUri() + "\"" : null) + ",\n" + + " \"jwkSetUri\": " + ((providerDetails.getJwkSetUri() != null) ? "\"" + providerDetails.getJwkSetUri() + "\"" : null) + ",\n" + + " \"issuerUri\": " + ((providerDetails.getIssuerUri() != null) ? "\"" + providerDetails.getIssuerUri() + "\"" : null) + ",\n" + " \"configurationMetadata\": {\n" + " " + configurationMetadata + "\n" + " }\n" + diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/ClientRegistrationsTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/ClientRegistrationsTests.java index ee51e2cf1d..61dc4e954a 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/ClientRegistrationsTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/ClientRegistrationsTests.java @@ -393,7 +393,7 @@ public class ClientRegistrationsTests { this.issuer = createIssuerFromServer(path); this.response.put("issuer", this.issuer); this.issuer = this.server.url(path).toString(); - final String responseBody = body != null ? body : this.mapper.writeValueAsString(this.response); + final String responseBody = (body != null) ? body : this.mapper.writeValueAsString(this.response); final Dispatcher dispatcher = new Dispatcher() { @Override @@ -429,7 +429,7 @@ public class ClientRegistrationsTests { this.issuer = createIssuerFromServer(path); this.response.put("issuer", this.issuer); - String responseBody = body != null ? body : this.mapper.writeValueAsString(this.response); + String responseBody = (body != null) ? body : this.mapper.writeValueAsString(this.response); final Dispatcher dispatcher = new Dispatcher() { @Override diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/result/method/annotation/OAuth2AuthorizedClientArgumentResolverTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/result/method/annotation/OAuth2AuthorizedClientArgumentResolverTests.java index 577aca3bb7..f92100222f 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/result/method/annotation/OAuth2AuthorizedClientArgumentResolverTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/result/method/annotation/OAuth2AuthorizedClientArgumentResolverTests.java @@ -175,8 +175,8 @@ public class OAuth2AuthorizedClientArgumentResolverTests { private Object resolveArgument(MethodParameter methodParameter) { return this.argumentResolver.resolveArgument(methodParameter, null, null) - .subscriberContext(this.authentication == null ? Context.empty() - : ReactiveSecurityContextHolder.withAuthentication(this.authentication)) + .subscriberContext((this.authentication != null) + ? ReactiveSecurityContextHolder.withAuthentication(this.authentication) : Context.empty()) .subscriberContext(serverWebExchange()).block(); } diff --git a/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/AbstractOAuth2Token.java b/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/AbstractOAuth2Token.java index 2b00d4a00b..1d4e1daf0d 100644 --- a/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/AbstractOAuth2Token.java +++ b/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/AbstractOAuth2Token.java @@ -98,23 +98,24 @@ public abstract class AbstractOAuth2Token implements Serializable { return false; } - AbstractOAuth2Token that = (AbstractOAuth2Token) obj; + AbstractOAuth2Token other = (AbstractOAuth2Token) obj; - if (!this.getTokenValue().equals(that.getTokenValue())) { + if (!this.getTokenValue().equals(other.getTokenValue())) { return false; } - if (this.getIssuedAt() != null ? !this.getIssuedAt().equals(that.getIssuedAt()) : that.getIssuedAt() != null) { + if ((this.getIssuedAt() != null) ? !this.getIssuedAt().equals(other.getIssuedAt()) + : other.getIssuedAt() != null) { return false; } - return this.getExpiresAt() != null ? this.getExpiresAt().equals(that.getExpiresAt()) - : that.getExpiresAt() == null; + return (this.getExpiresAt() != null) ? this.getExpiresAt().equals(other.getExpiresAt()) + : other.getExpiresAt() == null; } @Override public int hashCode() { int result = this.getTokenValue().hashCode(); - result = 31 * result + (this.getIssuedAt() != null ? this.getIssuedAt().hashCode() : 0); - result = 31 * result + (this.getExpiresAt() != null ? this.getExpiresAt().hashCode() : 0); + result = 31 * result + ((this.getIssuedAt() != null) ? this.getIssuedAt().hashCode() : 0); + result = 31 * result + ((this.getExpiresAt() != null) ? this.getExpiresAt().hashCode() : 0); return result; } diff --git a/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/DefaultOAuth2AuthenticatedPrincipal.java b/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/DefaultOAuth2AuthenticatedPrincipal.java index 7107109323..e537ad953d 100644 --- a/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/DefaultOAuth2AuthenticatedPrincipal.java +++ b/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/DefaultOAuth2AuthenticatedPrincipal.java @@ -64,9 +64,9 @@ public final class DefaultOAuth2AuthenticatedPrincipal implements OAuth2Authenti Assert.notEmpty(attributes, "attributes cannot be empty"); this.attributes = Collections.unmodifiableMap(attributes); - this.authorities = authorities == null ? AuthorityUtils.NO_AUTHORITIES - : Collections.unmodifiableCollection(authorities); - this.name = name == null ? (String) this.attributes.get("sub") : name; + this.authorities = (authorities != null) ? Collections.unmodifiableCollection(authorities) + : AuthorityUtils.NO_AUTHORITIES; + this.name = (name != null) ? name : (String) this.attributes.get("sub"); } /** diff --git a/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/OAuth2AccessToken.java b/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/OAuth2AccessToken.java index 0c27e45de5..8ec26b6023 100644 --- a/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/OAuth2AccessToken.java +++ b/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/OAuth2AccessToken.java @@ -71,7 +71,7 @@ public class OAuth2AccessToken extends AbstractOAuth2Token { super(tokenValue, issuedAt, expiresAt); Assert.notNull(tokenType, "tokenType cannot be null"); this.tokenType = tokenType; - this.scopes = Collections.unmodifiableSet(scopes != null ? scopes : Collections.emptySet()); + this.scopes = Collections.unmodifiableSet((scopes != null) ? scopes : Collections.emptySet()); } /** diff --git a/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/OAuth2Error.java b/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/OAuth2Error.java index 8a7d04c2b6..f1816b723d 100644 --- a/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/OAuth2Error.java +++ b/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/OAuth2Error.java @@ -93,7 +93,7 @@ public class OAuth2Error implements Serializable { @Override public String toString() { - return "[" + this.getErrorCode() + "] " + (this.getDescription() != null ? this.getDescription() : ""); + return "[" + this.getErrorCode() + "] " + ((this.getDescription() != null) ? this.getDescription() : ""); } } diff --git a/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/converter/ObjectToStringConverter.java b/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/converter/ObjectToStringConverter.java index f816dc9ad4..a82e0341b3 100644 --- a/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/converter/ObjectToStringConverter.java +++ b/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/converter/ObjectToStringConverter.java @@ -35,7 +35,7 @@ final class ObjectToStringConverter implements GenericConverter { @Override public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { - return source == null ? null : source.toString(); + return (source != null) ? source.toString() : null; } } diff --git a/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/endpoint/OAuth2AccessTokenResponse.java b/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/endpoint/OAuth2AccessTokenResponse.java index 9c2a65ace8..6d5197350a 100644 --- a/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/endpoint/OAuth2AccessTokenResponse.java +++ b/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/endpoint/OAuth2AccessTokenResponse.java @@ -120,7 +120,8 @@ public final class OAuth2AccessTokenResponse { this.issuedAt = accessToken.getIssuedAt(); this.expiresAt = accessToken.getExpiresAt(); this.scopes = accessToken.getScopes(); - this.refreshToken = response.getRefreshToken() == null ? null : response.getRefreshToken().getTokenValue(); + this.refreshToken = (response.getRefreshToken() != null) ? response.getRefreshToken().getTokenValue() + : null; this.additionalParameters = response.getAdditionalParameters(); } @@ -217,7 +218,7 @@ public final class OAuth2AccessTokenResponse { private Instant getExpiresAt() { if (this.expiresAt == null) { Instant issuedAt = getIssuedAt(); - this.expiresAt = this.expiresIn > 0 ? issuedAt.plusSeconds(this.expiresIn) : issuedAt.plusSeconds(1); + this.expiresAt = (this.expiresIn > 0) ? issuedAt.plusSeconds(this.expiresIn) : issuedAt.plusSeconds(1); } return this.expiresAt; } diff --git a/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/oidc/DefaultAddressStandardClaim.java b/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/oidc/DefaultAddressStandardClaim.java index 73fad90051..e5ffcdc544 100644 --- a/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/oidc/DefaultAddressStandardClaim.java +++ b/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/oidc/DefaultAddressStandardClaim.java @@ -81,37 +81,38 @@ public final class DefaultAddressStandardClaim implements AddressStandardClaim { return false; } - AddressStandardClaim that = (AddressStandardClaim) obj; + AddressStandardClaim other = (AddressStandardClaim) obj; - if (this.getFormatted() != null ? !this.getFormatted().equals(that.getFormatted()) - : that.getFormatted() != null) { + if ((this.getFormatted() != null) ? !this.getFormatted().equals(other.getFormatted()) + : other.getFormatted() != null) { return false; } - if (this.getStreetAddress() != null ? !this.getStreetAddress().equals(that.getStreetAddress()) - : that.getStreetAddress() != null) { + if ((this.getStreetAddress() != null) ? !this.getStreetAddress().equals(other.getStreetAddress()) + : other.getStreetAddress() != null) { return false; } - if (this.getLocality() != null ? !this.getLocality().equals(that.getLocality()) : that.getLocality() != null) { + if ((this.getLocality() != null) ? !this.getLocality().equals(other.getLocality()) + : other.getLocality() != null) { return false; } - if (this.getRegion() != null ? !this.getRegion().equals(that.getRegion()) : that.getRegion() != null) { + if ((this.getRegion() != null) ? !this.getRegion().equals(other.getRegion()) : other.getRegion() != null) { return false; } - if (this.getPostalCode() != null ? !this.getPostalCode().equals(that.getPostalCode()) - : that.getPostalCode() != null) { + if ((this.getPostalCode() != null) ? !this.getPostalCode().equals(other.getPostalCode()) + : other.getPostalCode() != null) { return false; } - return this.getCountry() != null ? this.getCountry().equals(that.getCountry()) : that.getCountry() == null; + return (this.getCountry() != null) ? this.getCountry().equals(other.getCountry()) : other.getCountry() == null; } @Override public int hashCode() { - int result = this.getFormatted() != null ? this.getFormatted().hashCode() : 0; - result = 31 * result + (this.getStreetAddress() != null ? this.getStreetAddress().hashCode() : 0); - result = 31 * result + (this.getLocality() != null ? this.getLocality().hashCode() : 0); - result = 31 * result + (this.getRegion() != null ? this.getRegion().hashCode() : 0); - result = 31 * result + (this.getPostalCode() != null ? this.getPostalCode().hashCode() : 0); - result = 31 * result + (this.getCountry() != null ? this.getCountry().hashCode() : 0); + int result = (this.getFormatted() != null) ? this.getFormatted().hashCode() : 0; + result = 31 * result + ((this.getStreetAddress() != null) ? this.getStreetAddress().hashCode() : 0); + result = 31 * result + ((this.getLocality() != null) ? this.getLocality().hashCode() : 0); + result = 31 * result + ((this.getRegion() != null) ? this.getRegion().hashCode() : 0); + result = 31 * result + ((this.getPostalCode() != null) ? this.getPostalCode().hashCode() : 0); + result = 31 * result + ((this.getCountry() != null) ? this.getCountry().hashCode() : 0); return result; } diff --git a/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/oidc/user/OidcUserAuthority.java b/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/oidc/user/OidcUserAuthority.java index fe0220028b..fb57773904 100644 --- a/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/oidc/user/OidcUserAuthority.java +++ b/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/oidc/user/OidcUserAuthority.java @@ -104,14 +104,15 @@ public class OidcUserAuthority extends OAuth2UserAuthority { if (!this.getIdToken().equals(that.getIdToken())) { return false; } - return this.getUserInfo() != null ? this.getUserInfo().equals(that.getUserInfo()) : that.getUserInfo() == null; + return (this.getUserInfo() != null) ? this.getUserInfo().equals(that.getUserInfo()) + : that.getUserInfo() == null; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + this.getIdToken().hashCode(); - result = 31 * result + (this.getUserInfo() != null ? this.getUserInfo().hashCode() : 0); + result = 31 * result + ((this.getUserInfo() != null) ? this.getUserInfo().hashCode() : 0); return result; } diff --git a/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/web/reactive/function/OAuth2AccessTokenResponseBodyExtractor.java b/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/web/reactive/function/OAuth2AccessTokenResponseBodyExtractor.java index 3eaf03d205..1cb8553fc7 100644 --- a/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/web/reactive/function/OAuth2AccessTokenResponseBodyExtractor.java +++ b/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/web/reactive/function/OAuth2AccessTokenResponseBodyExtractor.java @@ -99,9 +99,9 @@ class OAuth2AccessTokenResponseBodyExtractor } else { oauth2Error = new OAuth2Error( - errorObject.getCode() != null ? errorObject.getCode() : OAuth2ErrorCodes.SERVER_ERROR, + (errorObject.getCode() != null) ? errorObject.getCode() : OAuth2ErrorCodes.SERVER_ERROR, errorObject.getDescription(), - errorObject.getURI() != null ? errorObject.getURI().toString() : null); + (errorObject.getURI() != null) ? errorObject.getURI().toString() : null); } return Mono.error(new OAuth2AuthorizationException(oauth2Error)); } @@ -114,8 +114,8 @@ class OAuth2AccessTokenResponseBodyExtractor } long expiresIn = accessToken.getLifetime(); - Set scopes = accessToken.getScope() == null ? Collections.emptySet() - : new LinkedHashSet<>(accessToken.getScope().toStringList()); + Set scopes = (accessToken.getScope() != null) + ? new LinkedHashSet<>(accessToken.getScope().toStringList()) : Collections.emptySet(); String refreshToken = null; if (accessTokenResponse.getTokens().getRefreshToken() != null) { diff --git a/openid/src/main/java/org/springframework/security/openid/OpenID4JavaConsumer.java b/openid/src/main/java/org/springframework/security/openid/OpenID4JavaConsumer.java index 009fd4eec5..aa8dac2356 100644 --- a/openid/src/main/java/org/springframework/security/openid/OpenID4JavaConsumer.java +++ b/openid/src/main/java/org/springframework/security/openid/OpenID4JavaConsumer.java @@ -164,7 +164,7 @@ public class OpenID4JavaConsumer implements OpenIDConsumer { if (verified == null) { Identifier id = discovered.getClaimedIdentifier(); return new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.FAILURE, - id == null ? "Unknown" : id.getIdentifier(), + (id != null) ? id.getIdentifier() : "Unknown", "Verification status message: [" + verification.getStatusMsg() + "]", Collections.emptyList()); } diff --git a/remoting/src/main/java/org/springframework/security/remoting/rmi/ContextPropagatingRemoteInvocation.java b/remoting/src/main/java/org/springframework/security/remoting/rmi/ContextPropagatingRemoteInvocation.java index a5f37c60c8..0f6bffb0c9 100644 --- a/remoting/src/main/java/org/springframework/security/remoting/rmi/ContextPropagatingRemoteInvocation.java +++ b/remoting/src/main/java/org/springframework/security/remoting/rmi/ContextPropagatingRemoteInvocation.java @@ -65,7 +65,7 @@ public class ContextPropagatingRemoteInvocation extends RemoteInvocation { if (currentUser != null) { this.principal = currentUser.getName(); Object userCredentials = currentUser.getCredentials(); - this.credentials = userCredentials == null ? null : userCredentials.toString(); + this.credentials = (userCredentials != null) ? userCredentials.toString() : null; } else { this.credentials = null; diff --git a/rsocket/src/main/java/org/springframework/security/rsocket/util/matcher/PayloadExchangeMatcher.java b/rsocket/src/main/java/org/springframework/security/rsocket/util/matcher/PayloadExchangeMatcher.java index 3dc38c0e68..582bf8a2e4 100644 --- a/rsocket/src/main/java/org/springframework/security/rsocket/util/matcher/PayloadExchangeMatcher.java +++ b/rsocket/src/main/java/org/springframework/security/rsocket/util/matcher/PayloadExchangeMatcher.java @@ -81,7 +81,9 @@ public interface PayloadExchangeMatcher { * @return */ public static Mono match(Map variables) { - return Mono.just(new MatchResult(true, variables == null ? null : new HashMap(variables))); + MatchResult result = new MatchResult(true, + (variables != null) ? new HashMap(variables) : null); + return Mono.just(result); } /** diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/core/Saml2Error.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/core/Saml2Error.java index 92338f5551..6709092ced 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/core/Saml2Error.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/core/Saml2Error.java @@ -69,7 +69,7 @@ public class Saml2Error implements Serializable { @Override public String toString() { - return "[" + this.getErrorCode() + "] " + (this.getDescription() != null ? this.getDescription() : ""); + return "[" + this.getErrorCode() + "] " + ((this.getDescription() != null) ? this.getDescription() : ""); } } diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationProvider.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationProvider.java index 0a5b4cd4ba..3c1f122d1a 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationProvider.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationProvider.java @@ -536,11 +536,11 @@ public final class OpenSamlAuthenticationProvider implements AuthenticationProvi } if (xmlObject instanceof XSBoolean) { XSBooleanValue xsBooleanValue = ((XSBoolean) xmlObject).getValue(); - return xsBooleanValue != null ? xsBooleanValue.getValue() : null; + return (xsBooleanValue != null) ? xsBooleanValue.getValue() : null; } if (xmlObject instanceof XSDateTime) { DateTime dateTime = ((XSDateTime) xmlObject).getValue(); - return dateTime != null ? Instant.ofEpochMilli(dateTime.getMillis()) : null; + return (dateTime != null) ? Instant.ofEpochMilli(dateTime.getMillis()) : null; } return null; } diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/Saml2Error.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/Saml2Error.java index 23f3d24d1b..4c2b35afae 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/Saml2Error.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/Saml2Error.java @@ -66,7 +66,7 @@ public class Saml2Error implements Serializable { @Override public String toString() { - return "[" + this.getErrorCode() + "] " + (this.getDescription() != null ? this.getDescription() : ""); + return "[" + this.getErrorCode() + "] " + ((this.getDescription() != null) ? this.getDescription() : ""); } } diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2ServletUtils.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2ServletUtils.java index 046d75f33a..ce062757dc 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2ServletUtils.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2ServletUtils.java @@ -48,19 +48,19 @@ final class Saml2ServletUtils { UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(baseUrl).replaceQuery(null).fragment(null) .build(); String scheme = uriComponents.getScheme(); - uriVariables.put("baseScheme", scheme == null ? "" : scheme); + uriVariables.put("baseScheme", (scheme != null) ? scheme : ""); String host = uriComponents.getHost(); - uriVariables.put("baseHost", host == null ? "" : host); + uriVariables.put("baseHost", (host != null) ? host : ""); // following logic is based on HierarchicalUriComponents#toUriString() int port = uriComponents.getPort(); - uriVariables.put("basePort", port == -1 ? "" : ":" + port); + uriVariables.put("basePort", (port != -1) ? ":" + port : ""); String path = uriComponents.getPath(); if (StringUtils.hasLength(path)) { if (path.charAt(0) != PATH_DELIMITER) { path = PATH_DELIMITER + path; } } - uriVariables.put("basePath", path == null ? "" : path); + uriVariables.put("basePath", (path != null) ? path : ""); uriVariables.put("baseUrl", uriComponents.toUriString()); uriVariables.put("entityId", StringUtils.hasText(entityId) ? entityId : ""); uriVariables.put("registrationId", StringUtils.hasText(registrationId) ? registrationId : ""); diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/DefaultRelyingPartyRegistrationResolver.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/DefaultRelyingPartyRegistrationResolver.java index c81f6b2b6d..45c6c27d95 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/DefaultRelyingPartyRegistrationResolver.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/DefaultRelyingPartyRegistrationResolver.java @@ -90,17 +90,17 @@ public final class DefaultRelyingPartyRegistrationResolver UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(baseUrl).replaceQuery(null).fragment(null) .build(); String scheme = uriComponents.getScheme(); - uriVariables.put("baseScheme", scheme == null ? "" : scheme); + uriVariables.put("baseScheme", (scheme != null) ? scheme : ""); String host = uriComponents.getHost(); - uriVariables.put("baseHost", host == null ? "" : host); + uriVariables.put("baseHost", (host != null) ? host : ""); // following logic is based on HierarchicalUriComponents#toUriString() int port = uriComponents.getPort(); - uriVariables.put("basePort", port == -1 ? "" : ":" + port); + uriVariables.put("basePort", (port == -1) ? "" : ":" + port); String path = uriComponents.getPath(); if (StringUtils.hasLength(path) && path.charAt(0) != PATH_DELIMITER) { path = PATH_DELIMITER + path; } - uriVariables.put("basePath", path == null ? "" : path); + uriVariables.put("basePath", (path != null) ? path : ""); uriVariables.put("baseUrl", uriComponents.toUriString()); uriVariables.put("entityId", StringUtils.hasText(entityId) ? entityId : ""); uriVariables.put("registrationId", StringUtils.hasText(registrationId) ? registrationId : ""); diff --git a/taglibs/src/main/java/org/springframework/security/taglibs/TagLibConfig.java b/taglibs/src/main/java/org/springframework/security/taglibs/TagLibConfig.java index c316bc8982..dfbe370fde 100644 --- a/taglibs/src/main/java/org/springframework/security/taglibs/TagLibConfig.java +++ b/taglibs/src/main/java/org/springframework/security/taglibs/TagLibConfig.java @@ -41,8 +41,8 @@ public final class TagLibConfig { String prefix = System.getProperty("spring.security.securedUIPrefix"); String suffix = System.getProperty("spring.security.securedUISuffix"); - SECURED_UI_PREFIX = prefix == null ? "" : prefix; - SECURED_UI_SUFFIX = suffix == null ? "" : suffix; + SECURED_UI_PREFIX = (prefix != null) ? prefix : ""; + SECURED_UI_SUFFIX = (suffix != null) ? suffix : ""; DISABLE_UI_SECURITY = "true".equals(db); diff --git a/test/src/main/java/org/springframework/security/test/context/support/WithSecurityContextTestExecutionListener.java b/test/src/main/java/org/springframework/security/test/context/support/WithSecurityContextTestExecutionListener.java index 0a5bb40de4..862f79962b 100644 --- a/test/src/main/java/org/springframework/security/test/context/support/WithSecurityContextTestExecutionListener.java +++ b/test/src/main/java/org/springframework/security/test/context/support/WithSecurityContextTestExecutionListener.java @@ -100,8 +100,8 @@ public class WithSecurityContextTestExecutionListener extends AbstractTestExecut private TestSecurityContext createTestSecurityContext(Class annotated, TestContext context) { MetaAnnotationUtils.AnnotationDescriptor withSecurityContextDescriptor = MetaAnnotationUtils .findAnnotationDescriptor(annotated, WithSecurityContext.class); - WithSecurityContext withSecurityContext = withSecurityContextDescriptor == null ? null - : withSecurityContextDescriptor.getAnnotation(); + WithSecurityContext withSecurityContext = (withSecurityContextDescriptor != null) + ? withSecurityContextDescriptor.getAnnotation() : null; return createTestSecurityContext(annotated, withSecurityContext, context); } diff --git a/test/src/main/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessors.java b/test/src/main/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessors.java index 846bc223c0..975c684174 100644 --- a/test/src/main/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessors.java +++ b/test/src/main/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessors.java @@ -770,7 +770,7 @@ public final class SecurityMockMvcRequestPostProcessors { // remember the SecurityContextRepository is used in many different // locations SecurityContext delegateResult = this.delegate.loadContext(requestResponseHolder); - return result == null ? delegateResult : result; + return (result != null) ? result : delegateResult; } @Override diff --git a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsDigestTests.java b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsDigestTests.java index 51a9687d6e..9f9653ff25 100644 --- a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsDigestTests.java +++ b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsDigestTests.java @@ -120,8 +120,8 @@ public class SecurityMockMvcRequestPostProcessorsDigestTests { @Override public void doFilter(ServletRequest request, ServletResponse response) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - SecurityMockMvcRequestPostProcessorsDigestTests.this.username = authentication == null ? null - : authentication.getName(); + SecurityMockMvcRequestPostProcessorsDigestTests.this.username = (authentication != null) + ? authentication.getName() : null; } }); return this.username; diff --git a/web/src/main/java/org/springframework/security/web/FilterChainProxy.java b/web/src/main/java/org/springframework/security/web/FilterChainProxy.java index d6ba03070d..47bb405a83 100644 --- a/web/src/main/java/org/springframework/security/web/FilterChainProxy.java +++ b/web/src/main/java/org/springframework/security/web/FilterChainProxy.java @@ -202,7 +202,7 @@ public class FilterChainProxy extends GenericFilterBean { if (filters == null || filters.size() == 0) { if (logger.isDebugEnabled()) { logger.debug(UrlUtils.buildRequestUrl(fwRequest) - + (filters == null ? " has no matching filters" : " has an empty filter list")); + + ((filters != null) ? " has an empty filter list" : " has no matching filters")); } fwRequest.reset(); diff --git a/web/src/main/java/org/springframework/security/web/FilterInvocation.java b/web/src/main/java/org/springframework/security/web/FilterInvocation.java index 5a0f90ab87..879b1ce94b 100644 --- a/web/src/main/java/org/springframework/security/web/FilterInvocation.java +++ b/web/src/main/java/org/springframework/security/web/FilterInvocation.java @@ -89,7 +89,7 @@ public class FilterInvocation { } request.setContextPath(contextPath); request.setServletPath(servletPath); - request.setRequestURI(contextPath + servletPath + (pathInfo == null ? "" : pathInfo)); + request.setRequestURI(contextPath + servletPath + ((pathInfo != null) ? pathInfo : "")); request.setPathInfo(pathInfo); request.setQueryString(query); request.setMethod(method); @@ -268,7 +268,7 @@ public class FilterInvocation { @Override public String getParameter(String name) { String[] arr = this.parameters.get(name); - return (arr != null && arr.length > 0 ? arr[0] : null); + return (arr != null && arr.length > 0) ? arr[0] : null; } @Override diff --git a/web/src/main/java/org/springframework/security/web/access/channel/AbstractRetryEntryPoint.java b/web/src/main/java/org/springframework/security/web/access/channel/AbstractRetryEntryPoint.java index 9efe0bf185..607ada7667 100644 --- a/web/src/main/java/org/springframework/security/web/access/channel/AbstractRetryEntryPoint.java +++ b/web/src/main/java/org/springframework/security/web/access/channel/AbstractRetryEntryPoint.java @@ -59,7 +59,7 @@ public abstract class AbstractRetryEntryPoint implements ChannelEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response) throws IOException { String queryString = request.getQueryString(); - String redirectUrl = request.getRequestURI() + ((queryString == null) ? "" : ("?" + queryString)); + String redirectUrl = request.getRequestURI() + ((queryString != null) ? ("?" + queryString) : ""); Integer currentPort = this.portResolver.getServerPort(request); Integer redirectPort = getMappedPort(currentPort); diff --git a/web/src/main/java/org/springframework/security/web/access/expression/WebExpressionConfigAttribute.java b/web/src/main/java/org/springframework/security/web/access/expression/WebExpressionConfigAttribute.java index 4f40ffc7dd..b967de5e38 100644 --- a/web/src/main/java/org/springframework/security/web/access/expression/WebExpressionConfigAttribute.java +++ b/web/src/main/java/org/springframework/security/web/access/expression/WebExpressionConfigAttribute.java @@ -45,7 +45,7 @@ class WebExpressionConfigAttribute implements ConfigAttribute, EvaluationContext @Override public EvaluationContext postProcess(EvaluationContext context, FilterInvocation fi) { - return this.postProcessor == null ? context : this.postProcessor.postProcess(context, fi); + return (this.postProcessor != null) ? this.postProcessor.postProcess(context, fi) : context; } @Override diff --git a/web/src/main/java/org/springframework/security/web/access/intercept/RequestKey.java b/web/src/main/java/org/springframework/security/web/access/intercept/RequestKey.java index 6779564117..8e6c569313 100644 --- a/web/src/main/java/org/springframework/security/web/access/intercept/RequestKey.java +++ b/web/src/main/java/org/springframework/security/web/access/intercept/RequestKey.java @@ -64,7 +64,7 @@ public class RequestKey { @Override public int hashCode() { int result = this.url.hashCode(); - result = 31 * result + (this.method != null ? this.method.hashCode() : 0); + result = 31 * result + ((this.method != null) ? this.method.hashCode() : 0); return result; } diff --git a/web/src/main/java/org/springframework/security/web/authentication/preauth/j2ee/J2eePreAuthenticatedProcessingFilter.java b/web/src/main/java/org/springframework/security/web/authentication/preauth/j2ee/J2eePreAuthenticatedProcessingFilter.java index edc855132a..4fce63bd38 100755 --- a/web/src/main/java/org/springframework/security/web/authentication/preauth/j2ee/J2eePreAuthenticatedProcessingFilter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/preauth/j2ee/J2eePreAuthenticatedProcessingFilter.java @@ -35,7 +35,7 @@ public class J2eePreAuthenticatedProcessingFilter extends AbstractPreAuthenticat */ @Override protected Object getPreAuthenticatedPrincipal(HttpServletRequest httpRequest) { - Object principal = httpRequest.getUserPrincipal() == null ? null : httpRequest.getUserPrincipal().getName(); + Object principal = (httpRequest.getUserPrincipal() != null) ? httpRequest.getUserPrincipal().getName() : null; if (this.logger.isDebugEnabled()) { this.logger.debug("PreAuthenticated J2EE principal: " + principal); } diff --git a/web/src/main/java/org/springframework/security/web/authentication/rememberme/AbstractRememberMeServices.java b/web/src/main/java/org/springframework/security/web/authentication/rememberme/AbstractRememberMeServices.java index 5e0f49d509..a250449dc8 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/rememberme/AbstractRememberMeServices.java +++ b/web/src/main/java/org/springframework/security/web/authentication/rememberme/AbstractRememberMeServices.java @@ -417,7 +417,7 @@ public abstract class AbstractRememberMeServices implements RememberMeServices, private String getCookiePath(HttpServletRequest request) { String contextPath = request.getContextPath(); - return contextPath.length() > 0 ? contextPath : "/"; + return (contextPath.length() > 0) ? contextPath : "/"; } /** @@ -427,7 +427,7 @@ public abstract class AbstractRememberMeServices implements RememberMeServices, @Override public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { if (this.logger.isDebugEnabled()) { - this.logger.debug("Logout of user " + (authentication == null ? "Unknown" : authentication.getName())); + this.logger.debug("Logout of user " + ((authentication != null) ? authentication.getName() : "Unknown")); } cancelCookie(request, response); } diff --git a/web/src/main/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServices.java b/web/src/main/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServices.java index 649d06726c..d75d228ed2 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServices.java +++ b/web/src/main/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServices.java @@ -187,7 +187,7 @@ public class TokenBasedRememberMeServices extends AbstractRememberMeServices { int tokenLifetime = calculateLoginLifetime(request, successfulAuthentication); long expiryTime = System.currentTimeMillis(); // SEC-949 - expiryTime += 1000L * (tokenLifetime < 0 ? TWO_WEEKS_S : tokenLifetime); + expiryTime += 1000L * ((tokenLifetime < 0) ? TWO_WEEKS_S : tokenLifetime); String signatureValue = makeTokenSignature(expiryTime, username, password); diff --git a/web/src/main/java/org/springframework/security/web/authentication/switchuser/SwitchUserFilter.java b/web/src/main/java/org/springframework/security/web/authentication/switchuser/SwitchUserFilter.java index 5f1dd45139..58e1e4fb44 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/switchuser/SwitchUserFilter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/switchuser/SwitchUserFilter.java @@ -151,8 +151,9 @@ public class SwitchUserFilter extends GenericFilterBean implements ApplicationEv } if (this.failureHandler == null) { - this.failureHandler = this.switchFailureUrl == null ? new SimpleUrlAuthenticationFailureHandler() - : new SimpleUrlAuthenticationFailureHandler(this.switchFailureUrl); + this.failureHandler = (this.switchFailureUrl != null) + ? new SimpleUrlAuthenticationFailureHandler(this.switchFailureUrl) + : new SimpleUrlAuthenticationFailureHandler(); } else { Assert.isNull(this.switchFailureUrl, "You cannot set both a switchFailureUrl and a failureHandler"); diff --git a/web/src/main/java/org/springframework/security/web/authentication/ui/DefaultLoginPageGeneratingFilter.java b/web/src/main/java/org/springframework/security/web/authentication/ui/DefaultLoginPageGeneratingFilter.java index ba90274987..f3c96da440 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/ui/DefaultLoginPageGeneratingFilter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/ui/DefaultLoginPageGeneratingFilter.java @@ -242,7 +242,7 @@ public class DefaultLoginPageGeneratingFilter extends GenericFilterBean { if (session != null) { AuthenticationException ex = (AuthenticationException) session .getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); - errorMsg = ex != null ? ex.getMessage() : "Invalid credentials"; + errorMsg = (ex != null) ? ex.getMessage() : "Invalid credentials"; } } diff --git a/web/src/main/java/org/springframework/security/web/csrf/CookieCsrfTokenRepository.java b/web/src/main/java/org/springframework/security/web/csrf/CookieCsrfTokenRepository.java index b885ea265a..761785fb8e 100644 --- a/web/src/main/java/org/springframework/security/web/csrf/CookieCsrfTokenRepository.java +++ b/web/src/main/java/org/springframework/security/web/csrf/CookieCsrfTokenRepository.java @@ -67,7 +67,7 @@ public final class CookieCsrfTokenRepository implements CsrfTokenRepository { @Override public void saveToken(CsrfToken token, HttpServletRequest request, HttpServletResponse response) { - String tokenValue = token == null ? "" : token.getToken(); + String tokenValue = (token != null) ? token.getToken() : ""; Cookie cookie = new Cookie(this.cookieName, tokenValue); if (this.secure == null) { cookie.setSecure(request.isSecure()); @@ -151,7 +151,7 @@ public final class CookieCsrfTokenRepository implements CsrfTokenRepository { private String getRequestContext(HttpServletRequest request) { String contextPath = request.getContextPath(); - return contextPath.length() > 0 ? contextPath : "/"; + return (contextPath.length() > 0) ? contextPath : "/"; } /** diff --git a/web/src/main/java/org/springframework/security/web/firewall/DefaultHttpFirewall.java b/web/src/main/java/org/springframework/security/web/firewall/DefaultHttpFirewall.java index 4c90eb24c6..ed6b51922a 100644 --- a/web/src/main/java/org/springframework/security/web/firewall/DefaultHttpFirewall.java +++ b/web/src/main/java/org/springframework/security/web/firewall/DefaultHttpFirewall.java @@ -54,7 +54,7 @@ public class DefaultHttpFirewall implements HttpFirewall { if (!isNormalized(fwr.getServletPath()) || !isNormalized(fwr.getPathInfo())) { throw new RequestRejectedException("Un-normalized paths are not supported: " + fwr.getServletPath() - + (fwr.getPathInfo() != null ? fwr.getPathInfo() : "")); + + ((fwr.getPathInfo() != null) ? fwr.getPathInfo() : "")); } String requestURI = fwr.getRequestURI(); diff --git a/web/src/main/java/org/springframework/security/web/jackson2/CookieDeserializer.java b/web/src/main/java/org/springframework/security/web/jackson2/CookieDeserializer.java index f6ad7efc04..90e1273faf 100644 --- a/web/src/main/java/org/springframework/security/web/jackson2/CookieDeserializer.java +++ b/web/src/main/java/org/springframework/security/web/jackson2/CookieDeserializer.java @@ -57,8 +57,12 @@ class CookieDeserializer extends JsonDeserializer { } private JsonNode readJsonNode(JsonNode jsonNode, String field) { - return jsonNode.has(field) && !(jsonNode.get(field) instanceof NullNode) ? jsonNode.get(field) + return hasNonNullField(jsonNode, field) ? jsonNode.get(field) : MissingNode.getInstance(); } + private boolean hasNonNullField(JsonNode jsonNode, String field) { + return jsonNode.has(field) && !(jsonNode.get(field) instanceof NullNode); + } + } diff --git a/web/src/main/java/org/springframework/security/web/reactive/result/method/annotation/AuthenticationPrincipalArgumentResolver.java b/web/src/main/java/org/springframework/security/web/reactive/result/method/annotation/AuthenticationPrincipalArgumentResolver.java index edc2ee76be..6068d82f9d 100644 --- a/web/src/main/java/org/springframework/security/web/reactive/result/method/annotation/AuthenticationPrincipalArgumentResolver.java +++ b/web/src/main/java/org/springframework/security/web/reactive/result/method/annotation/AuthenticationPrincipalArgumentResolver.java @@ -75,7 +75,7 @@ public class AuthenticationPrincipalArgumentResolver extends HandlerMethodArgume return ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication).flatMap((a) -> { Object p = resolvePrincipal(parameter, a.getPrincipal()); Mono principal = Mono.justOrEmpty(p); - return adapter == null ? principal : Mono.just(adapter.fromPublisher(principal)); + return (adapter != null) ? Mono.just(adapter.fromPublisher(principal)) : principal; }); } diff --git a/web/src/main/java/org/springframework/security/web/reactive/result/method/annotation/CurrentSecurityContextArgumentResolver.java b/web/src/main/java/org/springframework/security/web/reactive/result/method/annotation/CurrentSecurityContextArgumentResolver.java index af4a52ed49..101749642f 100644 --- a/web/src/main/java/org/springframework/security/web/reactive/result/method/annotation/CurrentSecurityContextArgumentResolver.java +++ b/web/src/main/java/org/springframework/security/web/reactive/result/method/annotation/CurrentSecurityContextArgumentResolver.java @@ -87,7 +87,7 @@ public class CurrentSecurityContextArgumentResolver extends HandlerMethodArgumen return reactiveSecurityContext.flatMap((a) -> { Object p = resolveSecurityContext(parameter, a); Mono o = Mono.justOrEmpty(p); - return adapter == null ? o : Mono.just(adapter.fromPublisher(o)); + return (adapter != null) ? Mono.just(adapter.fromPublisher(o)) : o; }); } diff --git a/web/src/main/java/org/springframework/security/web/savedrequest/RequestCacheAwareFilter.java b/web/src/main/java/org/springframework/security/web/savedrequest/RequestCacheAwareFilter.java index 773072bd88..27657614c0 100644 --- a/web/src/main/java/org/springframework/security/web/savedrequest/RequestCacheAwareFilter.java +++ b/web/src/main/java/org/springframework/security/web/savedrequest/RequestCacheAwareFilter.java @@ -62,7 +62,7 @@ public class RequestCacheAwareFilter extends GenericFilterBean { HttpServletRequest wrappedSavedRequest = this.requestCache.getMatchingRequest((HttpServletRequest) request, (HttpServletResponse) response); - chain.doFilter(wrappedSavedRequest == null ? request : wrappedSavedRequest, response); + chain.doFilter((wrappedSavedRequest != null) ? wrappedSavedRequest : request, response); } } diff --git a/web/src/main/java/org/springframework/security/web/server/ServerHttpBasicAuthenticationConverter.java b/web/src/main/java/org/springframework/security/web/server/ServerHttpBasicAuthenticationConverter.java index 334e4ed2f7..e0afa30196 100644 --- a/web/src/main/java/org/springframework/security/web/server/ServerHttpBasicAuthenticationConverter.java +++ b/web/src/main/java/org/springframework/security/web/server/ServerHttpBasicAuthenticationConverter.java @@ -53,7 +53,7 @@ public class ServerHttpBasicAuthenticationConverter implements Function saveToken(ServerWebExchange exchange, CsrfToken token) { return Mono.fromRunnable(() -> { - String tokenValue = token != null ? token.getToken() : ""; + String tokenValue = (token != null) ? token.getToken() : ""; int maxAge = !tokenValue.isEmpty() ? -1 : 0; - String path = this.cookiePath != null ? this.cookiePath : getRequestContext(exchange.getRequest()); + String path = (this.cookiePath != null) ? this.cookiePath : getRequestContext(exchange.getRequest()); boolean secure = exchange.getRequest().getSslInfo() != null; ResponseCookie cookie = ResponseCookie.from(this.cookieName, tokenValue).domain(this.cookieDomain) diff --git a/web/src/main/java/org/springframework/security/web/server/savedrequest/CookieServerRequestCache.java b/web/src/main/java/org/springframework/security/web/server/savedrequest/CookieServerRequestCache.java index d9135feb3d..ca8bd11c79 100644 --- a/web/src/main/java/org/springframework/security/web/server/savedrequest/CookieServerRequestCache.java +++ b/web/src/main/java/org/springframework/security/web/server/savedrequest/CookieServerRequestCache.java @@ -99,7 +99,7 @@ public class CookieServerRequestCache implements ServerRequestCache { private static ResponseCookie createRedirectUriCookie(ServerHttpRequest request) { String path = request.getPath().pathWithinApplication().value(); String query = request.getURI().getRawQuery(); - String redirectUri = path + (query != null ? "?" + query : ""); + String redirectUri = path + ((query != null) ? "?" + query : ""); return createResponseCookie(request, encodeCookie(redirectUri), COOKIE_MAX_AGE); } diff --git a/web/src/main/java/org/springframework/security/web/server/savedrequest/WebSessionServerRequestCache.java b/web/src/main/java/org/springframework/security/web/server/savedrequest/WebSessionServerRequestCache.java index 533e960ed0..37822da309 100644 --- a/web/src/main/java/org/springframework/security/web/server/savedrequest/WebSessionServerRequestCache.java +++ b/web/src/main/java/org/springframework/security/web/server/savedrequest/WebSessionServerRequestCache.java @@ -102,7 +102,7 @@ public class WebSessionServerRequestCache implements ServerRequestCache { private static String pathInApplication(ServerHttpRequest request) { String path = request.getPath().pathWithinApplication().value(); String query = request.getURI().getRawQuery(); - return path + (query != null ? "?" + query : ""); + return path + ((query != null) ? "?" + query : ""); } private static ServerWebExchangeMatcher createDefaultRequestMacher() { diff --git a/web/src/main/java/org/springframework/security/web/servlet/util/matcher/MvcRequestMatcher.java b/web/src/main/java/org/springframework/security/web/servlet/util/matcher/MvcRequestMatcher.java index 9a9afc8efa..8ca395e047 100644 --- a/web/src/main/java/org/springframework/security/web/servlet/util/matcher/MvcRequestMatcher.java +++ b/web/src/main/java/org/springframework/security/web/servlet/util/matcher/MvcRequestMatcher.java @@ -100,7 +100,7 @@ public class MvcRequestMatcher implements RequestMatcher, RequestVariablesExtrac return this.defaultMatcher.matcher(request); } RequestMatchResult result = mapping.match(request, this.pattern); - return result == null ? MatchResult.notMatch() : MatchResult.match(result.extractUriTemplateVariables()); + return (result != null) ? MatchResult.match(result.extractUriTemplateVariables()) : MatchResult.notMatch(); } /** diff --git a/web/src/main/java/org/springframework/security/web/util/OnCommittedResponseWrapper.java b/web/src/main/java/org/springframework/security/web/util/OnCommittedResponseWrapper.java index d35d6336a0..6cd63e0e4c 100644 --- a/web/src/main/java/org/springframework/security/web/util/OnCommittedResponseWrapper.java +++ b/web/src/main/java/org/springframework/security/web/util/OnCommittedResponseWrapper.java @@ -186,13 +186,13 @@ public abstract class OnCommittedResponseWrapper extends HttpServletResponseWrap private void trackContentLength(byte[] content) { if (!this.disableOnCommitted) { - checkContentLength(content == null ? 0 : content.length); + checkContentLength((content != null) ? content.length : 0); } } private void trackContentLength(char[] content) { if (!this.disableOnCommitted) { - checkContentLength(content == null ? 0 : content.length); + checkContentLength((content != null) ? content.length : 0); } } @@ -222,7 +222,7 @@ public abstract class OnCommittedResponseWrapper extends HttpServletResponseWrap private void trackContentLength(String content) { if (!this.disableOnCommitted) { - int contentLength = content == null ? 4 : content.length(); + int contentLength = (content != null) ? content.length() : 4; checkContentLength(contentLength); } } diff --git a/web/src/main/java/org/springframework/security/web/util/matcher/AntPathRequestMatcher.java b/web/src/main/java/org/springframework/security/web/util/matcher/AntPathRequestMatcher.java index abd5b0b089..0e707cfdfe 100644 --- a/web/src/main/java/org/springframework/security/web/util/matcher/AntPathRequestMatcher.java +++ b/web/src/main/java/org/springframework/security/web/util/matcher/AntPathRequestMatcher.java @@ -220,8 +220,8 @@ public final class AntPathRequestMatcher implements RequestMatcher, RequestVaria @Override public int hashCode() { - int result = this.pattern != null ? this.pattern.hashCode() : 0; - result = 31 * result + (this.httpMethod != null ? this.httpMethod.hashCode() : 0); + int result = (this.pattern != null) ? this.pattern.hashCode() : 0; + result = 31 * result + ((this.httpMethod != null) ? this.httpMethod.hashCode() : 0); result = 31 * result + (this.caseSensitive ? 1231 : 1237); return result; } diff --git a/web/src/test/java/org/springframework/security/web/method/ResolvableMethod.java b/web/src/test/java/org/springframework/security/web/method/ResolvableMethod.java index 933d2efaad..0e8f447630 100644 --- a/web/src/test/java/org/springframework/security/web/method/ResolvableMethod.java +++ b/web/src/test/java/org/springframework/security/web/method/ResolvableMethod.java @@ -215,7 +215,7 @@ public final class ResolvableMethod { private String formatParameter(Parameter param) { Annotation[] annot = param.getAnnotations(); - return annot.length > 0 + return (annot.length > 0) ? Arrays.stream(annot).map(this::formatAnnotation).collect(Collectors.joining(",", "[", "]")) + " " + param : param.toString();