Skip to content

[8.x] Cleanup missing use of StandardCharsets (#125424) #125438

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: 8.19
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
*/
package org.elasticsearch.gradle.internal;

import com.google.common.collect.Iterables;

import org.gradle.api.DefaultTask;
import org.gradle.api.file.FileCollection;
import org.gradle.api.tasks.Input;
Expand Down Expand Up @@ -85,7 +87,7 @@ public void setAdditionalLines(List<String> additionalLines) {
public void concatFiles() throws IOException {
if (getHeaderLine() != null) {
getTarget().getParentFile().mkdirs();
Files.write(getTarget().toPath(), (getHeaderLine() + '\n').getBytes(StandardCharsets.UTF_8));
Files.writeString(getTarget().toPath(), getHeaderLine() + '\n');
}

// To remove duplicate lines
Expand All @@ -95,11 +97,12 @@ public void concatFiles() throws IOException {
uniqueLines.addAll(Files.readAllLines(f.toPath(), StandardCharsets.UTF_8));
}
}
Files.write(getTarget().toPath(), uniqueLines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);

for (String additionalLine : additionalLines) {
Files.write(getTarget().toPath(), (additionalLine + '\n').getBytes(StandardCharsets.UTF_8), StandardOpenOption.APPEND);
}
Files.write(
getTarget().toPath(),
Iterables.concat(uniqueLines, additionalLines),
StandardCharsets.UTF_8,
StandardOpenOption.APPEND
);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ public void generateDependenciesInfo() throws IOException {
output.append(dep.getGroup() + ":" + dep.getName() + "," + dep.getVersion() + "," + url + "," + licenseType + "\n");
}

Files.write(outputFile.toPath(), output.toString().getBytes("UTF-8"), StandardOpenOption.CREATE);
Files.writeString(outputFile.toPath(), output.toString(), StandardOpenOption.CREATE);
}

@Input
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
Expand Down Expand Up @@ -440,7 +441,7 @@ private PrintWriter setupCurrent(Snippet test) {
// Now setup the writer
try {
Files.createDirectories(dest.getParent());
current = new PrintWriter(dest.toFile(), "UTF-8");
current = new PrintWriter(dest.toFile(), StandardCharsets.UTF_8);
return current;
} catch (IOException e) {
throw new RuntimeException(e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ public void checkInvalidPermissions() throws IOException {
}

outputMarker.getParentFile().mkdirs();
Files.write(outputMarker.toPath(), "done".getBytes("UTF-8"));
Files.writeString(outputMarker.toPath(), "done");
}

@OutputFile
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ public void checkInvalidPatterns() throws IOException {

File outputMarker = getOutputMarker();
outputMarker.getParentFile().mkdirs();
Files.write(outputMarker.toPath(), "done".getBytes(StandardCharsets.UTF_8));
Files.writeString(outputMarker.toPath(), "done");
}

@OutputFile
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,7 @@ private String runForbiddenAPIsCli() throws IOException {
}
final String forbiddenApisOutput;
try (ByteArrayOutputStream outputStream = errorOut) {
forbiddenApisOutput = outputStream.toString(StandardCharsets.UTF_8.name());
forbiddenApisOutput = outputStream.toString(StandardCharsets.UTF_8);
}
if (EXPECTED_EXIT_CODES.contains(result.getExitValue()) == false) {
throw new IllegalStateException("Forbidden APIs cli failed: " + forbiddenApisOutput);
Expand Down Expand Up @@ -402,7 +402,7 @@ private Set<String> runJdkJarHellCheck() throws IOException {
}
final String jdkJarHellCheckList;
try (ByteArrayOutputStream outputStream = standardOut) {
jdkJarHellCheckList = outputStream.toString(StandardCharsets.UTF_8.name());
jdkJarHellCheckList = outputStream.toString(StandardCharsets.UTF_8);
}
return new TreeSet<>(Arrays.asList(jdkJarHellCheckList.split("\\r?\\n")));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ public void testConcatenationWithUnique() throws IOException {
file2.getParentFile().mkdirs();
file1.createNewFile();
file2.createNewFile();
Files.write(file1.toPath(), ("Hello" + System.lineSeparator() + "Hello").getBytes(StandardCharsets.UTF_8));
Files.write(file2.toPath(), ("Hello" + System.lineSeparator() + "नमस्ते").getBytes(StandardCharsets.UTF_8));
Files.writeString(file1.toPath(), "Hello" + System.lineSeparator() + "Hello");
Files.writeString(file2.toPath(), "Hello" + System.lineSeparator() + "नमस्ते");

concatFilesTask.setFiles(project.fileTree(file1.getParentFile().getParentFile()));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ private void createFileIn(File parent, String name, String content) throws IOExc
Path file = parent.toPath().resolve(name);
file.toFile().createNewFile();

Files.write(file, content.getBytes(StandardCharsets.UTF_8));
Files.writeString(file, content);
}

private TaskProvider<DependencyLicensesTask> createDependencyLicensesTask(Project project) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import org.junit.Test;

import java.io.File;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
import java.util.stream.Collectors;
Expand Down Expand Up @@ -61,7 +61,7 @@ public void testCheckPermissionsWhenNoFileExists() throws Exception {
filePermissionsTask.checkInvalidPermissions();

File outputMarker = new File(project.getBuildDir(), "markers/filePermissions");
List<String> result = Files.readAllLines(outputMarker.toPath(), Charset.forName("UTF-8"));
List<String> result = Files.readAllLines(outputMarker.toPath(), StandardCharsets.UTF_8);
assertEquals("done", result.get(0));
}

Expand All @@ -80,7 +80,7 @@ public void testCheckPermissionsWhenNoExecutableFileExists() throws Exception {
filePermissionsTask.checkInvalidPermissions();

File outputMarker = new File(project.getBuildDir(), "markers/filePermissions");
List<String> result = Files.readAllLines(outputMarker.toPath(), Charset.forName("UTF-8"));
List<String> result = Files.readAllLines(outputMarker.toPath(), StandardCharsets.UTF_8);
assertEquals("done", result.get(0));

file.delete();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@
import java.io.IOException;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
Expand Down Expand Up @@ -182,11 +181,7 @@ public void run() {
execSpec.setWorkingDir(getWorkingDir().get());
}
if (getStandardInput().isPresent()) {
try {
execSpec.setStandardInput(new ByteArrayInputStream(getStandardInput().get().getBytes("UTF-8")));
} catch (UnsupportedEncodingException e) {
throw new GradleException("Cannot set standard input", e);
}
execSpec.setStandardInput(new ByteArrayInputStream(getStandardInput().get().getBytes(StandardCharsets.UTF_8)));
}
});
int exitValue = execResult.getExitValue();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.security.GeneralSecurityException;
import java.util.Collection;
Expand Down Expand Up @@ -533,7 +532,7 @@ public void writeUnicastHostsFiles() {
String unicastUris = nodes.stream().flatMap(node -> node.getAllTransportPortURI().stream()).collect(Collectors.joining("\n"));
nodes.forEach(node -> {
try {
Files.write(node.getConfigDir().resolve("unicast_hosts.txt"), unicastUris.getBytes(StandardCharsets.UTF_8));
Files.writeString(node.getConfigDir().resolve("unicast_hosts.txt"), unicastUris);
} catch (IOException e) {
throw new UncheckedIOException("Failed to write unicast_hosts for " + this, e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,7 @@ static void writePluginSecurityPolicy(Path pluginDir, String... permissions) thr
securityPolicyContent.append("\";");
}
securityPolicyContent.append("\n};\n");
Files.write(pluginDir.resolve("plugin-security.policy"), securityPolicyContent.toString().getBytes(StandardCharsets.UTF_8));
Files.writeString(pluginDir.resolve("plugin-security.policy"), securityPolicyContent.toString());
}

static InstallablePlugin createStablePlugin(String name, Path structure, boolean hasNamedComponentFile, String... additionalProps)
Expand Down Expand Up @@ -787,10 +787,10 @@ public void testConfig() throws Exception {
public void testExistingConfig() throws Exception {
Path envConfigDir = env.v2().configDir().resolve("fake");
Files.createDirectories(envConfigDir);
Files.write(envConfigDir.resolve("custom.yml"), "existing config".getBytes(StandardCharsets.UTF_8));
Files.writeString(envConfigDir.resolve("custom.yml"), "existing config");
Path configDir = pluginDir.resolve("config");
Files.createDirectory(configDir);
Files.write(configDir.resolve("custom.yml"), "new config".getBytes(StandardCharsets.UTF_8));
Files.writeString(configDir.resolve("custom.yml"), "new config");
Files.createFile(configDir.resolve("other.yml"));
InstallablePlugin pluginZip = createPluginZip("fake", pluginDir);
installPlugin(pluginZip);
Expand Down Expand Up @@ -1033,13 +1033,13 @@ URL openUrl(String urlString) throws IOException {
Path shaFile = temp.apply("shas").resolve("downloaded.zip" + shaExtension);
byte[] zipbytes = Files.readAllBytes(pluginZipPath);
String checksum = shaCalculator.apply(zipbytes);
Files.write(shaFile, checksum.getBytes(StandardCharsets.UTF_8));
Files.writeString(shaFile, checksum);
return shaFile.toUri().toURL();
} else if ((url + ".asc").equals(urlString)) {
final Path ascFile = temp.apply("asc").resolve("downloaded.zip" + ".asc");
final byte[] zipBytes = Files.readAllBytes(pluginZipPath);
final String asc = signature.apply(zipBytes, secretKey);
Files.write(ascFile, asc.getBytes(StandardCharsets.UTF_8));
Files.writeString(ascFile, asc);
return ascFile.toUri().toURL();
}
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -426,7 +426,7 @@ static void checkFilesReadAllLinesWithCharset() throws IOException {
@EntitlementTest(expectedAccess = PLUGINS)
static void checkFilesWrite() throws IOException {
var directory = EntitledActions.createTempDirectoryForWrite();
Files.write(directory.resolve("file"), "foo".getBytes(StandardCharsets.UTF_8));
Files.writeString(directory.resolve("file"), "foo");
}

@EntitlementTest(expectedAccess = PLUGINS)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ protected boolean isSupportedValue(Object value) {

private static boolean isValidUrlEncodedString(String s) {
try {
URLDecoder.decode(s, "UTF-8");
URLDecoder.decode(s, StandardCharsets.UTF_8);
return true;
} catch (Exception e) {
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -425,7 +425,7 @@ public void testUrlEncoderWithParam() throws Exception {
assertScript(
"{{#url}}prefix_{{s}}{{/url}}",
singletonMap("s", random),
equalTo("prefix_" + URLEncoder.encode(random, StandardCharsets.UTF_8.name()))
equalTo("prefix_" + URLEncoder.encode(random, StandardCharsets.UTF_8))
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public static void main(String[] args) throws IOException {
PrintStream jsonStream = new PrintStream(
Files.newOutputStream(json, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE),
false,
StandardCharsets.UTF_8.name()
StandardCharsets.UTF_8
)
) {

Expand All @@ -63,7 +63,7 @@ public static void main(String[] args) throws IOException {
PrintStream jsonStream = new PrintStream(
Files.newOutputStream(json, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE),
false,
StandardCharsets.UTF_8.name()
StandardCharsets.UTF_8
)
) {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,6 @@

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
Expand Down Expand Up @@ -351,14 +350,14 @@ public void dispatchBadRequest(final RestChannel channel, final ThreadContext th
final TransportAddress remoteAddress = randomFrom(transport.boundAddress().boundAddresses());

try (Netty4HttpClient client = new Netty4HttpClient()) {
final String url = "/" + new String(new byte[maxInitialLineLength], Charset.forName("UTF-8"));
final String url = "/" + new String(new byte[maxInitialLineLength], StandardCharsets.UTF_8);
final FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, url);

final FullHttpResponse response = client.send(remoteAddress.address(), request);
try {
assertThat(response.status(), equalTo(HttpResponseStatus.BAD_REQUEST));
assertThat(
new String(response.content().array(), Charset.forName("UTF-8")),
new String(response.content().array(), StandardCharsets.UTF_8),
containsString("you sent a bad request and you should feel bad")
);
} finally {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
import org.elasticsearch.index.analysis.AbstractTokenFilterFactory;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;

Expand Down Expand Up @@ -51,7 +51,7 @@ public IcuCollationTokenFilterFactory(IndexSettings indexSettings, Environment e
if (rules != null) {
Exception failureToResolve = null;
try {
rules = Streams.copyToString(Files.newBufferedReader(environment.configDir().resolve(rules), Charset.forName("UTF-8")));
rules = Streams.copyToString(Files.newBufferedReader(environment.configDir().resolve(rules), StandardCharsets.UTF_8));
} catch (IOException | SecurityException | InvalidPathException e) {
failureToResolve = e;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
import org.elasticsearch.test.ESTestCase;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.Locale;
Expand Down Expand Up @@ -165,7 +166,7 @@ public void testAnnotatedTextStructuredMatch() throws Exception {
// on marked-up
// content using an "annotated_text" type field.
String url = "https://en.wikipedia.org/wiki/Key_Word_in_Context";
String encodedUrl = URLEncoder.encode(url, "UTF-8");
String encodedUrl = URLEncoder.encode(url, StandardCharsets.UTF_8);
String annotatedWord = "[highlighting](" + encodedUrl + ")";
String highlightedAnnotatedWord = "[highlighting]("
+ AnnotatedPassageFormatter.SEARCH_HIT_TYPE
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
import org.elasticsearch.test.MockLog;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFileAttributeView;
Expand Down Expand Up @@ -271,7 +270,7 @@ public void testSpawnerHandlingOfDesktopServicesStoreFiles() throws IOException
private void createControllerProgram(final Path outputFile) throws IOException {
final Path outputDir = outputFile.getParent();
Files.createDirectories(outputDir);
Files.write(outputFile, CONTROLLER_SOURCE.getBytes(StandardCharsets.UTF_8));
Files.writeString(outputFile, CONTROLLER_SOURCE);
final PosixFileAttributeView view = Files.getFileAttributeView(outputFile, PosixFileAttributeView.class);
if (view != null) {
final Set<PosixFilePermission> perms = new HashSet<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ public static String slurpTxtorGz(Path file) {
public static String slurpAllLogs(Path logPath, String activeLogFile, String rotatedLogFilesGlob) {
StringJoiner logFileJoiner = new StringJoiner("\n");
try {
logFileJoiner.add(new String(Files.readAllBytes(logPath.resolve(activeLogFile)), StandardCharsets.UTF_8));
logFileJoiner.add(Files.readString(logPath.resolve(activeLogFile)));

for (Path rotatedLogFile : FileUtils.lsGlob(logPath, rotatedLogFilesGlob)) {
logFileJoiner.add(FileUtils.slurpTxtorGz(rotatedLogFile));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ public void afterIndexShardClosed(ShardId sid, @Nullable IndexShard indexShard,
return;
}
BytesStreamOutput os = new BytesStreamOutput();
PrintStream out = new PrintStream(os, false, StandardCharsets.UTF_8.name());
PrintStream out = new PrintStream(os, false, StandardCharsets.UTF_8);
CheckIndex.Status status = store.checkIndex(out);
out.flush();
if (status.clean == false) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ private void writeJSONFile(String node, String json) throws Exception {

logger.info("--> writing JSON config to node {} with path {}", node, tempFilePath);
logger.info(Strings.format(json, version));
Files.write(tempFilePath, Strings.format(json, version).getBytes(StandardCharsets.UTF_8));
Files.writeString(tempFilePath, Strings.format(json, version));
Files.move(tempFilePath, fileSettingsService.watchedFile(), StandardCopyOption.ATOMIC_MOVE);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
import org.junit.Before;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
Expand Down Expand Up @@ -252,7 +251,7 @@ private void writeFileSettings(String json) throws Exception {
Path fileSettings = configDir.resolve("operator").resolve("settings.json");
Files.createDirectories(fileSettings.getParent());

Files.write(tempFilePath, Strings.format(json, version).getBytes(StandardCharsets.UTF_8));
Files.writeString(tempFilePath, Strings.format(json, version));
Files.move(tempFilePath, fileSettings, StandardCopyOption.ATOMIC_MOVE);
logger.info("--> New file settings: [{}]", Strings.format(json, version));
}
Expand Down
Loading