Browse Source

Use Files.writeString() and Files.readString() where possible

See gh-31459
pull/31462/head
dreis2211 4 years ago committed by Stephane Nicoll
parent
commit
fb45fc4819
  1. 10
      buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/UpgradeApplicator.java
  2. 2
      buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/MavenPluginPlugin.java
  3. 11
      buildSrc/src/test/java/org/springframework/boot/build/bom/bomr/UpgradeApplicatorTests.java
  4. 8
      spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/ssl/CertificateParser.java
  5. 8
      spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/ssl/PrivateKeyParser.java
  6. 7
      spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/ResolveMainClassName.java
  7. 11
      spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoIntegrationTests.java
  8. 18
      spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveTests.java
  9. 20
      spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/MavenBuild.java

10
buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/UpgradeApplicator.java

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2021 the original author or authors. * Copyright 2012-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -17,7 +17,6 @@
package org.springframework.boot.build.bom.bomr; package org.springframework.boot.build.bom.bomr;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.StandardOpenOption; import java.nio.file.StandardOpenOption;
@ -42,7 +41,7 @@ class UpgradeApplicator {
} }
Path apply(Upgrade upgrade) throws IOException { Path apply(Upgrade upgrade) throws IOException {
String buildFileContents = new String(Files.readAllBytes(this.buildFile), StandardCharsets.UTF_8); String buildFileContents = Files.readString(this.buildFile);
Matcher matcher = Pattern.compile("library\\(\"" + upgrade.getLibrary().getName() + "\", \"(.+)\"\\)") Matcher matcher = Pattern.compile("library\\(\"" + upgrade.getLibrary().getName() + "\", \"(.+)\"\\)")
.matcher(buildFileContents); .matcher(buildFileContents);
if (!matcher.find()) { if (!matcher.find()) {
@ -68,7 +67,7 @@ class UpgradeApplicator {
private void updateGradleProperties(Upgrade upgrade, String version) throws IOException { private void updateGradleProperties(Upgrade upgrade, String version) throws IOException {
String property = version.substring(2, version.length() - 1); String property = version.substring(2, version.length() - 1);
String gradlePropertiesContents = new String(Files.readAllBytes(this.gradleProperties), StandardCharsets.UTF_8); String gradlePropertiesContents = Files.readString(this.gradleProperties);
String modified = gradlePropertiesContents.replace( String modified = gradlePropertiesContents.replace(
property + "=" + upgrade.getLibrary().getVersion().getVersion(), property + "=" + upgrade.getVersion()); property + "=" + upgrade.getLibrary().getVersion().getVersion(), property + "=" + upgrade.getVersion());
overwrite(this.gradleProperties, modified); overwrite(this.gradleProperties, modified);
@ -82,8 +81,7 @@ class UpgradeApplicator {
} }
private void overwrite(Path target, String content) throws IOException { private void overwrite(Path target, String content) throws IOException {
Files.write(target, content.getBytes(StandardCharsets.UTF_8), StandardOpenOption.WRITE, Files.writeString(target, content, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
StandardOpenOption.TRUNCATE_EXISTING);
} }
} }

2
buildSrc/src/main/java/org/springframework/boot/build/mavenplugin/MavenPluginPlugin.java

@ -309,7 +309,7 @@ public class MavenPluginPlugin implements Plugin<Project> {
Path outputLocation = this.outputDir.toPath().resolve(relativePath); Path outputLocation = this.outputDir.toPath().resolve(relativePath);
try { try {
Files.createDirectories(outputLocation.getParent()); Files.createDirectories(outputLocation.getParent());
Files.write(outputLocation, edit.getFormattedContent().getBytes(StandardCharsets.UTF_8)); Files.writeString(outputLocation, edit.getFormattedContent());
} }
catch (Exception ex) { catch (Exception ex) {
throw new TaskExecutionException(this, ex); throw new TaskExecutionException(this, ex);

11
buildSrc/src/test/java/org/springframework/boot/build/bom/bomr/UpgradeApplicatorTests.java

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2021 the original author or authors. * Copyright 2012-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -20,7 +20,6 @@ import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.util.Properties; import java.util.Properties;
@ -49,13 +48,13 @@ class UpgradeApplicatorTests {
void whenUpgradeIsAppliedToLibraryWithVersionThenBomIsUpdated() throws IOException { void whenUpgradeIsAppliedToLibraryWithVersionThenBomIsUpdated() throws IOException {
File bom = new File(this.temp, "bom.gradle"); File bom = new File(this.temp, "bom.gradle");
FileCopyUtils.copy(new File("src/test/resources/bom.gradle"), bom); FileCopyUtils.copy(new File("src/test/resources/bom.gradle"), bom);
String originalContents = new String(Files.readAllBytes(bom.toPath()), StandardCharsets.UTF_8); String originalContents = Files.readString(bom.toPath());
File gradleProperties = new File(this.temp, "gradle.properties"); File gradleProperties = new File(this.temp, "gradle.properties");
FileCopyUtils.copy(new File("src/test/resources/gradle.properties"), gradleProperties); FileCopyUtils.copy(new File("src/test/resources/gradle.properties"), gradleProperties);
new UpgradeApplicator(bom.toPath(), gradleProperties.toPath()).apply(new Upgrade( new UpgradeApplicator(bom.toPath(), gradleProperties.toPath()).apply(new Upgrade(
new Library("ActiveMQ", new LibraryVersion(DependencyVersion.parse("5.15.11"), null), null, null, null), new Library("ActiveMQ", new LibraryVersion(DependencyVersion.parse("5.15.11"), null), null, null, null),
DependencyVersion.parse("5.16"))); DependencyVersion.parse("5.16")));
String bomContents = new String(Files.readAllBytes(bom.toPath()), StandardCharsets.UTF_8); String bomContents = Files.readString(bom.toPath());
assertThat(bomContents.length()).isEqualTo(originalContents.length() - 3); assertThat(bomContents.length()).isEqualTo(originalContents.length() - 3);
} }
@ -63,13 +62,13 @@ class UpgradeApplicatorTests {
void whenUpgradeIsAppliedToLibraryWithAlignedVersionThenBomIsUpdated() throws IOException { void whenUpgradeIsAppliedToLibraryWithAlignedVersionThenBomIsUpdated() throws IOException {
File bom = new File(this.temp, "bom.gradle"); File bom = new File(this.temp, "bom.gradle");
FileCopyUtils.copy(new File("src/test/resources/bom.gradle"), bom); FileCopyUtils.copy(new File("src/test/resources/bom.gradle"), bom);
String originalContents = new String(Files.readAllBytes(bom.toPath()), StandardCharsets.UTF_8); String originalContents = Files.readString(bom.toPath());
File gradleProperties = new File(this.temp, "gradle.properties"); File gradleProperties = new File(this.temp, "gradle.properties");
FileCopyUtils.copy(new File("src/test/resources/gradle.properties"), gradleProperties); FileCopyUtils.copy(new File("src/test/resources/gradle.properties"), gradleProperties);
new UpgradeApplicator(bom.toPath(), gradleProperties.toPath()).apply( new UpgradeApplicator(bom.toPath(), gradleProperties.toPath()).apply(
new Upgrade(new Library("OAuth2 OIDC SDK", new LibraryVersion(DependencyVersion.parse("8.36.1"), null), new Upgrade(new Library("OAuth2 OIDC SDK", new LibraryVersion(DependencyVersion.parse("8.36.1"), null),
null, null, null), DependencyVersion.parse("8.36.2"))); null, null, null), DependencyVersion.parse("8.36.2")));
String bomContents = new String(Files.readAllBytes(bom.toPath()), StandardCharsets.UTF_8); String bomContents = Files.readString(bom.toPath());
assertThat(bomContents.length()).isEqualTo(originalContents.length()); assertThat(bomContents.length()).isEqualTo(originalContents.length());
assertThat(bomContents).contains("version(\"8.36.2\")"); assertThat(bomContents).contains("version(\"8.36.2\")");
} }

8
spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/ssl/CertificateParser.java

@ -18,7 +18,6 @@ package org.springframework.boot.buildpack.platform.docker.ssl;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
@ -76,7 +75,7 @@ final class CertificateParser {
private static void readCertificates(Path path, CertificateFactory factory, Consumer<X509Certificate> consumer) { private static void readCertificates(Path path, CertificateFactory factory, Consumer<X509Certificate> consumer) {
try { try {
String text = readText(path); String text = Files.readString(path);
Matcher matcher = PATTERN.matcher(text); Matcher matcher = PATTERN.matcher(text);
while (matcher.find()) { while (matcher.find()) {
String encodedText = matcher.group(1); String encodedText = matcher.group(1);
@ -92,11 +91,6 @@ final class CertificateParser {
} }
} }
private static String readText(Path path) throws IOException {
byte[] bytes = Files.readAllBytes(path);
return new String(bytes, StandardCharsets.UTF_8);
}
private static byte[] decodeBase64(String content) { private static byte[] decodeBase64(String content) {
byte[] bytes = content.replaceAll("\r", "").replaceAll("\n", "").getBytes(); byte[] bytes = content.replaceAll("\r", "").replaceAll("\n", "").getBytes();
return Base64Utils.decode(bytes); return Base64Utils.decode(bytes);

8
spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/ssl/PrivateKeyParser.java

@ -18,7 +18,6 @@ package org.springframework.boot.buildpack.platform.docker.ssl;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.security.GeneralSecurityException; import java.security.GeneralSecurityException;
@ -65,7 +64,7 @@ final class PrivateKeyParser {
*/ */
static PrivateKey parse(Path path) { static PrivateKey parse(Path path) {
try { try {
String text = readText(path); String text = Files.readString(path);
Matcher matcher = PKCS1_PATTERN.matcher(text); Matcher matcher = PKCS1_PATTERN.matcher(text);
if (matcher.find()) { if (matcher.find()) {
return parsePkcs1(decodeBase64(matcher.group(1))); return parsePkcs1(decodeBase64(matcher.group(1)));
@ -132,11 +131,6 @@ final class PrivateKeyParser {
} }
} }
private static String readText(Path path) throws IOException {
byte[] bytes = Files.readAllBytes(path);
return new String(bytes, StandardCharsets.UTF_8);
}
private static byte[] decodeBase64(String content) { private static byte[] decodeBase64(String content) {
byte[] contentBytes = content.replaceAll("\r", "").replaceAll("\n", "").getBytes(); byte[] contentBytes = content.replaceAll("\r", "").replaceAll("\n", "").getBytes();
return Base64Utils.decode(contentBytes); return Base64Utils.decode(contentBytes);

7
spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/ResolveMainClassName.java

@ -18,7 +18,6 @@ package org.springframework.boot.gradle.plugin;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.StandardOpenOption; import java.nio.file.StandardOpenOption;
@ -122,8 +121,8 @@ public class ResolveMainClassName extends DefaultTask {
File outputFile = this.outputFile.getAsFile().get(); File outputFile = this.outputFile.getAsFile().get();
outputFile.getParentFile().mkdirs(); outputFile.getParentFile().mkdirs();
String mainClassName = resolveMainClassName(); String mainClassName = resolveMainClassName();
Files.write(outputFile.toPath(), mainClassName.getBytes(StandardCharsets.UTF_8), StandardOpenOption.WRITE, Files.writeString(outputFile.toPath(), mainClassName, StandardOpenOption.WRITE, StandardOpenOption.CREATE,
StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); StandardOpenOption.TRUNCATE_EXISTING);
} }
private String resolveMainClassName() { private String resolveMainClassName() {
@ -158,7 +157,7 @@ public class ResolveMainClassName extends DefaultTask {
} }
Path output = file.getAsFile().toPath(); Path output = file.getAsFile().toPath();
try { try {
return new String(Files.readAllBytes(output), StandardCharsets.UTF_8); return Files.readString(output);
} }
catch (IOException ex) { catch (IOException ex) {
throw new RuntimeException("Failed to read main class name from '" + output + "'"); throw new RuntimeException("Failed to read main class name from '" + output + "'");

11
spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoIntegrationTests.java

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2021 the original author or authors. * Copyright 2012-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -19,7 +19,6 @@ package org.springframework.boot.gradle.tasks.buildinfo;
import java.io.File; import java.io.File;
import java.io.FileReader; import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.StandardOpenOption; import java.nio.file.StandardOpenOption;
@ -101,11 +100,11 @@ class BuildInfoIntegrationTests {
@TestTemplate @TestTemplate
void notUpToDateWhenExecutedTwiceWithFixedTimeAndChangedGradlePropertiesProjectVersion() throws IOException { void notUpToDateWhenExecutedTwiceWithFixedTimeAndChangedGradlePropertiesProjectVersion() throws IOException {
Path gradleProperties = new File(this.gradleBuild.getProjectDir(), "gradle.properties").toPath(); Path gradleProperties = new File(this.gradleBuild.getProjectDir(), "gradle.properties").toPath();
Files.write(gradleProperties, "version=0.1.0".getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, Files.writeString(gradleProperties, "version=0.1.0", StandardOpenOption.CREATE, StandardOpenOption.WRITE,
StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); StandardOpenOption.TRUNCATE_EXISTING);
assertThat(this.gradleBuild.build("buildInfo").task(":buildInfo").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); assertThat(this.gradleBuild.build("buildInfo").task(":buildInfo").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
Files.write(gradleProperties, "version=0.2.0".getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, Files.writeString(gradleProperties, "version=0.2.0", StandardOpenOption.CREATE, StandardOpenOption.WRITE,
StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); StandardOpenOption.TRUNCATE_EXISTING);
assertThat(this.gradleBuild.build("buildInfo").task(":buildInfo").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); assertThat(this.gradleBuild.build("buildInfo").task(":buildInfo").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
} }

18
spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveTests.java

@ -22,11 +22,12 @@ import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption; import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.PosixFilePermission; import java.nio.file.attribute.PosixFilePermission;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
@ -294,11 +295,11 @@ abstract class AbstractBootArchiveTests<T extends Jar & BootArchive> {
void customLaunchScriptCanBePrepended() throws IOException { void customLaunchScriptCanBePrepended() throws IOException {
this.task.getMainClass().set("com.example.Main"); this.task.getMainClass().set("com.example.Main");
File customScript = new File(this.temp, "custom.script"); File customScript = new File(this.temp, "custom.script");
Files.write(customScript.toPath(), Arrays.asList("custom script"), StandardOpenOption.CREATE); Files.writeString(customScript.toPath(), "custom script", StandardOpenOption.CREATE);
this.task.launchScript((configuration) -> configuration.setScript(customScript)); this.task.launchScript((configuration) -> configuration.setScript(customScript));
executeTask(); executeTask();
assertThat(Files.readAllBytes(this.task.getArchiveFile().get().getAsFile().toPath())) Path path = this.task.getArchiveFile().get().getAsFile().toPath();
.startsWith("custom script".getBytes()); assertThat(Files.readString(path, StandardCharsets.ISO_8859_1)).startsWith("custom script");
} }
@Test @Test
@ -310,10 +311,11 @@ abstract class AbstractBootArchiveTests<T extends Jar & BootArchive> {
configuration.getProperties().put("initInfoDescription", "description"); configuration.getProperties().put("initInfoDescription", "description");
}); });
executeTask(); executeTask();
byte[] bytes = Files.readAllBytes(this.task.getArchiveFile().get().getAsFile().toPath()); Path path = this.task.getArchiveFile().get().getAsFile().toPath();
assertThat(bytes).containsSequence("Provides: provides".getBytes()); String content = Files.readString(path, StandardCharsets.ISO_8859_1);
assertThat(bytes).containsSequence("Short-Description: short description".getBytes()); assertThat(content).containsSequence("Provides: provides");
assertThat(bytes).containsSequence("Description: description".getBytes()); assertThat(content).containsSequence("Short-Description: short description");
assertThat(content).containsSequence("Description: description");
} }
@Test @Test

20
spring-boot-project/spring-boot-tools/spring-boot-maven-plugin/src/intTest/java/org/springframework/boot/maven/MavenBuild.java

@ -20,7 +20,6 @@ import java.io.File;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitResult; import java.nio.file.FileVisitResult;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
@ -140,12 +139,12 @@ class MavenBuild {
@Override @Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (file.toFile().getName().equals("pom.xml")) { if (file.toFile().getName().equals("pom.xml")) {
String pomXml = new String(Files.readAllBytes(file), StandardCharsets.UTF_8); String pomXml = Files.readString(file);
for (Entry<String, String> replacement : MavenBuild.this.pomReplacements.entrySet()) { for (Entry<String, String> replacement : MavenBuild.this.pomReplacements.entrySet()) {
pomXml = pomXml.replace("@" + replacement.getKey() + "@", replacement.getValue()); pomXml = pomXml.replace("@" + replacement.getKey() + "@", replacement.getValue());
} }
Files.write(destination.resolve(source.relativize(file)), Files.writeString(destination.resolve(source.relativize(file)), pomXml,
pomXml.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE_NEW); StandardOpenOption.CREATE_NEW);
} }
else { else {
Files.copy(file, destination.resolve(source.relativize(file)), Files.copy(file, destination.resolve(source.relativize(file)),
@ -155,14 +154,11 @@ class MavenBuild {
} }
}); });
String settingsXml = new String(Files.readAllBytes(Paths.get("src", "intTest", "projects", "settings.xml")), String settingsXml = Files.readString(Paths.get("src", "intTest", "projects", "settings.xml"))
StandardCharsets.UTF_8) .replace("@localCentralUrl@",
.replace("@localCentralUrl@", new File("build/int-test-maven-repository").toURI().toURL().toString())
new File("build/int-test-maven-repository").toURI().toURL().toString()) .replace("@localRepositoryPath@", new File("build/local-maven-repository").getAbsolutePath());
.replace("@localRepositoryPath@", Files.writeString(destination.resolve("settings.xml"), settingsXml, StandardOpenOption.CREATE_NEW);
new File("build/local-maven-repository").getAbsolutePath());
Files.write(destination.resolve("settings.xml"), settingsXml.getBytes(StandardCharsets.UTF_8),
StandardOpenOption.CREATE_NEW);
request.setBaseDirectory(this.temp); request.setBaseDirectory(this.temp);
request.setJavaHome(new File(System.getProperty("java.home"))); request.setJavaHome(new File(System.getProperty("java.home")));
request.setProperties(this.properties); request.setProperties(this.properties);

Loading…
Cancel
Save