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
This commit is contained in:
Phillip Webb
2020-07-30 00:31:13 -07:00
committed by Rob Winch
parent 8d3f039f76
commit 834dcf5bcf
131 changed files with 277 additions and 265 deletions

View File

@@ -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();

View File

@@ -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

View File

@@ -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);

View File

@@ -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

View File

@@ -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;
}

View File

@@ -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);
}

View File

@@ -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);
}

View File

@@ -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);

View File

@@ -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");

View File

@@ -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";
}
}

View File

@@ -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 : "/";
}
/**

View File

@@ -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();

View File

@@ -57,8 +57,12 @@ class CookieDeserializer extends JsonDeserializer<Cookie> {
}
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);
}
}

View File

@@ -75,7 +75,7 @@ public class AuthenticationPrincipalArgumentResolver extends HandlerMethodArgume
return ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication).flatMap((a) -> {
Object p = resolvePrincipal(parameter, a.getPrincipal());
Mono<Object> principal = Mono.justOrEmpty(p);
return adapter == null ? principal : Mono.just(adapter.fromPublisher(principal));
return (adapter != null) ? Mono.just(adapter.fromPublisher(principal)) : principal;
});
}

View File

@@ -87,7 +87,7 @@ public class CurrentSecurityContextArgumentResolver extends HandlerMethodArgumen
return reactiveSecurityContext.flatMap((a) -> {
Object p = resolveSecurityContext(parameter, a);
Mono<Object> o = Mono.justOrEmpty(p);
return adapter == null ? o : Mono.just(adapter.fromPublisher(o));
return (adapter != null) ? Mono.just(adapter.fromPublisher(o)) : o;
});
}

View File

@@ -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);
}
}

View File

@@ -53,7 +53,7 @@ public class ServerHttpBasicAuthenticationConverter implements Function<ServerWe
return Mono.empty();
}
String credentials = authorization.length() <= BASIC.length() ? ""
String credentials = (authorization.length() <= BASIC.length()) ? ""
: authorization.substring(BASIC.length(), authorization.length());
byte[] decodedCredentials = base64Decode(credentials);
String decodedAuthz = new String(decodedCredentials);

View File

@@ -73,9 +73,9 @@ public final class CookieServerCsrfTokenRepository implements ServerCsrfTokenRep
@Override
public Mono<Void> 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)

View File

@@ -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);
}

View File

@@ -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() {

View File

@@ -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();
}
/**

View File

@@ -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);
}
}

View File

@@ -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;
}

View File

@@ -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();