Use String#isEmpty()

Closes gh-1335
(cherry picked from commit 7d062df)
This commit is contained in:
stonio 2017-02-21 16:23:40 +01:00 committed by Juergen Hoeller
parent 34a0857628
commit 1db42081e5
15 changed files with 93 additions and 110 deletions

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -150,10 +150,10 @@ public abstract class PropertyMatches {
* @return the distance value
*/
private static int calculateStringDistance(String s1, String s2) {
if (s1.length() == 0) {
if (s1.isEmpty()) {
return s2.length();
}
if (s2.length() == 0) {
if (s2.isEmpty()) {
return s1.length();
}
int d[][] = new int[s1.length() + 1][s2.length() + 1];

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -28,7 +28,7 @@ final class StringToCharacterConverter implements Converter<String, Character> {
@Override
public Character convert(String source) {
if (source.length() == 0) {
if (source.isEmpty()) {
return null;
}
if (source.length() > 1) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -45,7 +45,7 @@ final class StringToEnumConverterFactory implements ConverterFactory<String, Enu
@Override
public T convert(String source) {
if (source.length() == 0) {
if (source.isEmpty()) {
// It's an empty enum identifier: reset the enum value to null.
return null;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -56,7 +56,7 @@ final class StringToNumberConverterFactory implements ConverterFactory<String, N
@Override
public T convert(String source) {
if (source.length() == 0) {
if (source.isEmpty()) {
return null;
}
return NumberUtils.parseNumber(source, this.targetType);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -833,7 +833,7 @@ public class PathMatchingResourcePatternResolver implements ResourcePatternResol
public PatternVirtualFileVisitor(String rootPath, String subPattern, PathMatcher pathMatcher) {
this.subPattern = subPattern;
this.pathMatcher = pathMatcher;
this.rootPath = (rootPath.length() == 0 || rootPath.endsWith("/") ? rootPath : rootPath + "/");
this.rootPath = (rootPath.isEmpty() || rootPath.endsWith("/") ? rootPath : rootPath + "/");
}
@Override

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -159,7 +159,7 @@ public abstract class Base64Utils {
if (src == null) {
return null;
}
if (src.length() == 0) {
if (src.isEmpty()) {
return new byte[0];
}

View File

@ -243,7 +243,7 @@ public abstract class MimeTypeUtils {
int index = mimeType.indexOf(';');
String fullType = (index >= 0 ? mimeType.substring(0, index) : mimeType).trim();
if (fullType.length() == 0) {
if (fullType.isEmpty()) {
throw new InvalidMimeTypeException(mimeType, "'mimeType' must not be empty");
}

View File

@ -371,7 +371,7 @@ public abstract class StringUtils {
* @param sub string to search for. Return 0 if this is {@code null}.
*/
public static int countOccurrencesOf(String str, String sub) {
if (str == null || sub == null || str.length() == 0 || sub.length() == 0) {
if (!hasLength(str) || !hasLength(sub)) {
return 0;
}
int count = 0;
@ -513,25 +513,23 @@ public abstract class StringUtils {
}
private static String changeFirstCharacterCase(String str, boolean capitalize) {
if (str == null || str.length() == 0) {
if (!hasLength(str)) {
return str;
}
else {
char baseChar = str.charAt(0);
char updatedChar;
if (capitalize) {
updatedChar = Character.toUpperCase(baseChar);
}
else {
updatedChar = Character.toLowerCase(baseChar);
}
if (baseChar == updatedChar) {
return str;
}
char[] chars = str.toCharArray();
chars[0] = updatedChar;
return new String(chars, 0, chars.length);
char baseChar = str.charAt(0);
char updatedChar;
if (capitalize) {
updatedChar = Character.toUpperCase(baseChar);
}
else {
updatedChar = Character.toLowerCase(baseChar);
}
if (baseChar == updatedChar) {
return str;
}
char[] chars = str.toCharArray();
chars[0] = updatedChar;
return new String(chars, 0, chars.length);
}
/**

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -223,8 +223,8 @@ abstract class AbstractStaxHandler implements ContentHandler, LexicalHandler {
protected boolean isNamespaceDeclaration(QName qName) {
String prefix = qName.getPrefix();
String localPart = qName.getLocalPart();
return (XMLConstants.XMLNS_ATTRIBUTE.equals(localPart) && prefix.length() == 0) ||
(XMLConstants.XMLNS_ATTRIBUTE.equals(prefix) && localPart.length() != 0);
return (XMLConstants.XMLNS_ATTRIBUTE.equals(localPart) && prefix.isEmpty()) ||
(XMLConstants.XMLNS_ATTRIBUTE.equals(prefix) && !localPart.isEmpty());
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -40,31 +40,28 @@ public abstract class TemplateAwareExpressionParser implements ExpressionParser
* Default ParserContext instance for non-template expressions.
*/
private static final ParserContext NON_TEMPLATE_PARSER_CONTEXT = new ParserContext() {
@Override
public String getExpressionPrefix() {
return null;
}
@Override
public String getExpressionSuffix() {
return null;
}
@Override
public boolean isTemplate() {
return false;
}
};
@Override
public Expression parseExpression(String expressionString) throws ParseException {
return parseExpression(expressionString, NON_TEMPLATE_PARSER_CONTEXT);
}
@Override
public Expression parseExpression(String expressionString, ParserContext context)
throws ParseException {
public Expression parseExpression(String expressionString, ParserContext context) throws ParseException {
if (context == null) {
context = NON_TEMPLATE_PARSER_CONTEXT;
}
@ -77,11 +74,12 @@ public abstract class TemplateAwareExpressionParser implements ExpressionParser
}
}
private Expression parseTemplate(String expressionString, ParserContext context)
throws ParseException {
if (expressionString.length() == 0) {
private Expression parseTemplate(String expressionString, ParserContext context) throws ParseException {
if (expressionString.isEmpty()) {
return new LiteralExpression("");
}
Expression[] expressions = parseExpressions(expressionString, context);
if (expressions.length == 1) {
return expressions[0];
@ -109,8 +107,7 @@ public abstract class TemplateAwareExpressionParser implements ExpressionParser
* @return the parsed expressions
* @throws ParseException when the expressions cannot be parsed
*/
private Expression[] parseExpressions(String expressionString, ParserContext context)
throws ParseException {
private Expression[] parseExpressions(String expressionString, ParserContext context) throws ParseException {
List<Expression> expressions = new LinkedList<Expression>();
String prefix = context.getExpressionPrefix();
String suffix = context.getExpressionSuffix();
@ -120,35 +117,29 @@ public abstract class TemplateAwareExpressionParser implements ExpressionParser
if (prefixIndex >= startIdx) {
// an inner expression was found - this is a composite
if (prefixIndex > startIdx) {
expressions.add(createLiteralExpression(context,
expressionString.substring(startIdx, prefixIndex)));
expressions.add(new LiteralExpression(expressionString.substring(startIdx, prefixIndex)));
}
int afterPrefixIndex = prefixIndex + prefix.length();
int suffixIndex = skipToCorrectEndSuffix(prefix, suffix,
expressionString, afterPrefixIndex);
int suffixIndex = skipToCorrectEndSuffix(suffix, expressionString, afterPrefixIndex);
if (suffixIndex == -1) {
throw new ParseException(expressionString, prefixIndex,
"No ending suffix '" + suffix
+ "' for expression starting at character "
+ prefixIndex + ": "
+ expressionString.substring(prefixIndex));
"No ending suffix '" + suffix + "' for expression starting at character " +
prefixIndex + ": " + expressionString.substring(prefixIndex));
}
if (suffixIndex == afterPrefixIndex) {
throw new ParseException(expressionString, prefixIndex,
"No expression defined within delimiter '" + prefix + suffix
+ "' at character " + prefixIndex);
"No expression defined within delimiter '" + prefix + suffix +
"' at character " + prefixIndex);
}
String expr = expressionString.substring(prefixIndex + prefix.length(),
suffixIndex);
String expr = expressionString.substring(prefixIndex + prefix.length(), suffixIndex);
expr = expr.trim();
if (expr.length() == 0) {
if (expr.isEmpty()) {
throw new ParseException(expressionString, prefixIndex,
"No expression defined within delimiter '" + prefix + suffix
+ "' at character " + prefixIndex);
"No expression defined within delimiter '" + prefix + suffix +
"' at character " + prefixIndex);
}
expressions.add(doParseExpression(expr, context));
@ -156,18 +147,13 @@ public abstract class TemplateAwareExpressionParser implements ExpressionParser
}
else {
// no more ${expressions} found in string, add rest as static text
expressions.add(createLiteralExpression(context,
expressionString.substring(startIdx)));
expressions.add(new LiteralExpression(expressionString.substring(startIdx)));
startIdx = expressionString.length();
}
}
return expressions.toArray(new Expression[expressions.size()]);
}
private Expression createLiteralExpression(ParserContext context, String text) {
return new LiteralExpression(text);
}
/**
* Return true if the specified suffix can be found at the supplied position in the
* supplied expression string.
@ -192,15 +178,15 @@ public abstract class TemplateAwareExpressionParser implements ExpressionParser
/**
* Copes with nesting, for example '${...${...}}' where the correct end for the first
* ${ is the final }.
* @param prefix the prefix
* @param suffix the suffix
* @param expressionString the expression string
* @param afterPrefixIndex the most recently found prefix location for which the
* matching end suffix is being sought
* matching end suffix is being sought
* @return the position of the correct matching nextSuffix or -1 if none can be found
*/
private int skipToCorrectEndSuffix(String prefix, String suffix,
String expressionString, int afterPrefixIndex) throws ParseException {
private int skipToCorrectEndSuffix(String suffix, String expressionString, int afterPrefixIndex)
throws ParseException {
// Chew on the expression text - relying on the rules:
// brackets must be in pairs: () [] {}
// string literals are "..." or '...' and these may contain unmatched brackets
@ -226,16 +212,15 @@ public abstract class TemplateAwareExpressionParser implements ExpressionParser
case ']':
case ')':
if (stack.isEmpty()) {
throw new ParseException(expressionString, pos, "Found closing '"
+ ch + "' at position " + pos + " without an opening '"
+ Bracket.theOpenBracketFor(ch) + "'");
throw new ParseException(expressionString, pos, "Found closing '" + ch +
"' at position " + pos + " without an opening '" +
Bracket.theOpenBracketFor(ch) + "'");
}
Bracket p = stack.pop();
if (!p.compatibleWithCloseBracket(ch)) {
throw new ParseException(expressionString, pos, "Found closing '"
+ ch + "' at position " + pos
+ " but most recent opening is '" + p.bracket
+ "' at position " + p.pos);
throw new ParseException(expressionString, pos, "Found closing '" + ch +
"' at position " + pos + " but most recent opening is '" + p.bracket +
"' at position " + p.pos);
}
break;
case '\'':
@ -244,8 +229,7 @@ public abstract class TemplateAwareExpressionParser implements ExpressionParser
int endLiteral = expressionString.indexOf(ch, pos + 1);
if (endLiteral == -1) {
throw new ParseException(expressionString, pos,
"Found non terminating string literal starting at position "
+ pos);
"Found non terminating string literal starting at position " + pos);
}
pos = endLiteral;
break;
@ -254,9 +238,8 @@ public abstract class TemplateAwareExpressionParser implements ExpressionParser
}
if (!stack.isEmpty()) {
Bracket p = stack.pop();
throw new ParseException(expressionString, p.pos, "Missing closing '"
+ Bracket.theCloseBracketFor(p.bracket) + "' for '" + p.bracket
+ "' at position " + p.pos);
throw new ParseException(expressionString, p.pos, "Missing closing '" +
Bracket.theCloseBracketFor(p.bracket) + "' for '" + p.bracket + "' at position " + p.pos);
}
if (!isSuffixHere(expressionString, pos, suffix)) {
return -1;
@ -265,6 +248,17 @@ public abstract class TemplateAwareExpressionParser implements ExpressionParser
}
/**
* Actually parse the expression string and return an Expression object.
* @param expressionString the raw expression string to parse
* @param context a context for influencing this expression parsing routine (optional)
* @return an evaluator for the parsed expression
* @throws ParseException an exception occurred during parsing
*/
protected abstract Expression doParseExpression(String expressionString, ParserContext context)
throws ParseException;
/**
* This captures a type of bracket and the position in which it occurs in the
* expression. The positional information is used if an error has to be reported
@ -313,14 +307,4 @@ public abstract class TemplateAwareExpressionParser implements ExpressionParser
}
}
/**
* Actually parse the expression string and return an Expression object.
* @param expressionString the raw expression string to parse
* @param context a context for influencing this expression parsing routine (optional)
* @return an evaluator for the parsed expression
* @throws ParseException an exception occurred during parsing
*/
protected abstract Expression doParseExpression(String expressionString,
ParserContext context) throws ParseException;
}

View File

@ -143,7 +143,7 @@ public abstract class AbstractNamedValueMethodArgumentResolver implements Handle
*/
private NamedValueInfo updateNamedValueInfo(MethodParameter parameter, NamedValueInfo info) {
String name = info.name;
if (info.name.length() == 0) {
if (info.name.isEmpty()) {
name = parameter.getParameterName();
if (name == null) {
throw new IllegalArgumentException("Name for argument type [" + parameter.getParameterType().getName() +

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -161,7 +161,7 @@ public abstract class AbstractNamedValueMethodArgumentResolver implements Handle
*/
private NamedValueInfo updateNamedValueInfo(MethodParameter parameter, NamedValueInfo info) {
String name = info.name;
if (info.name.length() == 0) {
if (info.name.isEmpty()) {
name = parameter.getParameterName();
if (name == null) {
throw new IllegalArgumentException(

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -116,7 +116,7 @@ public class CommonsMultipartResolverTests {
}
private void doTestParameters(MultipartHttpServletRequest request) {
Set<String> parameterNames = new HashSet<String>();
Set<String> parameterNames = new HashSet<>();
Enumeration<String> parameterEnum = request.getParameterNames();
while (parameterEnum.hasMoreElements()) {
parameterNames.add(parameterEnum.nextElement());
@ -137,8 +137,8 @@ public class CommonsMultipartResolverTests {
assertEquals("value4", request.getParameter("field4"));
assertEquals("getValue", request.getParameter("getField"));
List<String> parameterMapKeys = new ArrayList<String>();
List<Object> parameterMapValues = new ArrayList<Object>();
List<String> parameterMapKeys = new ArrayList<>();
List<Object> parameterMapValues = new ArrayList<>();
for (Object o : request.getParameterMap().keySet()) {
String key = (String) o;
parameterMapKeys.add(key);
@ -165,7 +165,7 @@ public class CommonsMultipartResolverTests {
}
private void doTestFiles(MultipartHttpServletRequest request) throws IOException {
Set<String> fileNames = new HashSet<String>();
Set<String> fileNames = new HashSet<>();
Iterator<String> fileIter = request.getFileNames();
while (fileIter.hasNext()) {
fileNames.add(fileIter.next());
@ -258,13 +258,13 @@ public class CommonsMultipartResolverTests {
binder.setBindEmptyMultipartFiles(false);
String firstBound = mtb2.getField2();
binder.bind(request);
assertTrue(mtb2.getField2().length() > 0);
assertFalse(mtb2.getField2().isEmpty());
assertEquals(firstBound, mtb2.getField2());
request = resolver.resolveMultipart(originalRequest);
binder.setBindEmptyMultipartFiles(true);
binder.bind(request);
assertTrue(mtb2.getField2().length() == 0);
assertTrue(mtb2.getField2().isEmpty());
}
@Test
@ -284,7 +284,7 @@ public class CommonsMultipartResolverTests {
final MultipartFilter filter = new MultipartFilter();
filter.init(filterConfig);
final List<MultipartFile> files = new ArrayList<MultipartFile>();
final List<MultipartFile> files = new ArrayList<>();
final FilterChain filterChain = new FilterChain() {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) {
@ -322,7 +322,7 @@ public class CommonsMultipartResolverTests {
MockFilterConfig filterConfig = new MockFilterConfig(wac.getServletContext(), "filter");
filterConfig.addInitParameter("multipartResolverBeanName", "myMultipartResolver");
final List<MultipartFile> files = new ArrayList<MultipartFile>();
final List<MultipartFile> files = new ArrayList<>();
FilterChain filterChain = new FilterChain() {
@Override
public void doFilter(ServletRequest originalRequest, ServletResponse response) {
@ -377,7 +377,7 @@ public class CommonsMultipartResolverTests {
if (request instanceof MultipartHttpServletRequest) {
throw new IllegalStateException("Already a multipart request");
}
List<FileItem> fileItems = new ArrayList<FileItem>();
List<FileItem> fileItems = new ArrayList<>();
MockFileItem fileItem1 = new MockFileItem(
"field1", "type1", empty ? "" : "field1.txt", empty ? "" : "text1");
MockFileItem fileItem1x = new MockFileItem(

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -159,7 +159,7 @@ public class RequestPartMethodArgumentResolver extends AbstractMessageConverterM
private String getPartName(MethodParameter methodParam, RequestPart requestPart) {
String partName = (requestPart != null ? requestPart.name() : "");
if (partName.length() == 0) {
if (partName.isEmpty()) {
partName = methodParam.getParameterName();
if (partName == null) {
throw new IllegalArgumentException("Request part name for argument type [" +

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -25,6 +25,7 @@ import java.util.Set;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.util.StringUtils;
/**
* A specialization of {@link ResponseBodyEmitter} for sending
@ -234,7 +235,7 @@ public class SseEmitter extends ResponseBodyEmitter {
@Override
public Set<DataWithMediaType> build() {
if ((this.sb == null || this.sb.length() == 0) && this.dataToSend.isEmpty()) {
if (!StringUtils.hasLength(this.sb) && this.dataToSend.isEmpty()) {
return Collections.<DataWithMediaType>emptySet();
}
append("\n");