Cleanup missing use of StandardCharsets (#125424)

Random annoyance that I figured, I'd just fix globally:
We can do a bit of a cleaner job when doing byte <-> string conversion here and there.
This commit is contained in:
Armin Braun 2025-03-21 20:10:15 +01:00 committed by GitHub
parent 02f12c8e83
commit 50437e79d3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
55 changed files with 97 additions and 99 deletions

View file

@ -8,6 +8,8 @@
*/ */
package org.elasticsearch.gradle.internal; package org.elasticsearch.gradle.internal;
import com.google.common.collect.Iterables;
import org.gradle.api.DefaultTask; import org.gradle.api.DefaultTask;
import org.gradle.api.file.FileCollection; import org.gradle.api.file.FileCollection;
import org.gradle.api.tasks.Input; import org.gradle.api.tasks.Input;
@ -85,7 +87,7 @@ public class ConcatFilesTask extends DefaultTask {
public void concatFiles() throws IOException { public void concatFiles() throws IOException {
if (getHeaderLine() != null) { if (getHeaderLine() != null) {
getTarget().getParentFile().mkdirs(); getTarget().getParentFile().mkdirs();
Files.write(getTarget().toPath(), (getHeaderLine() + '\n').getBytes(StandardCharsets.UTF_8)); Files.writeString(getTarget().toPath(), getHeaderLine() + '\n');
} }
// To remove duplicate lines // To remove duplicate lines
@ -95,11 +97,12 @@ public class ConcatFilesTask extends DefaultTask {
uniqueLines.addAll(Files.readAllLines(f.toPath(), StandardCharsets.UTF_8)); uniqueLines.addAll(Files.readAllLines(f.toPath(), StandardCharsets.UTF_8));
} }
} }
Files.write(getTarget().toPath(), uniqueLines, StandardCharsets.UTF_8, StandardOpenOption.APPEND); Files.write(
getTarget().toPath(),
for (String additionalLine : additionalLines) { Iterables.concat(uniqueLines, additionalLines),
Files.write(getTarget().toPath(), (additionalLine + '\n').getBytes(StandardCharsets.UTF_8), StandardOpenOption.APPEND); StandardCharsets.UTF_8,
} StandardOpenOption.APPEND
);
} }
} }

View file

@ -155,7 +155,7 @@ public class DependenciesInfoTask extends ConventionTask {
output.append(dep.getGroup() + ":" + dep.getName() + "," + dep.getVersion() + "," + url + "," + licenseType + "\n"); 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 @Input

View file

@ -24,6 +24,7 @@ import org.gradle.api.tasks.OutputDirectory;
import java.io.File; import java.io.File;
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.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
@ -440,7 +441,7 @@ public abstract class RestTestsFromDocSnippetTask extends DocSnippetTask {
// Now setup the writer // Now setup the writer
try { try {
Files.createDirectories(dest.getParent()); Files.createDirectories(dest.getParent());
current = new PrintWriter(dest.toFile(), "UTF-8"); current = new PrintWriter(dest.toFile(), StandardCharsets.UTF_8);
return current; return current;
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);

View file

@ -106,7 +106,7 @@ public abstract class FilePermissionsTask extends DefaultTask {
} }
outputMarker.getParentFile().mkdirs(); outputMarker.getParentFile().mkdirs();
Files.write(outputMarker.toPath(), "done".getBytes("UTF-8")); Files.writeString(outputMarker.toPath(), "done");
} }
@OutputFile @OutputFile

View file

@ -135,7 +135,7 @@ public abstract class ForbiddenPatternsTask extends DefaultTask {
File outputMarker = getOutputMarker(); File outputMarker = getOutputMarker();
outputMarker.getParentFile().mkdirs(); outputMarker.getParentFile().mkdirs();
Files.write(outputMarker.toPath(), "done".getBytes(StandardCharsets.UTF_8)); Files.writeString(outputMarker.toPath(), "done");
} }
@OutputFile @OutputFile

View file

@ -364,7 +364,7 @@ public abstract class ThirdPartyAuditTask extends DefaultTask {
} }
final String forbiddenApisOutput; final String forbiddenApisOutput;
try (ByteArrayOutputStream outputStream = errorOut) { 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) { if (EXPECTED_EXIT_CODES.contains(result.getExitValue()) == false) {
throw new IllegalStateException("Forbidden APIs cli failed: " + forbiddenApisOutput); throw new IllegalStateException("Forbidden APIs cli failed: " + forbiddenApisOutput);
@ -397,7 +397,7 @@ public abstract class ThirdPartyAuditTask extends DefaultTask {
} }
final String jdkJarHellCheckList; final String jdkJarHellCheckList;
try (ByteArrayOutputStream outputStream = standardOut) { 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"))); return new TreeSet<>(Arrays.asList(jdkJarHellCheckList.split("\\r?\\n")));
} }

View file

@ -60,8 +60,8 @@ public class ConcatFilesTaskTests {
file2.getParentFile().mkdirs(); file2.getParentFile().mkdirs();
file1.createNewFile(); file1.createNewFile();
file2.createNewFile(); file2.createNewFile();
Files.write(file1.toPath(), ("Hello" + System.lineSeparator() + "Hello").getBytes(StandardCharsets.UTF_8)); Files.writeString(file1.toPath(), "Hello" + System.lineSeparator() + "Hello");
Files.write(file2.toPath(), ("Hello" + System.lineSeparator() + "नमस्ते").getBytes(StandardCharsets.UTF_8)); Files.writeString(file2.toPath(), "Hello" + System.lineSeparator() + "नमस्ते");
concatFilesTask.setFiles(project.fileTree(file1.getParentFile().getParentFile())); concatFilesTask.setFiles(project.fileTree(file1.getParentFile().getParentFile()));

View file

@ -244,7 +244,7 @@ public class DependencyLicensesTaskTests {
Path file = parent.toPath().resolve(name); Path file = parent.toPath().resolve(name);
file.toFile().createNewFile(); file.toFile().createNewFile();
Files.write(file, content.getBytes(StandardCharsets.UTF_8)); Files.writeString(file, content);
} }
private TaskProvider<DependencyLicensesTask> createDependencyLicensesTask(Project project) { private TaskProvider<DependencyLicensesTask> createDependencyLicensesTask(Project project) {

View file

@ -18,7 +18,7 @@ import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import java.io.File; import java.io.File;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -61,7 +61,7 @@ public class FilePermissionsTaskTests {
filePermissionsTask.checkInvalidPermissions(); filePermissionsTask.checkInvalidPermissions();
File outputMarker = new File(project.getBuildDir(), "markers/filePermissions"); 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)); assertEquals("done", result.get(0));
} }
@ -80,7 +80,7 @@ public class FilePermissionsTaskTests {
filePermissionsTask.checkInvalidPermissions(); filePermissionsTask.checkInvalidPermissions();
File outputMarker = new File(project.getBuildDir(), "markers/filePermissions"); 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)); assertEquals("done", result.get(0));
file.delete(); file.delete();

