Skip to content

Commit 9198e03

Browse files
committed
Consistent use of StringUtils.hasLength(String) vs isEmpty(Object)
1 parent 5be693d commit 9198e03

File tree

17 files changed

+76
-76
lines changed

17 files changed

+76
-76
lines changed

spring-core/src/main/java/org/springframework/util/StringUtils.java

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,15 +75,20 @@ public abstract class StringUtils {
7575
//---------------------------------------------------------------------
7676

7777
/**
78-
* Check whether the given {@code String} is empty.
78+
* Check whether the given object (possibly a {@code String}) is empty.
79+
* This is effectly a shortcut for {@code !hasLength(String)}.
7980
* <p>This method accepts any Object as an argument, comparing it to
8081
* {@code null} and the empty String. As a consequence, this method
8182
* will never return {@code true} for a non-null non-String object.
8283
* <p>The Object signature is useful for general attribute handling code
8384
* that commonly deals with Strings but generally has to iterate over
8485
* Objects since attributes may e.g. be primitive value objects as well.
85-
* @param str the candidate String
86+
* <p><b>Note: If the object is typed to {@code String} upfront, prefer
87+
* {@link #hasLength(String)} or {@link #hasText(String)} instead.</b>
88+
* @param str the candidate object (possibly a {@code String})
8689
* @since 3.2.1
90+
* @see #hasLength(String)
91+
* @see #hasText(String)
8792
*/
8893
public static boolean isEmpty(@Nullable Object str) {
8994
return (str == null || "".equals(str));
@@ -136,6 +141,8 @@ public static boolean hasLength(@Nullable String str) {
136141
* @param str the {@code CharSequence} to check (may be {@code null})
137142
* @return {@code true} if the {@code CharSequence} is not {@code null},
138143
* its length is greater than 0, and it does not contain whitespace only
144+
* @see #hasText(String)
145+
* @see #hasLength(CharSequence)
139146
* @see Character#isWhitespace
140147
*/
141148
public static boolean hasText(@Nullable CharSequence str) {
@@ -151,6 +158,8 @@ public static boolean hasText(@Nullable CharSequence str) {
151158
* @return {@code true} if the {@code String} is not {@code null}, its
152159
* length is greater than 0, and it does not contain whitespace only
153160
* @see #hasText(CharSequence)
161+
* @see #hasLength(String)
162+
* @see Character#isWhitespace
154163
*/
155164
public static boolean hasText(@Nullable String str) {
156165
return (str != null && !str.isEmpty() && containsText(str));

spring-jdbc/src/main/java/org/springframework/jdbc/core/JdbcTemplate.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -564,7 +564,7 @@ public int[] doInStatement(Statement stmt) throws SQLException, DataAccessExcept
564564
}
565565

566566
private String appendSql(@Nullable String sql, String statement) {
567-
return (StringUtils.isEmpty(sql) ? statement : sql + "; " + statement);
567+
return (StringUtils.hasLength(sql) ? sql + "; " + statement : statement);
568568
}
569569

570570
@Override

spring-web/src/main/java/org/springframework/http/HttpHeaders.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -700,7 +700,7 @@ public void setAllow(Set<HttpMethod> allowedMethods) {
700700
*/
701701
public Set<HttpMethod> getAllow() {
702702
String value = getFirst(ALLOW);
703-
if (!StringUtils.isEmpty(value)) {
703+
if (StringUtils.hasLength(value)) {
704704
String[] tokens = StringUtils.tokenizeToStringArray(value, ",");
705705
List<HttpMethod> result = new ArrayList<>(tokens.length);
706706
for (String token : tokens) {

spring-web/src/main/java/org/springframework/http/server/reactive/UndertowServerHttpRequest.java

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2018 the original author or authors.
2+
* Copyright 2002-2019 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -70,10 +70,10 @@ public UndertowServerHttpRequest(HttpServerExchange exchange, DataBufferFactory
7070
}
7171

7272
private static URI initUri(HttpServerExchange exchange) throws URISyntaxException {
73-
Assert.notNull(exchange, "HttpServerExchange is required.");
73+
Assert.notNull(exchange, "HttpServerExchange is required");
7474
String requestURL = exchange.getRequestURL();
7575
String query = exchange.getQueryString();
76-
String requestUriAndQuery = StringUtils.isEmpty(query) ? requestURL : requestURL + "?" + query;
76+
String requestUriAndQuery = (StringUtils.hasLength(query) ? requestURL + "?" + query : requestURL);
7777
return new URI(requestUriAndQuery);
7878
}
7979

@@ -171,12 +171,10 @@ protected DataBuffer read() throws IOException {
171171
boolean release = true;
172172
try {
173173
ByteBuffer byteBuffer = pooledByteBuffer.getBuffer();
174-
175174
int read = this.channel.read(byteBuffer);
176175
if (logger.isTraceEnabled()) {
177176
logger.trace("Channel read returned " + read + (read != -1 ? " bytes" : ""));
178177
}
179-
180178
if (read > 0) {
181179
byteBuffer.flip();
182180
DataBuffer dataBuffer = this.bufferFactory.wrap(byteBuffer);
@@ -187,7 +185,8 @@ else if (read == -1) {
187185
onAllDataRead();
188186
}
189187
return null;
190-
} finally {
188+
}
189+
finally {
191190
if (release && pooledByteBuffer.isOpen()) {
192191
pooledByteBuffer.close();
193192
}
@@ -200,6 +199,7 @@ protected void discardData() {
200199
}
201200
}
202201

202+
203203
private static class UndertowDataBuffer implements PooledDataBuffer {
204204

205205
private final DataBuffer dataBuffer;
@@ -299,8 +299,7 @@ public DataBuffer read(byte[] destination) {
299299
}
300300

301301
@Override
302-
public DataBuffer read(byte[] destination, int offset,
303-
int length) {
302+
public DataBuffer read(byte[] destination, int offset, int length) {
304303
return this.dataBuffer.read(destination, offset, length);
305304
}
306305

@@ -315,20 +314,17 @@ public DataBuffer write(byte[] source) {
315314
}
316315

317316
@Override
318-
public DataBuffer write(byte[] source, int offset,
319-
int length) {
317+
public DataBuffer write(byte[] source, int offset, int length) {
320318
return this.dataBuffer.write(source, offset, length);
321319
}
322320

323321
@Override
324-
public DataBuffer write(
325-
DataBuffer... buffers) {
322+
public DataBuffer write(DataBuffer... buffers) {
326323
return this.dataBuffer.write(buffers);
327324
}
328325

329326
@Override
330-
public DataBuffer write(
331-
ByteBuffer... byteBuffers) {
327+
public DataBuffer write(ByteBuffer... byteBuffers) {
332328
return this.dataBuffer.write(byteBuffers);
333329
}
334330

@@ -362,4 +358,5 @@ public OutputStream asOutputStream() {
362358
return this.dataBuffer.asOutputStream();
363359
}
364360
}
361+
365362
}

spring-web/src/main/java/org/springframework/web/method/annotation/RequestParamMethodArgumentResolver.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2018 the original author or authors.
2+
* Copyright 2002-2019 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -213,8 +213,8 @@ public void contributeMethodArgument(MethodParameter parameter, @Nullable Object
213213
}
214214

215215
RequestParam requestParam = parameter.getParameterAnnotation(RequestParam.class);
216-
String name = (requestParam == null || StringUtils.isEmpty(requestParam.name()) ?
217-
parameter.getParameterName() : requestParam.name());
216+
String name = (requestParam != null && StringUtils.hasLength(requestParam.name()) ?
217+
requestParam.name() : parameter.getParameterName());
218218
Assert.state(name != null, "Unresolvable parameter name");
219219

220220
if (value == null) {

spring-web/src/main/java/org/springframework/web/util/DefaultUriBuilderFactory.java

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2018 the original author or authors.
2+
* Copyright 2002-2019 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -33,7 +33,6 @@
3333
* <p>Provides options to create {@link UriBuilder} instances with a common
3434
* base URI, alternative encoding mode strategies, among others.
3535
*
36-
*
3736
* @author Rossen Stoyanchev
3837
* @since 5.0
3938
* @see UriComponentsBuilder
@@ -222,31 +221,27 @@ private class DefaultUriBuilder implements UriBuilder {
222221

223222
private final UriComponentsBuilder uriComponentsBuilder;
224223

225-
226224
public DefaultUriBuilder(String uriTemplate) {
227225
this.uriComponentsBuilder = initUriComponentsBuilder(uriTemplate);
228226
}
229227

230228
private UriComponentsBuilder initUriComponentsBuilder(String uriTemplate) {
231229
UriComponentsBuilder result;
232-
if (StringUtils.isEmpty(uriTemplate)) {
233-
result = baseUri != null ? baseUri.cloneBuilder() : UriComponentsBuilder.newInstance();
230+
if (!StringUtils.hasLength(uriTemplate)) {
231+
result = (baseUri != null ? baseUri.cloneBuilder() : UriComponentsBuilder.newInstance());
234232
}
235233
else if (baseUri != null) {
236234
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(uriTemplate);
237235
UriComponents uri = builder.build();
238-
result = uri.getHost() == null ? baseUri.cloneBuilder().uriComponents(uri) : builder;
236+
result = (uri.getHost() == null ? baseUri.cloneBuilder().uriComponents(uri) : builder);
239237
}
240238
else {
241239
result = UriComponentsBuilder.fromUriString(uriTemplate);
242240
}
243-
244241
if (encodingMode.equals(EncodingMode.TEMPLATE_AND_VALUES)) {
245242
result.encode();
246243
}
247-
248244
parsePathIfNecessary(result);
249-
250245
return result;
251246
}
252247

spring-webflux/src/main/java/org/springframework/web/reactive/resource/VersionResourceResolver.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2018 the original author or authors.
2+
* Copyright 2002-2019 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -172,7 +172,7 @@ private Mono<Resource> resolveVersionedResource(@Nullable ServerWebExchange exch
172172
}
173173

174174
String candidate = versionStrategy.extractVersion(requestPath);
175-
if (StringUtils.isEmpty(candidate)) {
175+
if (!StringUtils.hasLength(candidate)) {
176176
if (logger.isTraceEnabled()) {
177177
logger.trace("No version found in path \"" + requestPath + "\"");
178178
}

spring-webflux/src/main/java/org/springframework/web/reactive/result/view/RedirectView.java

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2018 the original author or authors.
2+
* Copyright 2002-2019 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -44,8 +44,8 @@
4444
* URI template in which case the URI template variables will be replaced with
4545
* values from the model or with URI variables from the current request.
4646
*
47-
* <p>By default {@link HttpStatus#SEE_OTHER} is used but alternate status
48-
* codes may be via constructor or setters arguments.
47+
* <p>By default {@link HttpStatus#SEE_OTHER} is used but alternate status codes
48+
* may be via constructor or setters arguments.
4949
*
5050
* @author Sebastien Deleuze
5151
* @author Rossen Stoyanchev
@@ -56,10 +56,10 @@ public class RedirectView extends AbstractUrlBasedView {
5656
private static final Pattern URI_TEMPLATE_VARIABLE_PATTERN = Pattern.compile("\\{([^/]+?)\\}");
5757

5858

59-
private boolean contextRelative = true;
60-
6159
private HttpStatus statusCode = HttpStatus.SEE_OTHER;
6260

61+
private boolean contextRelative = true;
62+
6363
private boolean propagateQuery = false;
6464

6565
@Nullable
@@ -91,22 +91,6 @@ public RedirectView(String redirectUrl, HttpStatus statusCode) {
9191
}
9292

9393

94-
/**
95-
* Whether to interpret a given redirect URLs that starts with a slash ("/")
96-
* as relative to the current context path ({@code true}, the default) or to
97-
* the web server root ({@code false}).
98-
*/
99-
public void setContextRelative(boolean contextRelative) {
100-
this.contextRelative = contextRelative;
101-
}
102-
103-
/**
104-
* Whether to interpret URLs as relative to the current context path.
105-
*/
106-
public boolean isContextRelative() {
107-
return this.contextRelative;
108-
}
109-
11094
/**
11195
* Set an alternate redirect status code such as
11296
* {@link HttpStatus#TEMPORARY_REDIRECT} or
@@ -124,6 +108,22 @@ public HttpStatus getStatusCode() {
124108
return this.statusCode;
125109
}
126110

111+
/**
112+
* Whether to interpret a given redirect URLs that starts with a slash ("/")
113+
* as relative to the current context path ({@code true}, the default) or to
114+
* the web server root ({@code false}).
115+
*/
116+
public void setContextRelative(boolean contextRelative) {
117+
this.contextRelative = contextRelative;
118+
}
119+
120+
/**
121+
* Whether to interpret URLs as relative to the current context path.
122+
*/
123+
public boolean isContextRelative() {
124+
return this.contextRelative;
125+
}
126+
127127
/**
128128
* Whether to append the query string of the current URL to the redirect URL
129129
* ({@code true}) or not ({@code false}, the default).
@@ -309,7 +309,7 @@ protected boolean isRemoteHost(String targetUrl) {
309309
return false;
310310
}
311311
String targetHost = UriComponentsBuilder.fromUriString(targetUrl).build().getHost();
312-
if (StringUtils.isEmpty(targetHost)) {
312+
if (!StringUtils.hasLength(targetHost)) {
313313
return false;
314314
}
315315
for (String host : this.hosts) {

spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilder.java

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2018 the original author or authors.
2+
* Copyright 2002-2019 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -357,11 +357,10 @@ public static MethodArgumentBuilder fromMappingName(@Nullable UriComponentsBuild
357357
RequestMappingInfoHandlerMapping handlerMapping = getRequestMappingInfoHandlerMapping();
358358
List<HandlerMethod> handlerMethods = handlerMapping.getHandlerMethodsForMappingName(name);
359359
if (handlerMethods == null) {
360-
throw new IllegalArgumentException("Mapping mappingName not found: " + name);
360+
throw new IllegalArgumentException("Mapping not found: " + name);
361361
}
362362
if (handlerMethods.size() != 1) {
363-
throw new IllegalArgumentException("No unique match for mapping mappingName " +
364-
name + ": " + handlerMethods);
363+
throw new IllegalArgumentException("No unique match for mapping " + name + ": " + handlerMethods);
365364
}
366365
HandlerMethod handlerMethod = handlerMethods.get(0);
367366
Class<?> controllerType = handlerMethod.getBeanType();
@@ -440,7 +439,7 @@ private static String getTypeRequestMapping(Class<?> controllerType) {
440439
return "/";
441440
}
442441
String[] paths = requestMapping.path();
443-
if (ObjectUtils.isEmpty(paths) || StringUtils.isEmpty(paths[0])) {
442+
if (ObjectUtils.isEmpty(paths) || !StringUtils.hasLength(paths[0])) {
444443
return "/";
445444
}
446445
if (paths.length > 1 && logger.isWarnEnabled()) {
@@ -456,7 +455,7 @@ private static String getMethodRequestMapping(Method method) {
456455
throw new IllegalArgumentException("No @RequestMapping on: " + method.toGenericString());
457456
}
458457
String[] paths = requestMapping.path();
459-
if (ObjectUtils.isEmpty(paths) || StringUtils.isEmpty(paths[0])) {
458+
if (ObjectUtils.isEmpty(paths) || !StringUtils.hasLength(paths[0])) {
460459
return "/";
461460
}
462461
if (paths.length > 1 && logger.isWarnEnabled()) {

spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/PathVariableMethodArgumentResolver.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2017 the original author or authors.
2+
* Copyright 2002-2019 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -125,7 +125,7 @@ public void contributeMethodArgument(MethodParameter parameter, Object value,
125125
}
126126

127127
PathVariable ann = parameter.getParameterAnnotation(PathVariable.class);
128-
String name = (ann != null && !StringUtils.isEmpty(ann.value()) ? ann.value() : parameter.getParameterName());
128+
String name = (ann != null && StringUtils.hasLength(ann.value()) ? ann.value() : parameter.getParameterName());
129129
String formatted = formatUriValue(conversionService, new TypeDescriptor(parameter.nestedIfOptional()), value);
130130
uriVariables.put(name, formatted);
131131
}

spring-webmvc/src/main/java/org/springframework/web/servlet/resource/VersionResourceResolver.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2018 the original author or authors.
2+
* Copyright 2002-2019 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -168,7 +168,7 @@ protected Resource resolveResourceInternal(@Nullable HttpServletRequest request,
168168
}
169169

170170
String candidateVersion = versionStrategy.extractVersion(requestPath);
171-
if (StringUtils.isEmpty(candidateVersion)) {
171+
if (!StringUtils.hasLength(candidateVersion)) {
172172
if (logger.isTraceEnabled()) {
173173
logger.trace("No version found in path \"" + requestPath + "\"");
174174
}

0 commit comments

Comments
 (0)