From 1db42081e59194e7bbb9997a60ec0d7a2aa0a506 Mon Sep 17 00:00:00 2001 From: stonio Date: Tue, 21 Feb 2017 16:23:40 +0100 Subject: [PATCH] Use String#isEmpty() Closes gh-1335 (cherry picked from commit 7d062df) --- .../beans/PropertyMatches.java | 6 +- .../support/StringToCharacterConverter.java | 4 +- .../support/StringToEnumConverterFactory.java | 4 +- .../StringToNumberConverterFactory.java | 4 +- .../PathMatchingResourcePatternResolver.java | 4 +- .../org/springframework/util/Base64Utils.java | 4 +- .../springframework/util/MimeTypeUtils.java | 2 +- .../org/springframework/util/StringUtils.java | 32 +++--- .../util/xml/AbstractStaxHandler.java | 6 +- .../common/TemplateAwareExpressionParser.java | 102 ++++++++---------- ...tractNamedValueMethodArgumentResolver.java | 2 +- ...tractNamedValueMethodArgumentResolver.java | 4 +- .../CommonsMultipartResolverTests.java | 20 ++-- .../RequestPartMethodArgumentResolver.java | 4 +- .../mvc/method/annotation/SseEmitter.java | 5 +- 15 files changed, 93 insertions(+), 110 deletions(-) diff --git a/spring-beans/src/main/java/org/springframework/beans/PropertyMatches.java b/spring-beans/src/main/java/org/springframework/beans/PropertyMatches.java index 87ccf2a95c..f0d607a1cd 100644 --- a/spring-beans/src/main/java/org/springframework/beans/PropertyMatches.java +++ b/spring-beans/src/main/java/org/springframework/beans/PropertyMatches.java @@ -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]; diff --git a/spring-core/src/main/java/org/springframework/core/convert/support/StringToCharacterConverter.java b/spring-core/src/main/java/org/springframework/core/convert/support/StringToCharacterConverter.java index 7a076d335c..5a8fd3c2bf 100644 --- a/spring-core/src/main/java/org/springframework/core/convert/support/StringToCharacterConverter.java +++ b/spring-core/src/main/java/org/springframework/core/convert/support/StringToCharacterConverter.java @@ -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 { @Override public Character convert(String source) { - if (source.length() == 0) { + if (source.isEmpty()) { return null; } if (source.length() > 1) { diff --git a/spring-core/src/main/java/org/springframework/core/convert/support/StringToEnumConverterFactory.java b/spring-core/src/main/java/org/springframework/core/convert/support/StringToEnumConverterFactory.java index 865d1e83a3..aa4ad50d04 100644 --- a/spring-core/src/main/java/org/springframework/core/convert/support/StringToEnumConverterFactory.java +++ b/spring-core/src/main/java/org/springframework/core/convert/support/StringToEnumConverterFactory.java @@ -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= 0 ? mimeType.substring(0, index) : mimeType).trim(); - if (fullType.length() == 0) { + if (fullType.isEmpty()) { throw new InvalidMimeTypeException(mimeType, "'mimeType' must not be empty"); } diff --git a/spring-core/src/main/java/org/springframework/util/StringUtils.java b/spring-core/src/main/java/org/springframework/util/StringUtils.java index 49f49a9395..7f9b901bfa 100644 --- a/spring-core/src/main/java/org/springframework/util/StringUtils.java +++ b/spring-core/src/main/java/org/springframework/util/StringUtils.java @@ -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); } /** diff --git a/spring-core/src/main/java/org/springframework/util/xml/AbstractStaxHandler.java b/spring-core/src/main/java/org/springframework/util/xml/AbstractStaxHandler.java index afbdf9a03b..e42948438f 100644 --- a/spring-core/src/main/java/org/springframework/util/xml/AbstractStaxHandler.java +++ b/spring-core/src/main/java/org/springframework/util/xml/AbstractStaxHandler.java @@ -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()); } diff --git a/spring-expression/src/main/java/org/springframework/expression/common/TemplateAwareExpressionParser.java b/spring-expression/src/main/java/org/springframework/expression/common/TemplateAwareExpressionParser.java index 1bfd482dd4..1eb6e89df3 100644 --- a/spring-expression/src/main/java/org/springframework/expression/common/TemplateAwareExpressionParser.java +++ b/spring-expression/src/main/java/org/springframework/expression/common/TemplateAwareExpressionParser.java @@ -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 expressions = new LinkedList(); 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; - } diff --git a/spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/support/AbstractNamedValueMethodArgumentResolver.java b/spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/support/AbstractNamedValueMethodArgumentResolver.java index b456646389..931fe06c74 100644 --- a/spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/support/AbstractNamedValueMethodArgumentResolver.java +++ b/spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/support/AbstractNamedValueMethodArgumentResolver.java @@ -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() + diff --git a/spring-web/src/main/java/org/springframework/web/method/annotation/AbstractNamedValueMethodArgumentResolver.java b/spring-web/src/main/java/org/springframework/web/method/annotation/AbstractNamedValueMethodArgumentResolver.java index 1fbe03dd1f..9e8c32ec2a 100644 --- a/spring-web/src/main/java/org/springframework/web/method/annotation/AbstractNamedValueMethodArgumentResolver.java +++ b/spring-web/src/main/java/org/springframework/web/method/annotation/AbstractNamedValueMethodArgumentResolver.java @@ -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( diff --git a/spring-web/src/test/java/org/springframework/web/multipart/commons/CommonsMultipartResolverTests.java b/spring-web/src/test/java/org/springframework/web/multipart/commons/CommonsMultipartResolverTests.java index e0c963df8d..ebad85d5cb 100644 --- a/spring-web/src/test/java/org/springframework/web/multipart/commons/CommonsMultipartResolverTests.java +++ b/spring-web/src/test/java/org/springframework/web/multipart/commons/CommonsMultipartResolverTests.java @@ -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 parameterNames = new HashSet(); + Set parameterNames = new HashSet<>(); Enumeration 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 parameterMapKeys = new ArrayList(); - List parameterMapValues = new ArrayList(); + List parameterMapKeys = new ArrayList<>(); + List 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 fileNames = new HashSet(); + Set fileNames = new HashSet<>(); Iterator 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 files = new ArrayList(); + final List 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 files = new ArrayList(); + final List 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 fileItems = new ArrayList(); + List fileItems = new ArrayList<>(); MockFileItem fileItem1 = new MockFileItem( "field1", "type1", empty ? "" : "field1.txt", empty ? "" : "text1"); MockFileItem fileItem1x = new MockFileItem( diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartMethodArgumentResolver.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartMethodArgumentResolver.java index a46d3a99f3..bddd91907d 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartMethodArgumentResolver.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartMethodArgumentResolver.java @@ -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 [" + diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/SseEmitter.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/SseEmitter.java index 72b283f06a..f2594cf1fe 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/SseEmitter.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/SseEmitter.java @@ -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 build() { - if ((this.sb == null || this.sb.length() == 0) && this.dataToSend.isEmpty()) { + if (!StringUtils.hasLength(this.sb) && this.dataToSend.isEmpty()) { return Collections.emptySet(); } append("\n");