View file

@ -38,7 +38,6 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.UncheckedIOException; import java.io.UncheckedIOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.util.List; import java.util.List;
@ -193,11 +192,7 @@ public abstract class LoggedExec extends DefaultTask implements FileSystemOperat
execSpec.setWorkingDir(getWorkingDir().get()); execSpec.setWorkingDir(getWorkingDir().get());
} }
if (getStandardInput().isPresent()) { if (getStandardInput().isPresent()) {
try { execSpec.setStandardInput(new ByteArrayInputStream(getStandardInput().get().getBytes(StandardCharsets.UTF_8)));
execSpec.setStandardInput(new ByteArrayInputStream(getStandardInput().get().getBytes("UTF-8")));
} catch (UnsupportedEncodingException e) {
throw new GradleException("Cannot set standard input", e);
}
} }
}); });
int exitValue = execResult.getExitValue(); int exitValue = execResult.getExitValue();

View file

@ -42,7 +42,6 @@ import org.gradle.process.ExecOperations;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.UncheckedIOException; import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.security.GeneralSecurityException; import java.security.GeneralSecurityException;
import java.util.Collection; import java.util.Collection;
@ -533,7 +532,7 @@ public class ElasticsearchCluster implements TestClusterConfiguration, Named {
String unicastUris = nodes.stream().flatMap(node -> node.getAllTransportPortURI().stream()).collect(Collectors.joining("\n")); String unicastUris = nodes.stream().flatMap(node -> node.getAllTransportPortURI().stream()).collect(Collectors.joining("\n"));
nodes.forEach(node -> { nodes.forEach(node -> {
try { 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) { } catch (IOException e) {
throw new UncheckedIOException("Failed to write unicast_hosts for " + this, e); throw new UncheckedIOException("Failed to write unicast_hosts for " + this, e);
} }

View file

@ -317,7 +317,7 @@ public class InstallPluginActionTests extends ESTestCase {
securityPolicyContent.append("\";"); securityPolicyContent.append("\";");
} }
securityPolicyContent.append("\n};\n"); 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) static InstallablePlugin createStablePlugin(String name, Path structure, boolean hasNamedComponentFile, String... additionalProps)
@ -787,10 +787,10 @@ public class InstallPluginActionTests extends ESTestCase {
public void testExistingConfig() throws Exception { public void testExistingConfig() throws Exception {
Path envConfigDir = env.v2().configDir().resolve("fake"); Path envConfigDir = env.v2().configDir().resolve("fake");
Files.createDirectories(envConfigDir); 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"); Path configDir = pluginDir.resolve("config");
Files.createDirectory(configDir); 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")); Files.createFile(configDir.resolve("other.yml"));
InstallablePlugin pluginZip = createPluginZip("fake", pluginDir); InstallablePlugin pluginZip = createPluginZip("fake", pluginDir);
installPlugin(pluginZip); installPlugin(pluginZip);
@ -1033,13 +1033,13 @@ public class InstallPluginActionTests extends ESTestCase {
Path shaFile = temp.apply("shas").resolve("downloaded.zip" + shaExtension); Path shaFile = temp.apply("shas").resolve("downloaded.zip" + shaExtension);
byte[] zipbytes = Files.readAllBytes(pluginZipPath); byte[] zipbytes = Files.readAllBytes(pluginZipPath);
String checksum = shaCalculator.apply(zipbytes); String checksum = shaCalculator.apply(zipbytes);
Files.write(shaFile, checksum.getBytes(StandardCharsets.UTF_8)); Files.writeString(shaFile, checksum);
return shaFile.toUri().toURL(); return shaFile.toUri().toURL();
} else if ((url + ".asc").equals(urlString)) { } else if ((url + ".asc").equals(urlString)) {
final Path ascFile = temp.apply("asc").resolve("downloaded.zip" + ".asc"); final Path ascFile = temp.apply("asc").resolve("downloaded.zip" + ".asc");
final byte[] zipBytes = Files.readAllBytes(pluginZipPath); final byte[] zipBytes = Files.readAllBytes(pluginZipPath);
final String asc = signature.apply(zipBytes, secretKey); final String asc = signature.apply(zipBytes, secretKey);
Files.write(ascFile, asc.getBytes(StandardCharsets.UTF_8)); Files.writeString(ascFile, asc);
return ascFile.toUri().toURL(); return ascFile.toUri().toURL();
} }
return null; return null;

View file

@ -426,7 +426,7 @@ class NioFilesActions {
@EntitlementTest(expectedAccess = PLUGINS) @EntitlementTest(expectedAccess = PLUGINS)
static void checkFilesWrite() throws IOException { static void checkFilesWrite() throws IOException {
var directory = EntitledActions.createTempDirectoryForWrite(); var directory = EntitledActions.createTempDirectoryForWrite();
Files.write(directory.resolve("file"), "foo".getBytes(StandardCharsets.UTF_8)); Files.writeString(directory.resolve("file"), "foo");
} }
@EntitlementTest(expectedAccess = PLUGINS) @EntitlementTest(expectedAccess = PLUGINS)

View file

@ -48,7 +48,7 @@ public class URLDecodeProcessorTests extends AbstractStringProcessorTestCase<Str
private static boolean isValidUrlEncodedString(String s) { private static boolean isValidUrlEncodedString(String s) {
try { try {
URLDecoder.decode(s, "UTF-8"); URLDecoder.decode(s, StandardCharsets.UTF_8);
return true; return true;
} catch (Exception e) { } catch (Exception e) {
return false; return false;

View file

@ -425,7 +425,7 @@ public class MustacheTests extends ESTestCase {
assertScript( assertScript(
"{{#url}}prefix_{{s}}{{/url}}", "{{#url}}prefix_{{s}}{{/url}}",
singletonMap("s", random), singletonMap("s", random),
equalTo("prefix_" + URLEncoder.encode(random, StandardCharsets.UTF_8.name())) equalTo("prefix_" + URLEncoder.encode(random, StandardCharsets.UTF_8))
); );
} }

View file

@ -46,7 +46,7 @@ public class ContextApiSpecGenerator {
PrintStream jsonStream = new PrintStream( PrintStream jsonStream = new PrintStream(
Files.newOutputStream(json, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE), Files.newOutputStream(json, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE),
false, false,
StandardCharsets.UTF_8.name() StandardCharsets.UTF_8
) )
) { ) {
@ -63,7 +63,7 @@ public class ContextApiSpecGenerator {
PrintStream jsonStream = new PrintStream( PrintStream jsonStream = new PrintStream(
Files.newOutputStream(json, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE), Files.newOutputStream(json, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE),
false, false,
StandardCharsets.UTF_8.name() StandardCharsets.UTF_8
) )
) { ) {

View file

@ -95,7 +95,6 @@ import org.junit.Before;
import java.io.IOException; import java.io.IOException;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
@ -351,14 +350,14 @@ public class Netty4HttpServerTransportTests extends AbstractHttpServerTransportT
final TransportAddress remoteAddress = randomFrom(transport.boundAddress().boundAddresses()); final TransportAddress remoteAddress = randomFrom(transport.boundAddress().boundAddresses());
try (Netty4HttpClient client = new Netty4HttpClient()) { 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 FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, url);
final FullHttpResponse response = client.send(remoteAddress.address(), request); final FullHttpResponse response = client.send(remoteAddress.address(), request);
try { try {
assertThat(response.status(), equalTo(HttpResponseStatus.BAD_REQUEST)); assertThat(response.status(), equalTo(HttpResponseStatus.BAD_REQUEST));
assertThat( 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") containsString("you sent a bad request and you should feel bad")
); );
} finally { } finally {

View file

@ -21,7 +21,7 @@ import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.analysis.AbstractTokenFilterFactory; import org.elasticsearch.index.analysis.AbstractTokenFilterFactory;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.InvalidPathException; import java.nio.file.InvalidPathException;
@ -51,7 +51,7 @@ public class IcuCollationTokenFilterFactory extends AbstractTokenFilterFactory {
if (rules != null) { if (rules != null) {
Exception failureToResolve = null; Exception failureToResolve = null;
try { 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) { } catch (IOException | SecurityException | InvalidPathException e) {
failureToResolve = e; failureToResolve = e;
} }

View file

@ -45,6 +45,7 @@ import org.elasticsearch.search.fetch.subphase.highlight.LimitTokenOffsetAnalyze
import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.ESTestCase;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.BreakIterator; import java.text.BreakIterator;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Locale; import java.util.Locale;
@ -167,7 +168,7 @@ public class AnnotatedTextHighlighterTests extends ESTestCase {
// on marked-up // on marked-up
// content using an "annotated_text" type field. // content using an "annotated_text" type field.
String url = "https://en.wikipedia.org/wiki/Key_Word_in_Context"; 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 annotatedWord = "[highlighting](" + encodedUrl + ")";
String highlightedAnnotatedWord = "[highlighting](" String highlightedAnnotatedWord = "[highlighting]("
+ AnnotatedPassageFormatter.SEARCH_HIT_TYPE + AnnotatedPassageFormatter.SEARCH_HIT_TYPE

View file

@ -27,7 +27,6 @@ import org.elasticsearch.test.GraalVMThreadsFilter;
import org.elasticsearch.test.MockLog; import org.elasticsearch.test.MockLog;
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.attribute.PosixFileAttributeView; import java.nio.file.attribute.PosixFileAttributeView;
@ -270,7 +269,7 @@ public class SpawnerNoBootstrapTests extends LuceneTestCase {
private void createControllerProgram(final Path outputFile) throws IOException { private void createControllerProgram(final Path outputFile) throws IOException {
final Path outputDir = outputFile.getParent(); final Path outputDir = outputFile.getParent();
Files.createDirectories(outputDir); 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); final PosixFileAttributeView view = Files.getFileAttributeView(outputFile, PosixFileAttributeView.class);
if (view != null) { if (view != null) {
final Set<PosixFilePermission> perms = new HashSet<>(); final Set<PosixFilePermission> perms = new HashSet<>();

View file

@ -208,7 +208,7 @@ public class FileUtils {
public static String slurpAllLogs(Path logPath, String activeLogFile, String rotatedLogFilesGlob) { public static String slurpAllLogs(Path logPath, String activeLogFile, String rotatedLogFilesGlob) {
StringJoiner logFileJoiner = new StringJoiner("\n"); StringJoiner logFileJoiner = new StringJoiner("\n");
try { 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)) { for (Path rotatedLogFile : FileUtils.lsGlob(logPath, rotatedLogFilesGlob)) {
logFileJoiner.add(FileUtils.slurpTxtorGz(rotatedLogFile)); logFileJoiner.add(FileUtils.slurpTxtorGz(rotatedLogFile));

View file

@ -217,7 +217,7 @@ public class CorruptedFileIT extends ESIntegTestCase {
return; return;
} }
BytesStreamOutput os = new BytesStreamOutput(); 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); CheckIndex.Status status = store.checkIndex(out);
out.flush(); out.flush();
if (status.clean == false) { if (status.clean == false) {

View file

@ -129,7 +129,7 @@ public class IngestFileSettingsIT extends ESIntegTestCase {
logger.info("--> writing JSON config to node {} with path {}", node, tempFilePath); logger.info("--> writing JSON config to node {} with path {}", node, tempFilePath);
logger.info(Strings.format(json, version)); 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); Files.move(tempFilePath, fileSettingsService.watchedFile(), StandardCopyOption.ATOMIC_MOVE);
} }

View file

@ -29,7 +29,6 @@ import org.elasticsearch.test.InternalTestCluster;
import org.junit.Before; import org.junit.Before;
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.StandardCopyOption; import java.nio.file.StandardCopyOption;
@ -252,7 +251,7 @@ public class ReadinessClusterIT extends ESIntegTestCase {
Path fileSettings = configDir.resolve("operator").resolve("settings.json"); Path fileSettings = configDir.resolve("operator").resolve("settings.json");
Files.createDirectories(fileSettings.getParent()); 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); Files.move(tempFilePath, fileSettings, StandardCopyOption.ATOMIC_MOVE);
logger.info("--> New file settings: [{}]", Strings.format(json, version)); logger.info("--> New file settings: [{}]", Strings.format(json, version));
} }

View file

@ -332,13 +332,10 @@ public class ScriptedMetricIT extends ESIntegTestCase {
// When using the MockScriptPlugin we can map File scripts to inline scripts: // When using the MockScriptPlugin we can map File scripts to inline scripts:
// the name of the file script is used in test method while the source of the file script // the name of the file script is used in test method while the source of the file script
// must match a predefined script from CustomScriptPlugin.pluginScripts() method // must match a predefined script from CustomScriptPlugin.pluginScripts() method
Files.write(scripts.resolve("init_script.mockscript"), "vars.multiplier = 3".getBytes("UTF-8")); Files.writeString(scripts.resolve("init_script.mockscript"), "vars.multiplier = 3");
Files.write(scripts.resolve("map_script.mockscript"), "state.list.add(vars.multiplier)".getBytes("UTF-8")); Files.writeString(scripts.resolve("map_script.mockscript"), "state.list.add(vars.multiplier)");
Files.write(scripts.resolve("combine_script.mockscript"), "sum state values as a new aggregation".getBytes("UTF-8")); Files.writeString(scripts.resolve("combine_script.mockscript"), "sum state values as a new aggregation");
Files.write( Files.writeString(scripts.resolve("reduce_script.mockscript"), "sum all states (lists) values as a new aggregation");
scripts.resolve("reduce_script.mockscript"),
"sum all states (lists) values as a new aggregation".getBytes("UTF-8")
);
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException("failed to create scripts"); throw new RuntimeException("failed to create scripts");
} }

View file

@ -37,6 +37,7 @@ import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xcontent.XContentFactory; import org.elasticsearch.xcontent.XContentFactory;
import org.elasticsearch.xcontent.XContentType; import org.elasticsearch.xcontent.XContentType;
import java.nio.charset.StandardCharsets;
import java.time.Instant; import java.time.Instant;
import java.time.ZoneOffset; import java.time.ZoneOffset;
import java.time.ZonedDateTime; import java.time.ZonedDateTime;
@ -612,7 +613,7 @@ public class SearchFieldsIT extends ESIntegTestCase {
.field("double_field", 6.0d) .field("double_field", 6.0d)
.field("date_field", DateFormatter.forPattern("date_optional_time").format(date)) .field("date_field", DateFormatter.forPattern("date_optional_time").format(date))
.field("boolean_field", true) .field("boolean_field", true)
.field("binary_field", Base64.getEncoder().encodeToString("testing text".getBytes("UTF-8"))) .field("binary_field", Base64.getEncoder().encodeToString("testing text".getBytes(StandardCharsets.UTF_8)))
.endObject() .endObject()
) )
.get(); .get();
@ -661,7 +662,10 @@ public class SearchFieldsIT extends ESIntegTestCase {
String dateTime = DateFormatter.forPattern("date_optional_time").format(date); String dateTime = DateFormatter.forPattern("date_optional_time").format(date);
assertThat(searchHit.getFields().get("date_field").getValue(), equalTo((Object) dateTime)); assertThat(searchHit.getFields().get("date_field").getValue(), equalTo((Object) dateTime));
assertThat(searchHit.getFields().get("boolean_field").getValue(), equalTo((Object) Boolean.TRUE)); assertThat(searchHit.getFields().get("boolean_field").getValue(), equalTo((Object) Boolean.TRUE));
assertThat(searchHit.getFields().get("binary_field").getValue(), equalTo(new BytesArray("testing text".getBytes("UTF8")))); assertThat(
searchHit.getFields().get("binary_field").getValue(),
equalTo(new BytesArray("testing text".getBytes(StandardCharsets.UTF_8)))
);
} }
); );
} }

View file

@ -3280,7 +3280,7 @@ public class IndexShard extends AbstractIndexShardComponent implements IndicesCl
} else { } else {
// full checkindex // full checkindex
final BytesStreamOutput os = new BytesStreamOutput(); final BytesStreamOutput os = new BytesStreamOutput();
final PrintStream out = new PrintStream(os, false, StandardCharsets.UTF_8.name()); final PrintStream out = new PrintStream(os, false, StandardCharsets.UTF_8);
final CheckIndex.Status status = store.checkIndex(out); final CheckIndex.Status status = store.checkIndex(out);
out.flush(); out.flush();
if (status.clean == false) { if (status.clean == false) {

View file

@ -92,7 +92,7 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.nio.charset.Charset; 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.StandardCopyOption; import java.nio.file.StandardCopyOption;
@ -653,7 +653,7 @@ public class Node implements Closeable {
*/ */
private void writePortsFile(String type, BoundTransportAddress boundAddress) { private void writePortsFile(String type, BoundTransportAddress boundAddress) {
Path tmpPortsFile = environment.logsDir().resolve(type + ".ports.tmp"); Path tmpPortsFile = environment.logsDir().resolve(type + ".ports.tmp");
try (BufferedWriter writer = Files.newBufferedWriter(tmpPortsFile, Charset.forName("UTF-8"))) { try (BufferedWriter writer = Files.newBufferedWriter(tmpPortsFile, StandardCharsets.UTF_8)) {
for (TransportAddress address : boundAddress.boundAddresses()) { for (TransportAddress address : boundAddress.boundAddresses()) {
InetAddress inetAddress = InetAddress.getByName(address.getAddress()); InetAddress inetAddress = InetAddress.getByName(address.getAddress());
writer.write(NetworkAddress.format(new InetSocketAddress(inetAddress, address.getPort())) + "\n"); writer.write(NetworkAddress.format(new InetSocketAddress(inetAddress, address.getPort())) + "\n");

View file

@ -25,6 +25,7 @@ import java.nio.channels.FileChannel;
import java.nio.channels.FileLock; import java.nio.channels.FileLock;
import java.nio.channels.ReadableByteChannel; import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel; import java.nio.channels.WritableByteChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.StandardOpenOption; import java.nio.file.StandardOpenOption;
@ -42,7 +43,7 @@ public class ChannelsTests extends ESTestCase {
Path tmpFile = createTempFile(); Path tmpFile = createTempFile();
FileChannel randomAccessFile = FileChannel.open(tmpFile, StandardOpenOption.READ, StandardOpenOption.WRITE); FileChannel randomAccessFile = FileChannel.open(tmpFile, StandardOpenOption.READ, StandardOpenOption.WRITE);
fileChannel = new MockFileChannel(randomAccessFile); fileChannel = new MockFileChannel(randomAccessFile);
randomBytes = randomUnicodeOfLength(scaledRandomIntBetween(10, 100000)).getBytes("UTF-8"); randomBytes = randomUnicodeOfLength(scaledRandomIntBetween(10, 100000)).getBytes(StandardCharsets.UTF_8);
} }
@Override @Override

View file

@ -20,6 +20,7 @@ import org.junit.Assert;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays; import java.util.Arrays;
import java.util.Random; import java.util.Random;
@ -61,7 +62,7 @@ public class DeflateCompressedXContentTests extends ESTestCase {
} }
public void testDifferentCompressedRepresentation() throws Exception { public void testDifferentCompressedRepresentation() throws Exception {
byte[] b = "---\nf:abcdefghijabcdefghij".getBytes("UTF-8"); byte[] b = "---\nf:abcdefghijabcdefghij".getBytes(StandardCharsets.UTF_8);
BytesStreamOutput bout = new BytesStreamOutput(); BytesStreamOutput bout = new BytesStreamOutput();
try (OutputStream out = compressor.threadLocalOutputStream(bout)) { try (OutputStream out = compressor.threadLocalOutputStream(bout)) {
out.write(b); out.write(b);

View file

@ -236,7 +236,7 @@ public class LocallyMountedSecretsTests extends ESTestCase {
private void writeTestFile(Path path, String contents) throws IOException { private void writeTestFile(Path path, String contents) throws IOException {
Path tempFilePath = createTempFile(); Path tempFilePath = createTempFile();
Files.write(tempFilePath, contents.getBytes(StandardCharsets.UTF_8)); Files.writeString(tempFilePath, contents);
Files.createDirectories(path.getParent()); Files.createDirectories(path.getParent());
Files.move(tempFilePath, path, StandardCopyOption.ATOMIC_MOVE); Files.move(tempFilePath, path, StandardCopyOption.ATOMIC_MOVE);
} }

View file

@ -43,6 +43,7 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.math.BigInteger; import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path; import java.nio.file.Path;
import java.time.DayOfWeek; import java.time.DayOfWeek;
import java.time.Duration; import java.time.Duration;
@ -1192,7 +1193,7 @@ public abstract class BaseXContentTestCase extends ESTestCase {
} }
private static byte[] randomBytes() throws Exception { private static byte[] randomBytes() throws Exception {
return randomUnicodeOfLength(scaledRandomIntBetween(10, 1000)).getBytes("UTF-8"); return randomUnicodeOfLength(scaledRandomIntBetween(10, 1000)).getBytes(StandardCharsets.UTF_8);
} }
@FunctionalInterface @FunctionalInterface

View file

@ -92,7 +92,7 @@ public class XContentParserUtilsTests extends ESTestCase {
} }
public void testStoredFieldsValueBinary() throws IOException { public void testStoredFieldsValueBinary() throws IOException {
final byte[] value = randomUnicodeOfLength(scaledRandomIntBetween(10, 1000)).getBytes("UTF-8"); final byte[] value = randomUnicodeOfLength(scaledRandomIntBetween(10, 1000)).getBytes(StandardCharsets.UTF_8);
assertParseFieldsSimpleValue(value, (xcontentType, result) -> { assertParseFieldsSimpleValue(value, (xcontentType, result) -> {
if (xcontentType.canonical() == XContentType.JSON) { if (xcontentType.canonical() == XContentType.JSON) {
// binary values will be parsed back and returned as base64 strings when reading from json // binary values will be parsed back and returned as base64 strings when reading from json

View file

@ -167,7 +167,7 @@ public class XContentBuilderTests extends ESTestCase {
gen.writeStartObject(); gen.writeStartObject();
gen.writeStringField("name", "something"); gen.writeStringField("name", "something");
gen.flush(); gen.flush();
bos.write(", source : { test : \"value\" }".getBytes("UTF8")); bos.write(", source : { test : \"value\" }".getBytes(StandardCharsets.UTF_8));
gen.writeStringField("name2", "something2"); gen.writeStringField("name2", "something2");
gen.writeEndObject(); gen.writeEndObject();
gen.close(); gen.close();

View file

@ -848,7 +848,7 @@ public class NumberFieldTypeTests extends FieldTypeTestCase {
public void write(XContentBuilder b) throws IOException { public void write(XContentBuilder b) throws IOException {
if (value instanceof BigInteger) { if (value instanceof BigInteger) {
b.rawField("field", new ByteArrayInputStream(value.toString().getBytes("UTF-8")), XContentType.JSON); b.rawField("field", new ByteArrayInputStream(value.toString().getBytes(StandardCharsets.UTF_8)), XContentType.JSON);
} else { } else {
b.field("field", value); b.field("field", value);
} }

View file

@ -158,7 +158,7 @@ public final class Krb5kDcContainer extends DockerEnvironmentAwareTestContainer
} }
try { try {
krb5ConfFile = temporaryFolder.newFile("krb5.conf").toPath(); krb5ConfFile = temporaryFolder.newFile("krb5.conf").toPath();
Files.write(krb5ConfFile, getConf().getBytes(StandardCharsets.UTF_8)); Files.writeString(krb5ConfFile, getConf());
return krb5ConfFile; return krb5ConfFile;
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);

View file

@ -128,11 +128,11 @@ public class OldElasticsearch {
} }
Path tmp = Files.createTempFile(baseDir, null, null); Path tmp = Files.createTempFile(baseDir, null, null);
Files.write(tmp, Integer.toString(port).getBytes(StandardCharsets.UTF_8)); Files.writeString(tmp, Integer.toString(port));
Files.move(tmp, baseDir.resolve("ports"), StandardCopyOption.ATOMIC_MOVE); Files.move(tmp, baseDir.resolve("ports"), StandardCopyOption.ATOMIC_MOVE);
tmp = Files.createTempFile(baseDir, null, null); tmp = Files.createTempFile(baseDir, null, null);
Files.write(tmp, Integer.toString(pid).getBytes(StandardCharsets.UTF_8)); Files.writeString(tmp, Integer.toString(pid));
Files.move(tmp, baseDir.resolve("pid"), StandardCopyOption.ATOMIC_MOVE); Files.move(tmp, baseDir.resolve("pid"), StandardCopyOption.ATOMIC_MOVE);
} }
} }

View file

@ -15,6 +15,7 @@ import org.elasticsearch.xcontent.XContentType;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.math.BigInteger; import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
public class NumberTypeOutOfRangeSpec { public class NumberTypeOutOfRangeSpec {
@ -34,7 +35,7 @@ public class NumberTypeOutOfRangeSpec {
public void write(XContentBuilder b) throws IOException { public void write(XContentBuilder b) throws IOException {
if (value instanceof BigInteger) { if (value instanceof BigInteger) {
b.rawField("field", new ByteArrayInputStream(value.toString().getBytes("UTF-8")), XContentType.JSON); b.rawField("field", new ByteArrayInputStream(value.toString().getBytes(StandardCharsets.UTF_8)), XContentType.JSON);
} else { } else {
b.field("field", value); b.field("field", value);
} }

View file

@ -83,7 +83,7 @@ public class MockFSDirectoryFactory implements IndexStorePlugin.DirectoryFactory
} }
try { try {
BytesStreamOutput os = new BytesStreamOutput(); 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); CheckIndex.Status status = store.checkIndex(out);
out.flush(); out.flush();
if (status.clean == false) { if (status.clean == false) {

View file

@ -81,7 +81,7 @@ public class LicenseGenerationToolTests extends CommandTestCase {
TestUtils.LicenseSpec inputLicenseSpec = TestUtils.generateRandomLicenseSpec(License.VERSION_CURRENT); TestUtils.LicenseSpec inputLicenseSpec = TestUtils.generateRandomLicenseSpec(License.VERSION_CURRENT);
String licenseSpecString = TestUtils.generateLicenseSpecString(inputLicenseSpec); String licenseSpecString = TestUtils.generateLicenseSpecString(inputLicenseSpec);
Path licenseSpecFile = createTempFile(); Path licenseSpecFile = createTempFile();
Files.write(licenseSpecFile, licenseSpecString.getBytes(StandardCharsets.UTF_8)); Files.writeString(licenseSpecFile, licenseSpecString);
String output = execute( String output = execute(
"--publicKeyPath", "--publicKeyPath",
pubKeyPath.toString(), pubKeyPath.toString(),

View file

@ -15,7 +15,6 @@ import org.elasticsearch.license.License;
import org.elasticsearch.license.licensor.TestUtils; import org.elasticsearch.license.licensor.TestUtils;
import org.junit.Before; import org.junit.Before;
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;
@ -74,7 +73,7 @@ public class LicenseVerificationToolTests extends CommandTestCase {
final TimeValue oneHour = TimeValue.timeValueHours(1); final TimeValue oneHour = TimeValue.timeValueHours(1);
License signedLicense = TestUtils.generateSignedLicense(oneHour, pubKeyPath, priKeyPath); License signedLicense = TestUtils.generateSignedLicense(oneHour, pubKeyPath, priKeyPath);
Path licenseSpecFile = createTempFile(); Path licenseSpecFile = createTempFile();
Files.write(licenseSpecFile, TestUtils.dumpLicense(signedLicense).getBytes(StandardCharsets.UTF_8)); Files.writeString(licenseSpecFile, TestUtils.dumpLicense(signedLicense));
String output = execute("--publicKeyPath", pubKeyPath.toString(), "--licenseFile", licenseSpecFile.toString()); String output = execute("--publicKeyPath", pubKeyPath.toString(), "--licenseFile", licenseSpecFile.toString());
assertFalse(output, output.isEmpty()); assertFalse(output, output.isEmpty());
} }

View file

@ -103,7 +103,7 @@ public class AutoscalingFileSettingsIT extends AutoscalingIntegTestCase {
Path tempFilePath = createTempFile(); Path tempFilePath = createTempFile();
logger.info("--> writing JSON config to node {} with path {}", node, tempFilePath); logger.info("--> writing JSON config to node {} with path {}", node, tempFilePath);
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); Files.move(tempFilePath, fileSettingsService.watchedFile(), StandardCopyOption.ATOMIC_MOVE);
} }

View file

@ -192,7 +192,7 @@ public class NamedPipeHelperNoBootstrapTests extends LuceneTestCase {
} }
private static void writeLineToPipeUnix(String pipeName, String line) throws IOException { private static void writeLineToPipeUnix(String pipeName, String line) throws IOException {
Files.write(PathUtils.get(pipeName), (line + '\n').getBytes(StandardCharsets.UTF_8), StandardOpenOption.WRITE); Files.writeString(PathUtils.get(pipeName), line + '\n', StandardOpenOption.WRITE);
} }
private static void writeLineToPipeWindows(String pipeName, Pointer handle, String line) throws IOException { private static void writeLineToPipeWindows(String pipeName, Pointer handle, String line) throws IOException {

View file

@ -701,7 +701,7 @@ public class AggregationToJsonProcessorTests extends ESTestCase {
processor.process(aggregations); processor.process(aggregations);
processor.writeAllDocsCancellable(_timestamp -> false, outputStream); processor.writeAllDocsCancellable(_timestamp -> false, outputStream);
keyValuePairsWritten = processor.getKeyValueCount(); keyValuePairsWritten = processor.getKeyValueCount();
return outputStream.toString(StandardCharsets.UTF_8.name()); return outputStream.toString(StandardCharsets.UTF_8);
} }
private String aggToStringComposite(Set<String> fields, List<InternalComposite.InternalBucket> buckets) throws IOException { private String aggToStringComposite(Set<String> fields, List<InternalComposite.InternalBucket> buckets) throws IOException {

View file

@ -79,6 +79,6 @@ public class SearchHitToJsonProcessorTests extends ESTestCase {
hitProcessor.process(searchHits[i], new SourceSupplier(searchHits[i])); hitProcessor.process(searchHits[i], new SourceSupplier(searchHits[i]));
} }
} }
return outputStream.toString(StandardCharsets.UTF_8.name()); return outputStream.toString(StandardCharsets.UTF_8);
} }
} }

View file

@ -80,7 +80,7 @@ public class StateStreamerTests extends ESTestCase {
StateStreamer stateStreamer = new StateStreamer(clientBuilder.build()); StateStreamer stateStreamer = new StateStreamer(clientBuilder.build());
stateStreamer.restoreStateToStream(JOB_ID, modelSnapshot, stream); stateStreamer.restoreStateToStream(JOB_ID, modelSnapshot, stream);
String[] restoreData = stream.toString(StandardCharsets.UTF_8.name()).split("\0"); String[] restoreData = stream.toString(StandardCharsets.UTF_8).split("\0");
assertEquals(3, restoreData.length); assertEquals(3, restoreData.length);
assertEquals("{\"modName1\":\"modVal1\"}", restoreData[0]); assertEquals("{\"modName1\":\"modVal1\"}", restoreData[0]);
assertEquals("{\"modName2\":\"modVal2\"}", restoreData[1]); assertEquals("{\"modName2\":\"modVal2\"}", restoreData[1]);

View file

@ -77,7 +77,7 @@ public class NativeControllerTests extends ESTestCase {
assertEquals( assertEquals(
"1\tstart\tmy_process\t--arg1\t--arg2=42\t--arg3=something with spaces\n", "1\tstart\tmy_process\t--arg1\t--arg2=42\t--arg3=something with spaces\n",
commandStream.toString(StandardCharsets.UTF_8.name()) commandStream.toString(StandardCharsets.UTF_8)
); );
mockNativeProcessLoggingStreamEnds.countDown(); mockNativeProcessLoggingStreamEnds.countDown();
@ -115,7 +115,7 @@ public class NativeControllerTests extends ESTestCase {
assertEquals( assertEquals(
"1\tstart\tmy_process\t--arg1\t--arg2=666\t--arg3=something different with spaces\n", "1\tstart\tmy_process\t--arg1\t--arg2=666\t--arg3=something different with spaces\n",
commandStream.toString(StandardCharsets.UTF_8.name()) commandStream.toString(StandardCharsets.UTF_8)
); );
assertEquals("ML controller failed to execute command [1]: [some problem]", e.getMessage()); assertEquals("ML controller failed to execute command [1]: [some problem]", e.getMessage());

View file

@ -52,6 +52,7 @@ import java.lang.management.LockInfo;
import java.lang.management.ManagementFactory; import java.lang.management.ManagementFactory;
import java.lang.management.MonitorInfo; import java.lang.management.MonitorInfo;
import java.lang.management.ThreadInfo; import java.lang.management.ThreadInfo;
import java.nio.charset.StandardCharsets;
import java.time.Instant; import java.time.Instant;
import java.time.ZoneOffset; import java.time.ZoneOffset;
import java.util.Arrays; import java.util.Arrays;
@ -130,7 +131,7 @@ public class MonitoringIT extends ESSingleNodeTestCase {
final MonitoringBulkResponse bulkResponse = new MonitoringBulkRequestBuilder(client()).add( final MonitoringBulkResponse bulkResponse = new MonitoringBulkRequestBuilder(client()).add(
system, system,
new BytesArray(createBulkEntity().getBytes("UTF-8")), new BytesArray(createBulkEntity().getBytes(StandardCharsets.UTF_8)),
XContentType.JSON, XContentType.JSON,
System.currentTimeMillis(), System.currentTimeMillis(),
interval.millis() interval.millis()

View file

@ -280,7 +280,7 @@ public class FileUserRolesStoreTests extends ESTestCase {
private Path writeUsersRoles(String input) throws Exception { private Path writeUsersRoles(String input) throws Exception {
Path file = getUsersRolesPath(); Path file = getUsersRolesPath();
Files.write(file, input.getBytes(StandardCharsets.UTF_8)); Files.writeString(file, input);
return file; return file;
} }
@ -292,7 +292,7 @@ public class FileUserRolesStoreTests extends ESTestCase {
private void assertInvalidInputIsSilentlyIgnored(String input) throws Exception { private void assertInvalidInputIsSilentlyIgnored(String input) throws Exception {
Path file = createTempFile(); Path file = createTempFile();
Files.write(file, input.getBytes(StandardCharsets.UTF_8)); Files.writeString(file, input);
Map<String, String[]> usersRoles = FileUserRolesStore.parseFile(file, null); Map<String, String[]> usersRoles = FileUserRolesStore.parseFile(file, null);
String reason = Strings.format("Expected userRoles to be empty, but was %s", usersRoles.keySet()); String reason = Strings.format("Expected userRoles to be empty, but was %s", usersRoles.keySet());
assertThat(reason, usersRoles.keySet(), hasSize(0)); assertThat(reason, usersRoles.keySet(), hasSize(0));

View file

@ -59,7 +59,6 @@ import org.opensaml.security.x509.X509Credential;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
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;
@ -145,7 +144,7 @@ public class SamlRealmTests extends SamlTestCase {
public void testReadIdpMetadataFromHttps() throws Exception { public void testReadIdpMetadataFromHttps() throws Exception {
final Path path = getDataPath("idp1.xml"); final Path path = getDataPath("idp1.xml");
final String body = new String(Files.readAllBytes(path), StandardCharsets.UTF_8); final String body = Files.readString(path);
TestsSSLService sslService = buildTestSslService(); TestsSSLService sslService = buildTestSslService();
try (MockWebServer proxyServer = new MockWebServer(sslService.sslContext("xpack.security.http.ssl"), false)) { try (MockWebServer proxyServer = new MockWebServer(sslService.sslContext("xpack.security.http.ssl"), false)) {
proxyServer.start(); proxyServer.start();
@ -204,7 +203,7 @@ public class SamlRealmTests extends SamlTestCase {
public void testRetryFailedHttpsMetadata() throws Exception { public void testRetryFailedHttpsMetadata() throws Exception {
final Path path = getDataPath("idp1.xml"); final Path path = getDataPath("idp1.xml");
final String body = new String(Files.readAllBytes(path), StandardCharsets.UTF_8); final String body = Files.readString(path);
TestsSSLService sslService = buildTestSslService(); TestsSSLService sslService = buildTestSslService();
doTestReloadFailedHttpsMetadata(body, sslService, true); doTestReloadFailedHttpsMetadata(body, sslService, true);
doTestReloadFailedHttpsMetadata(body, sslService, false); doTestReloadFailedHttpsMetadata(body, sslService, false);

View file

@ -491,7 +491,7 @@ public class FileOperatorUsersStoreTests extends ESTestCase {
private Path writeOperatorUsers(String input) throws IOException { private Path writeOperatorUsers(String input) throws IOException {
Path file = getOperatorUsersPath(); Path file = getOperatorUsersPath();
Files.write(file, input.getBytes(StandardCharsets.UTF_8)); Files.writeString(file, input);
return file; return file;
} }

View file

@ -164,7 +164,7 @@ public class SLMFileSettingsIT extends AbstractSnapshotIntegTestCase {
Files.createDirectories(fileSettingsService.watchedFileDir()); Files.createDirectories(fileSettingsService.watchedFileDir());
Path tempFilePath = createTempFile(); Path tempFilePath = createTempFile();
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); Files.move(tempFilePath, fileSettingsService.watchedFile(), StandardCopyOption.ATOMIC_MOVE);
} }

View file

@ -68,7 +68,7 @@ public class TransformIntegrationTests extends AbstractWatcherIntegrationTestCas
// When using the MockScriptPlugin we can map File scripts to inline scripts: // When using the MockScriptPlugin we can map File scripts to inline scripts:
// the name of the file script is used in test method while the source of the file script // the name of the file script is used in test method while the source of the file script
// must match a predefined script from CustomScriptPlugin.pluginScripts() method // must match a predefined script from CustomScriptPlugin.pluginScripts() method
Files.write(scripts.resolve("my-script.mockscript"), "['key3' : ctx.payload.key1 + ctx.payload.key2]".getBytes("UTF-8")); Files.writeString(scripts.resolve("my-script.mockscript"), "['key3' : ctx.payload.key1 + ctx.payload.key2]");
} catch (final IOException e) { } catch (final IOException e) {
throw new UncheckedIOException(e); throw new UncheckedIOException(e);
} }

View file

@ -25,7 +25,6 @@ import java.io.IOException;
import java.net.DatagramSocket; import java.net.DatagramSocket;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.ServerSocket; import java.net.ServerSocket;
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.AccessController; import java.security.AccessController;
@ -154,7 +153,7 @@ public class SimpleKdcLdapServer {
+ "admin_pw=secret\n" + "admin_pw=secret\n"
+ "base_dn=" + "base_dn="
+ baseDn; + baseDn;
Files.write(this.workDir.resolve("backend.conf"), backendConf.getBytes(StandardCharsets.UTF_8)); Files.writeString(this.workDir.resolve("backend.conf"), backendConf);
assert Files.exists(this.workDir.resolve("backend.conf")); assert Files.exists(this.workDir.resolve("backend.conf"));
} }

View file

@ -15,7 +15,6 @@ import org.elasticsearch.test.ESTestCase;
import java.io.IOException; import java.io.IOException;
import java.io.UncheckedIOException; import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem; import java.nio.file.FileSystem;
import java.nio.file.FileVisitResult; import java.nio.file.FileVisitResult;
import java.nio.file.Files; import java.nio.file.Files;
@ -52,7 +51,7 @@ public class SecurityFilesTests extends ESTestCase {
boolean supportsPosixPermissions = Environment.getFileStore(path).supportsFileAttributeView(PosixFileAttributeView.class); boolean supportsPosixPermissions = Environment.getFileStore(path).supportsFileAttributeView(PosixFileAttributeView.class);
assumeTrue("Ignoring because posix file attributes are not supported", supportsPosixPermissions); assumeTrue("Ignoring because posix file attributes are not supported", supportsPosixPermissions);
Files.write(path, "foo".getBytes(StandardCharsets.UTF_8)); Files.writeString(path, "foo");
Set<PosixFilePermission> perms = Sets.newHashSet(OWNER_READ, OWNER_WRITE); Set<PosixFilePermission> perms = Sets.newHashSet(OWNER_READ, OWNER_WRITE);
if (randomBoolean()) perms.add(OWNER_EXECUTE); if (randomBoolean()) perms.add(OWNER_EXECUTE);
@ -78,7 +77,7 @@ public class SecurityFilesTests extends ESTestCase {
public void testFailure() throws IOException { public void testFailure() throws IOException {
final Path path = createTempFile("existing", "file"); final Path path = createTempFile("existing", "file");
Files.write(path, "foo".getBytes(StandardCharsets.UTF_8)); Files.writeString(path, "foo");
final Visitor innerVisitor = new Visitor(path); final Visitor innerVisitor = new Visitor(path);
final RuntimeException re = expectThrows( final RuntimeException re = expectThrows(
@ -138,8 +137,8 @@ public class SecurityFilesTests extends ESTestCase {
try (FileSystem fs = Jimfs.newFileSystem(jimFsConfiguration)) { try (FileSystem fs = Jimfs.newFileSystem(jimFsConfiguration)) {
Path path = fs.getPath("foo"); Path path = fs.getPath("foo");
Path tempPath = fs.getPath("bar"); Path tempPath = fs.getPath("bar");
Files.write(path, "foo".getBytes(StandardCharsets.UTF_8)); Files.writeString(path, "foo");
Files.write(tempPath, "bar".getBytes(StandardCharsets.UTF_8)); Files.writeString(tempPath, "bar");
PosixFileAttributeView view = Files.getFileAttributeView(path, PosixFileAttributeView.class); PosixFileAttributeView view = Files.getFileAttributeView(path, PosixFileAttributeView.class);
view.setGroup(fs.getUserPrincipalLookupService().lookupPrincipalByGroupName(randomAlphaOfLength(10))); view.setGroup(fs.getUserPrincipalLookupService().lookupPrincipalByGroupName(randomAlphaOfLength(10)));