Skip to content

Commit

Permalink
Cleanup java sources
Browse files Browse the repository at this point in the history
1. use `StandardCharsets.UTF_8` where feasible
2. use `.isEmpty()` where feasible
3. remove unnecessary `static` modifier of inner record or interface type
4. remove unnecessary `final` modifier of private or static method
5. remove unnecessary `toString()`
  • Loading branch information
quaff committed Dec 12, 2023
1 parent 0fe7d78 commit 1af5669
Show file tree
Hide file tree
Showing 50 changed files with 66 additions and 69 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ void checkArchitecture() throws IOException {
if (!violations.isEmpty()) {
StringBuilder report = new StringBuilder();
for (EvaluationResult violation : violations) {
report.append(violation.getFailureReport().toString());
report.append(violation.getFailureReport());
report.append(String.format("%n"));
}
Files.writeString(outputFile.toPath(), report.toString(), StandardOpenOption.CREATE,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ private Provider<AutoConfigurationImports> autoConfigurationImports(Project proj
});
}

private static record AutoConfigurationImports(Path importsFile, List<String> imports) {
private record AutoConfigurationImports(Path importsFile, List<String> imports) {

}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ private void addClassifiedManagedDependencies(Node dependencyManagement) {
.collect(Collectors.toSet());
Node target = dependency;
for (String classifier : classifiers) {
if (classifier.length() > 0) {
if (!classifier.isEmpty()) {
if (target == null) {
target = new Node(null, "dependency");
target.appendNode("groupId", groupId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ private URI normalize(URI uri) {
if ("/".equals(uri.getPath())) {
return uri;
}
return URI.create(uri.toString() + "/");
return URI.create(uri + "/");
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ static class TestPathMatcher implements PathMapper {
@Override
public String getRootPath(EndpointId endpointId) {
if (endpointId.toString().endsWith("one")) {
return "1/" + endpointId.toString();
return "1/" + endpointId;
}
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -234,9 +234,8 @@ private void assertNoDuplicateOperations(EndpointBean endpointBean, MultiValueMa
String extensionBeanNames = extensions.stream()
.map(ExtensionBean::getBeanName)
.collect(Collectors.joining(", "));
throw new IllegalStateException("Unable to map duplicate endpoint operations: " + duplicates.toString()
+ " to " + endpointBean.getBeanName()
+ (extensions.isEmpty() ? "" : " (" + extensionBeanNames + ")"));
throw new IllegalStateException("Unable to map duplicate endpoint operations: " + duplicates + " to "
+ endpointBean.getBeanName() + (extensions.isEmpty() ? "" : " (" + extensionBeanNames + ")"));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ private Object getContributor(String[] path, int pathOffset) {
private String getName(String[] path, int pathOffset) {
StringBuilder name = new StringBuilder();
while (pathOffset < path.length) {
name.append((name.length() != 0) ? "/" : "");
name.append((!name.isEmpty()) ? "/" : "");
name.append(path[pathOffset]);
pathOffset++;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,7 @@ private String createOnBeanNoMatchReason(MatchResult matchResult) {

private void appendMessageForNoMatches(StringBuilder reason, Collection<String> unmatched, String description) {
if (!unmatched.isEmpty()) {
if (reason.length() > 0) {
if (!reason.isEmpty()) {
reason.append(" and ");
}
reason.append("did not find any beans ");
Expand All @@ -347,7 +347,7 @@ private String createOnMissingBeanNoMatchReason(MatchResult matchResult) {
appendMessageForMatches(reason, matchResult.getMatchedAnnotations(), "annotated with");
appendMessageForMatches(reason, matchResult.getMatchedTypes(), "of type");
if (!matchResult.getMatchedNames().isEmpty()) {
if (reason.length() > 0) {
if (!reason.isEmpty()) {
reason.append(" and ");
}
reason.append("found beans named ");
Expand All @@ -360,7 +360,7 @@ private void appendMessageForMatches(StringBuilder reason, Map<String, Collectio
String description) {
if (!matches.isEmpty()) {
matches.forEach((key, value) -> {
if (reason.length() > 0) {
if (!reason.isEmpty()) {
reason.append(" and ");
}
reason.append("found beans ");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ protected File getHomeDirectory() {
}

@SafeVarargs
private final File getHomeDirectory(Supplier<String>... pathSuppliers) {
private File getHomeDirectory(Supplier<String>... pathSuppliers) {
for (Supplier<String> pathSupplier : pathSuppliers) {
String path = pathSupplier.get();
if (StringUtils.hasText(path)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
Expand Down Expand Up @@ -159,7 +160,7 @@ private static List<URL> getUrlsFromManifestClassPathAttribute(URL jarUrl, JarFi
urls.add(referenced);
}
else {
referenced = new URL(jarUrl, URLDecoder.decode(entry, "UTF-8"));
referenced = new URL(jarUrl, URLDecoder.decode(entry, StandardCharsets.UTF_8));
if (new File(referenced.getFile()).exists()) {
urls.add(referenced);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ private Object invokeApplicationContextMethod(Method method, Object[] args) thro

private ApplicationContext getStartedApplicationContext() {
if (this.startupFailure != null) {
throw new IllegalStateException(toString() + " failed to start", this.startupFailure);
throw new IllegalStateException(this + " failed to start", this.startupFailure);
}
return this.applicationContext;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -956,7 +956,7 @@ private RequestEntity<?> createRequestEntityWithRootAppliedUri(RequestEntity<?>
private URI applyRootUriIfNecessary(URI uri) {
UriTemplateHandler uriTemplateHandler = this.restTemplate.getUriTemplateHandler();
if ((uriTemplateHandler instanceof RootUriTemplateHandler rootHandler) && uri.toString().startsWith("/")) {
return URI.create(rootHandler.getRootUri() + uri.toString());
return URI.create(rootHandler.getRootUri() + uri);
}
return uri;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ void parseMapShouldReturnContent() throws Exception {
assertThat(tester.parse(MAP_JSON)).asMap().containsEntry("a", OBJECT);
}

protected static final ExampleObject createExampleObject(String name, int age) {
protected static ExampleObject createExampleObject(String name, int age) {
ExampleObject exampleObject = new ExampleObject();
exampleObject.setName(name);
exampleObject.setAge(age);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

import jakarta.servlet.ServletContext;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -80,7 +81,7 @@ protected String getResourceLocation(String path) {
};
URL resource = context.getResource("/");
assertThat(resource).isNotNull();
File file = new File(URLDecoder.decode(resource.getPath(), "UTF-8"));
File file = new File(URLDecoder.decode(resource.getPath(), StandardCharsets.UTF_8));
assertThat(file).exists().isDirectory();
String[] contents = file.list((dir, name) -> !(".".equals(name) || "..".equals(name)));
assertThat(contents).isNotNull();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,7 @@ List<ContainerConnectionSource<?>> getSources() {
* Relevant details from {@link ContainerConnectionSource} used as a
* MergedContextConfiguration cache key.
*/
private static record CacheKey(String connectionName, Set<Class<?>> connectionDetailsTypes,
Container<?> container) {
private record CacheKey(String connectionName, Set<Class<?>> connectionDetailsTypes, Container<?> container) {

CacheKey(ContainerConnectionSource<?> source) {
this(source.getConnectionName(), source.getConnectionDetailsTypes(), source.getContainerSupplier().get());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ interface ContainerDefinitions {
}

@Retention(RetentionPolicy.RUNTIME)
static @interface ContainerAnnotation {
@interface ContainerAnnotation {

}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ RedisContainer redisContainer(DynamicPropertyRegistry properties) {
}

@ConfigurationProperties("container")
static record ContainerProperties(int port) {
record ContainerProperties(int port) {
}

static class TestBean {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,7 @@ private String toCommaDelimitedString(List<Object> list) {
}
StringBuilder result = new StringBuilder();
for (Object item : list) {
result.append((result.length() != 0) ? "," : "");
result.append((!result.isEmpty()) ? "," : "");
result.append(item);
}
return result.toString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ public JSONStringer endObject() throws JSONException {
* @throws JSONException if processing of json failed
*/
JSONStringer open(Scope empty, String openBracket) throws JSONException {
if (this.stack.isEmpty() && this.out.length() > 0) {
if (this.stack.isEmpty() && !this.out.isEmpty()) {
throw new JSONException("Nesting problem: multiple top-level roots");
}
beforeValue();
Expand Down Expand Up @@ -423,7 +423,7 @@ else if (context != Scope.NULL) {
*/
@Override
public String toString() {
return this.out.length() == 0 ? null : this.out.toString();
return this.out.isEmpty() ? null : this.out.toString();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ private String buildName(String prefix, String name) {
fullName.append(prefix);
}
if (name != null) {
if (fullName.length() > 0) {
if (!fullName.isEmpty()) {
fullName.append('.');
}
fullName.append(ConfigurationMetadata.toDashedCase(name));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
*/
class TestPrintStream extends PrintStream implements AssertProvider<PrintStreamAssert> {

private final Class<? extends Object> testClass;
private final Class<?> testClass;

TestPrintStream(Object testInstance) {
super(new ByteArrayOutputStream());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
Expand Down Expand Up @@ -227,7 +228,7 @@ private InputStream getResource(String config) throws Exception {

private String handleUrl(String path) throws UnsupportedEncodingException {
if (path.startsWith("jar:file:") || path.startsWith("file:")) {
path = URLDecoder.decode(path, "UTF-8");
path = URLDecoder.decode(path, StandardCharsets.UTF_8);
if (path.startsWith("file:")) {
path = path.substring("file:".length());
if (path.startsWith("//")) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.net.URLStreamHandler;
import java.nio.charset.StandardCharsets;
import java.security.Permission;

/**
Expand Down Expand Up @@ -318,13 +318,8 @@ private void write(String source, ByteArrayOutputStream outputStream) {
for (int i = 0; i < length; i++) {
int c = source.charAt(i);
if (c > 127) {
try {
String encoded = URLEncoder.encode(String.valueOf((char) c), "UTF-8");
write(encoded, outputStream);
}
catch (UnsupportedEncodingException ex) {
throw new IllegalStateException(ex);
}
String encoded = URLEncoder.encode(String.valueOf((char) c), StandardCharsets.UTF_8);
write(encoded, outputStream);
}
else {
if (c == '%') {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
}

boolean hasReportedErrors() {
return this.message.length() > 0;
return !this.message.isEmpty();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,7 @@ private void addClasspath(List<String> args) throws MojoExecutionException {
try {
StringBuilder classpath = new StringBuilder();
for (URL ele : getClassPathUrls()) {
if (classpath.length() > 0) {
if (!classpath.isEmpty()) {
classpath.append(File.pathSeparator);
}
classpath.append(new File(ele.toURI()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ static class ClasspathBuilder {
static String build(List<URL> classpathElements) {
StringBuilder classpath = new StringBuilder();
for (URL element : classpathElements) {
if (classpath.length() > 0) {
if (!classpath.isEmpty()) {
classpath.append(File.pathSeparator);
}
classpath.append(toFile(element));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ private void appendContext(StringBuilder message) {
}
append(context, "started by ", () -> System.getProperty("user.name"));
append(context, "in ", () -> System.getProperty("user.dir"));
if (context.length() > 0) {
if (!context.isEmpty()) {
message.append(" (");
message.append(context);
message.append(")");
Expand All @@ -140,7 +140,7 @@ private void append(StringBuilder message, String prefix, Callable<Object> call,
value = defaultValue;
}
if (StringUtils.hasLength(value)) {
message.append((message.length() > 0) ? " " : "");
message.append((!message.isEmpty()) ? " " : "");
message.append(prefix);
message.append(value);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public static String toDashedForm(String name) {
}
else {
ch = (ch != '_') ? ch : '-';
if (Character.isUpperCase(ch) && result.length() > 0 && result.charAt(result.length() - 1) != '-') {
if (Character.isUpperCase(ch) && !result.isEmpty() && result.charAt(result.length() - 1) != '-') {
result.append('-');
}
result.append(Character.toLowerCase(ch));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ private boolean isScalarValue(ConfigurationPropertySource source, ConfigurationP
private String getKeyName(ConfigurationPropertyName name) {
StringBuilder result = new StringBuilder();
for (int i = this.root.getNumberOfElements(); i < name.getNumberOfElements(); i++) {
if (result.length() != 0) {
if (!result.isEmpty()) {
result.append('.');
}
result.append(name.getElement(i, Form.ORIGINAL));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -543,7 +543,7 @@ private String buildToString() {
StringBuilder result = new StringBuilder(elements * 8);
for (int i = 0; i < elements; i++) {
boolean indexed = isIndexed(i);
if (result.length() > 0 && !indexed) {
if (!result.isEmpty() && !indexed) {
result.append('.');
}
if (indexed) {
Expand Down Expand Up @@ -615,7 +615,7 @@ private static Elements elementsOf(CharSequence name, boolean returnNullIfInvali
Assert.isTrue(returnNullIfInvalid, "Name must not be null");
return null;
}
if (name.length() == 0) {
if (name.isEmpty()) {
return Elements.EMPTY;
}
if (name.charAt(0) == '.' || name.charAt(name.length() - 1) == '.') {
Expand Down Expand Up @@ -674,7 +674,7 @@ public static ConfigurationPropertyName adapt(CharSequence name, char separator)
static ConfigurationPropertyName adapt(CharSequence name, char separator,
Function<CharSequence, CharSequence> elementValueProcessor) {
Assert.notNull(name, "Name must not be null");
if (name.length() == 0) {
if (name.isEmpty()) {
return EMPTY;
}
Elements elements = new ElementsParser(name, separator).parse(elementValueProcessor);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ private String convertName(ConfigurationPropertyName name) {
private String convertName(ConfigurationPropertyName name, int numberOfElements) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < numberOfElements; i++) {
if (result.length() > 0) {
if (!result.isEmpty()) {
result.append('_');
}
result.append(name.getElement(i, Form.UNIFORM).toUpperCase(Locale.ENGLISH));
Expand All @@ -68,7 +68,7 @@ private String convertName(ConfigurationPropertyName name, int numberOfElements)
private String convertLegacyName(ConfigurationPropertyName name) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < name.getNumberOfElements(); i++) {
if (result.length() > 0) {
if (!result.isEmpty()) {
result.append('_');
}
result.append(convertLegacyNameElement(name.getElement(i, Form.ORIGINAL)));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ else if (current == '\\') {
}
index++;
}
if (build.length() > 0) {
if (!build.isEmpty()) {
list.add(build.toString().trim());
}
return list;
Expand Down
Loading

0 comments on commit 1af5669

Please sign in to comment.