From 6707f8b727da1c7ee9eb0562e62d6a56e840c2cc Mon Sep 17 00:00:00 2001 From: Armin Braun Date: Fri, 21 Mar 2025 17:17:45 +0100 Subject: [PATCH] Cleanup missing use of StandardCharsets 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. --- .../gradle/internal/ConcatFilesTask.java | 15 +++++++++------ .../gradle/internal/DependenciesInfoTask.java | 2 +- .../internal/doc/RestTestsFromDocSnippetTask.java | 3 ++- .../internal/precommit/FilePermissionsTask.java | 2 +- .../internal/precommit/ForbiddenPatternsTask.java | 2 +- .../internal/precommit/ThirdPartyAuditTask.java | 4 ++-- .../gradle/internal/ConcatFilesTaskTests.java | 4 ++-- .../precommit/DependencyLicensesTaskTests.java | 2 +- .../precommit/FilePermissionsTaskTests.java | 6 +++--- .../java/org/elasticsearch/gradle/LoggedExec.java | 7 +------ .../gradle/testclusters/ElasticsearchCluster.java | 3 +-- .../plugins/cli/InstallPluginActionTests.java | 10 +++++----- .../entitlement/qa/test/NioFilesActions.java | 2 +- .../ingest/common/URLDecodeProcessorTests.java | 2 +- .../script/mustache/MustacheTests.java | 2 +- .../painless/ContextApiSpecGenerator.java | 4 ++-- .../netty4/Netty4HttpServerTransportTests.java | 5 ++--- .../icu/IcuCollationTokenFilterFactory.java | 4 ++-- .../AnnotatedTextHighlighterTests.java | 3 ++- .../bootstrap/SpawnerNoBootstrapTests.java | 3 +-- .../elasticsearch/packaging/util/FileUtils.java | 2 +- .../index/store/CorruptedFileIT.java | 2 +- .../ingest/IngestFileSettingsIT.java | 2 +- .../readiness/ReadinessClusterIT.java | 3 +-- .../aggregations/metrics/ScriptedMetricIT.java | 11 ++++------- .../search/fields/SearchFieldsIT.java | 8 ++++++-- .../org/elasticsearch/index/shard/IndexShard.java | 2 +- .../main/java/org/elasticsearch/node/Node.java | 4 ++-- .../org/elasticsearch/common/ChannelsTests.java | 3 ++- .../compress/DeflateCompressedXContentTests.java | 3 ++- .../settings/LocallyMountedSecretsTests.java | 2 +- .../common/xcontent/BaseXContentTestCase.java | 3 ++- .../common/xcontent/XContentParserUtilsTests.java | 2 +- .../xcontent/builder/XContentBuilderTests.java | 2 +- .../index/mapper/NumberFieldTypeTests.java | 2 +- .../test/fixtures/krb5kdc/Krb5kDcContainer.java | 2 +- .../src/main/java/oldes/OldElasticsearch.java | 4 ++-- .../index/mapper/NumberTypeOutOfRangeSpec.java | 3 ++- .../test/store/MockFSDirectoryFactory.java | 2 +- .../tools/LicenseGenerationToolTests.java | 2 +- .../tools/LicenseVerificationToolTests.java | 3 +-- .../autoscaling/AutoscalingFileSettingsIT.java | 2 +- .../ml/utils/NamedPipeHelperNoBootstrapTests.java | 2 +- .../AggregationToJsonProcessorTests.java | 2 +- .../scroll/SearchHitToJsonProcessorTests.java | 2 +- .../ml/job/persistence/StateStreamerTests.java | 2 +- .../xpack/ml/process/NativeControllerTests.java | 4 ++-- .../monitoring/integration/MonitoringIT.java | 3 ++- .../authc/file/FileUserRolesStoreTests.java | 4 ++-- .../xpack/security/authc/saml/SamlRealmTests.java | 5 ++--- .../operator/FileOperatorUsersStoreTests.java | 2 +- .../xpack/slm/SLMFileSettingsIT.java | 2 +- .../transform/TransformIntegrationTests.java | 2 +- .../authc/kerberos/SimpleKdcLdapServer.java | 3 +-- .../security/support/SecurityFilesTests.java | 9 ++++----- 55 files changed, 97 insertions(+), 99 deletions(-) diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/ConcatFilesTask.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/ConcatFilesTask.java index c84b52c612256..1c5e090e6ece3 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/ConcatFilesTask.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/ConcatFilesTask.java @@ -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; @@ -85,7 +87,7 @@ public void setAdditionalLines(List 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 @@ -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 + ); } } diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/DependenciesInfoTask.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/DependenciesInfoTask.java index 3ccae89139a12..fcea897212b43 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/DependenciesInfoTask.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/DependenciesInfoTask.java @@ -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 diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/doc/RestTestsFromDocSnippetTask.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/doc/RestTestsFromDocSnippetTask.java index cc15d4e9e4e90..945e5d9f404e4 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/doc/RestTestsFromDocSnippetTask.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/doc/RestTestsFromDocSnippetTask.java @@ -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; @@ -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); diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/precommit/FilePermissionsTask.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/precommit/FilePermissionsTask.java index 479b6f431b867..a3811139d05fa 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/precommit/FilePermissionsTask.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/precommit/FilePermissionsTask.java @@ -106,7 +106,7 @@ public void checkInvalidPermissions() throws IOException { } outputMarker.getParentFile().mkdirs(); - Files.write(outputMarker.toPath(), "done".getBytes("UTF-8")); + Files.writeString(outputMarker.toPath(), "done"); } @OutputFile diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/precommit/ForbiddenPatternsTask.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/precommit/ForbiddenPatternsTask.java index d84a72b1a6d9d..198fec7f234a8 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/precommit/ForbiddenPatternsTask.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/precommit/ForbiddenPatternsTask.java @@ -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 diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/precommit/ThirdPartyAuditTask.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/precommit/ThirdPartyAuditTask.java index 0c86a2d030741..1acdc794ee0d2 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/precommit/ThirdPartyAuditTask.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/precommit/ThirdPartyAuditTask.java @@ -364,7 +364,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); @@ -397,7 +397,7 @@ private Set 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"))); } diff --git a/build-tools-internal/src/test/java/org/elasticsearch/gradle/internal/ConcatFilesTaskTests.java b/build-tools-internal/src/test/java/org/elasticsearch/gradle/internal/ConcatFilesTaskTests.java index bb2ba43329731..bcbc1333709dc 100644 --- a/build-tools-internal/src/test/java/org/elasticsearch/gradle/internal/ConcatFilesTaskTests.java +++ b/build-tools-internal/src/test/java/org/elasticsearch/gradle/internal/ConcatFilesTaskTests.java @@ -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())); diff --git a/build-tools-internal/src/test/java/org/elasticsearch/gradle/internal/precommit/DependencyLicensesTaskTests.java b/build-tools-internal/src/test/java/org/elasticsearch/gradle/internal/precommit/DependencyLicensesTaskTests.java index 936a8379a5621..d09101a557ebb 100644 --- a/build-tools-internal/src/test/java/org/elasticsearch/gradle/internal/precommit/DependencyLicensesTaskTests.java +++ b/build-tools-internal/src/test/java/org/elasticsearch/gradle/internal/precommit/DependencyLicensesTaskTests.java @@ -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 createDependencyLicensesTask(Project project) { diff --git a/build-tools-internal/src/test/java/org/elasticsearch/gradle/internal/precommit/FilePermissionsTaskTests.java b/build-tools-internal/src/test/java/org/elasticsearch/gradle/internal/precommit/FilePermissionsTaskTests.java index 168b2da109852..165a6440c8517 100644 --- a/build-tools-internal/src/test/java/org/elasticsearch/gradle/internal/precommit/FilePermissionsTaskTests.java +++ b/build-tools-internal/src/test/java/org/elasticsearch/gradle/internal/precommit/FilePermissionsTaskTests.java @@ -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; @@ -61,7 +61,7 @@ public void testCheckPermissionsWhenNoFileExists() throws Exception { filePermissionsTask.checkInvalidPermissions(); File outputMarker = new File(project.getBuildDir(), "markers/filePermissions"); - List result = Files.readAllLines(outputMarker.toPath(), Charset.forName("UTF-8")); + List result = Files.readAllLines(outputMarker.toPath(), StandardCharsets.UTF_8); assertEquals("done", result.get(0)); } @@ -80,7 +80,7 @@ public void testCheckPermissionsWhenNoExecutableFileExists() throws Exception { filePermissionsTask.checkInvalidPermissions(); File outputMarker = new File(project.getBuildDir(), "markers/filePermissions"); - List result = Files.readAllLines(outputMarker.toPath(), Charset.forName("UTF-8")); + List result = Files.readAllLines(outputMarker.toPath(), StandardCharsets.UTF_8); assertEquals("done", result.get(0)); file.delete(); diff --git a/build-tools/src/main/java/org/elasticsearch/gradle/LoggedExec.java b/build-tools/src/main/java/org/elasticsearch/gradle/LoggedExec.java index 28018b4c50abe..1f289fd2af434 100644 --- a/build-tools/src/main/java/org/elasticsearch/gradle/LoggedExec.java +++ b/build-tools/src/main/java/org/elasticsearch/gradle/LoggedExec.java @@ -38,7 +38,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; @@ -193,11 +192,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(); diff --git a/build-tools/src/main/java/org/elasticsearch/gradle/testclusters/ElasticsearchCluster.java b/build-tools/src/main/java/org/elasticsearch/gradle/testclusters/ElasticsearchCluster.java index 77393fe16b4c2..7b8fd5bbb4c29 100644 --- a/build-tools/src/main/java/org/elasticsearch/gradle/testclusters/ElasticsearchCluster.java +++ b/build-tools/src/main/java/org/elasticsearch/gradle/testclusters/ElasticsearchCluster.java @@ -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; @@ -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); } diff --git a/distribution/tools/plugin-cli/src/test/java/org/elasticsearch/plugins/cli/InstallPluginActionTests.java b/distribution/tools/plugin-cli/src/test/java/org/elasticsearch/plugins/cli/InstallPluginActionTests.java index 67c053e5caec3..a741b629c535d 100644 --- a/distribution/tools/plugin-cli/src/test/java/org/elasticsearch/plugins/cli/InstallPluginActionTests.java +++ b/distribution/tools/plugin-cli/src/test/java/org/elasticsearch/plugins/cli/InstallPluginActionTests.java @@ -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) @@ -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); @@ -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; diff --git a/libs/entitlement/qa/entitlement-test-plugin/src/main/java/org/elasticsearch/entitlement/qa/test/NioFilesActions.java b/libs/entitlement/qa/entitlement-test-plugin/src/main/java/org/elasticsearch/entitlement/qa/test/NioFilesActions.java index 8f5ba8cadfb53..d06bb81d04bfb 100644 --- a/libs/entitlement/qa/entitlement-test-plugin/src/main/java/org/elasticsearch/entitlement/qa/test/NioFilesActions.java +++ b/libs/entitlement/qa/entitlement-test-plugin/src/main/java/org/elasticsearch/entitlement/qa/test/NioFilesActions.java @@ -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) diff --git a/modules/ingest-common/src/test/java/org/elasticsearch/ingest/common/URLDecodeProcessorTests.java b/modules/ingest-common/src/test/java/org/elasticsearch/ingest/common/URLDecodeProcessorTests.java index 1c43c5c056e92..a758da6605ab2 100644 --- a/modules/ingest-common/src/test/java/org/elasticsearch/ingest/common/URLDecodeProcessorTests.java +++ b/modules/ingest-common/src/test/java/org/elasticsearch/ingest/common/URLDecodeProcessorTests.java @@ -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; diff --git a/modules/lang-mustache/src/test/java/org/elasticsearch/script/mustache/MustacheTests.java b/modules/lang-mustache/src/test/java/org/elasticsearch/script/mustache/MustacheTests.java index 335cfe91df87d..7d31d6570c34e 100644 --- a/modules/lang-mustache/src/test/java/org/elasticsearch/script/mustache/MustacheTests.java +++ b/modules/lang-mustache/src/test/java/org/elasticsearch/script/mustache/MustacheTests.java @@ -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)) ); } diff --git a/modules/lang-painless/src/doc/java/org/elasticsearch/painless/ContextApiSpecGenerator.java b/modules/lang-painless/src/doc/java/org/elasticsearch/painless/ContextApiSpecGenerator.java index ef5cbd5c2a03a..5509c7eb966f9 100644 --- a/modules/lang-painless/src/doc/java/org/elasticsearch/painless/ContextApiSpecGenerator.java +++ b/modules/lang-painless/src/doc/java/org/elasticsearch/painless/ContextApiSpecGenerator.java @@ -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 ) ) { @@ -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 ) ) { diff --git a/modules/transport-netty4/src/test/java/org/elasticsearch/http/netty4/Netty4HttpServerTransportTests.java b/modules/transport-netty4/src/test/java/org/elasticsearch/http/netty4/Netty4HttpServerTransportTests.java index 1d39b993cef92..222d88642050a 100644 --- a/modules/transport-netty4/src/test/java/org/elasticsearch/http/netty4/Netty4HttpServerTransportTests.java +++ b/modules/transport-netty4/src/test/java/org/elasticsearch/http/netty4/Netty4HttpServerTransportTests.java @@ -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; @@ -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 { diff --git a/plugins/analysis-icu/src/main/java/org/elasticsearch/plugin/analysis/icu/IcuCollationTokenFilterFactory.java b/plugins/analysis-icu/src/main/java/org/elasticsearch/plugin/analysis/icu/IcuCollationTokenFilterFactory.java index 6854984c49c26..5a46217c6d467 100644 --- a/plugins/analysis-icu/src/main/java/org/elasticsearch/plugin/analysis/icu/IcuCollationTokenFilterFactory.java +++ b/plugins/analysis-icu/src/main/java/org/elasticsearch/plugin/analysis/icu/IcuCollationTokenFilterFactory.java @@ -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; @@ -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; } diff --git a/plugins/mapper-annotated-text/src/test/java/org/elasticsearch/index/mapper/annotatedtext/AnnotatedTextHighlighterTests.java b/plugins/mapper-annotated-text/src/test/java/org/elasticsearch/index/mapper/annotatedtext/AnnotatedTextHighlighterTests.java index 53bb87bdf0acb..d96c5cf8d0ea7 100644 --- a/plugins/mapper-annotated-text/src/test/java/org/elasticsearch/index/mapper/annotatedtext/AnnotatedTextHighlighterTests.java +++ b/plugins/mapper-annotated-text/src/test/java/org/elasticsearch/index/mapper/annotatedtext/AnnotatedTextHighlighterTests.java @@ -45,6 +45,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; @@ -167,7 +168,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 diff --git a/qa/no-bootstrap-tests/src/test/java/org/elasticsearch/bootstrap/SpawnerNoBootstrapTests.java b/qa/no-bootstrap-tests/src/test/java/org/elasticsearch/bootstrap/SpawnerNoBootstrapTests.java index 5c26a744b2fbf..cb70543cc952a 100644 --- a/qa/no-bootstrap-tests/src/test/java/org/elasticsearch/bootstrap/SpawnerNoBootstrapTests.java +++ b/qa/no-bootstrap-tests/src/test/java/org/elasticsearch/bootstrap/SpawnerNoBootstrapTests.java @@ -27,7 +27,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; @@ -270,7 +269,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 perms = new HashSet<>(); diff --git a/qa/packaging/src/test/java/org/elasticsearch/packaging/util/FileUtils.java b/qa/packaging/src/test/java/org/elasticsearch/packaging/util/FileUtils.java index 2b8fb0d4e6021..925a8e71a2aab 100644 --- a/qa/packaging/src/test/java/org/elasticsearch/packaging/util/FileUtils.java +++ b/qa/packaging/src/test/java/org/elasticsearch/packaging/util/FileUtils.java @@ -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)); diff --git a/server/src/internalClusterTest/java/org/elasticsearch/index/store/CorruptedFileIT.java b/server/src/internalClusterTest/java/org/elasticsearch/index/store/CorruptedFileIT.java index 17ca4be747cb2..60de9d1e182d6 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/index/store/CorruptedFileIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/index/store/CorruptedFileIT.java @@ -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) { diff --git a/server/src/internalClusterTest/java/org/elasticsearch/ingest/IngestFileSettingsIT.java b/server/src/internalClusterTest/java/org/elasticsearch/ingest/IngestFileSettingsIT.java index aba9914097deb..ef475b0d722e5 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/ingest/IngestFileSettingsIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/ingest/IngestFileSettingsIT.java @@ -129,7 +129,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); } diff --git a/server/src/internalClusterTest/java/org/elasticsearch/readiness/ReadinessClusterIT.java b/server/src/internalClusterTest/java/org/elasticsearch/readiness/ReadinessClusterIT.java index 11d9466aaf9db..cf8c377ad3410 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/readiness/ReadinessClusterIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/readiness/ReadinessClusterIT.java @@ -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; @@ -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)); } diff --git a/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/metrics/ScriptedMetricIT.java b/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/metrics/ScriptedMetricIT.java index 4c8fed2c16ddc..7851dd2b271d3 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/metrics/ScriptedMetricIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/metrics/ScriptedMetricIT.java @@ -332,13 +332,10 @@ public void setUp() throws Exception { // 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 // must match a predefined script from CustomScriptPlugin.pluginScripts() method - Files.write(scripts.resolve("init_script.mockscript"), "vars.multiplier = 3".getBytes("UTF-8")); - Files.write(scripts.resolve("map_script.mockscript"), "state.list.add(vars.multiplier)".getBytes("UTF-8")); - Files.write(scripts.resolve("combine_script.mockscript"), "sum state values as a new aggregation".getBytes("UTF-8")); - Files.write( - scripts.resolve("reduce_script.mockscript"), - "sum all states (lists) values as a new aggregation".getBytes("UTF-8") - ); + Files.writeString(scripts.resolve("init_script.mockscript"), "vars.multiplier = 3"); + Files.writeString(scripts.resolve("map_script.mockscript"), "state.list.add(vars.multiplier)"); + Files.writeString(scripts.resolve("combine_script.mockscript"), "sum state values as a new aggregation"); + Files.writeString(scripts.resolve("reduce_script.mockscript"), "sum all states (lists) values as a new aggregation"); } catch (IOException e) { throw new RuntimeException("failed to create scripts"); } diff --git a/server/src/internalClusterTest/java/org/elasticsearch/search/fields/SearchFieldsIT.java b/server/src/internalClusterTest/java/org/elasticsearch/search/fields/SearchFieldsIT.java index 0310af3685e3e..bec4e0a2d6970 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/search/fields/SearchFieldsIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/search/fields/SearchFieldsIT.java @@ -37,6 +37,7 @@ import org.elasticsearch.xcontent.XContentFactory; import org.elasticsearch.xcontent.XContentType; +import java.nio.charset.StandardCharsets; import java.time.Instant; import java.time.ZoneOffset; import java.time.ZonedDateTime; @@ -612,7 +613,7 @@ public void testStoredFieldsWithoutSource() throws Exception { .field("double_field", 6.0d) .field("date_field", DateFormatter.forPattern("date_optional_time").format(date)) .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() ) .get(); @@ -661,7 +662,10 @@ public void testStoredFieldsWithoutSource() throws Exception { String dateTime = DateFormatter.forPattern("date_optional_time").format(date); 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("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))) + ); } ); } diff --git a/server/src/main/java/org/elasticsearch/index/shard/IndexShard.java b/server/src/main/java/org/elasticsearch/index/shard/IndexShard.java index 511e06d6884ee..1cfc7fab9fc83 100644 --- a/server/src/main/java/org/elasticsearch/index/shard/IndexShard.java +++ b/server/src/main/java/org/elasticsearch/index/shard/IndexShard.java @@ -3280,7 +3280,7 @@ private void doCheckIndex() throws IOException { } else { // full checkindex 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); out.flush(); if (status.clean == false) { diff --git a/server/src/main/java/org/elasticsearch/node/Node.java b/server/src/main/java/org/elasticsearch/node/Node.java index f4b390c9863f2..30a32b07f15f0 100644 --- a/server/src/main/java/org/elasticsearch/node/Node.java +++ b/server/src/main/java/org/elasticsearch/node/Node.java @@ -92,7 +92,7 @@ import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; -import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; @@ -653,7 +653,7 @@ protected void validateNodeBeforeAcceptingRequests( */ private void writePortsFile(String type, BoundTransportAddress boundAddress) { 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()) { InetAddress inetAddress = InetAddress.getByName(address.getAddress()); writer.write(NetworkAddress.format(new InetSocketAddress(inetAddress, address.getPort())) + "\n"); diff --git a/server/src/test/java/org/elasticsearch/common/ChannelsTests.java b/server/src/test/java/org/elasticsearch/common/ChannelsTests.java index af280d9aa67e5..c00bf708cb84b 100644 --- a/server/src/test/java/org/elasticsearch/common/ChannelsTests.java +++ b/server/src/test/java/org/elasticsearch/common/ChannelsTests.java @@ -25,6 +25,7 @@ import java.nio.channels.FileLock; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; +import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.StandardOpenOption; @@ -42,7 +43,7 @@ public void setUp() throws Exception { Path tmpFile = createTempFile(); FileChannel randomAccessFile = FileChannel.open(tmpFile, StandardOpenOption.READ, StandardOpenOption.WRITE); fileChannel = new MockFileChannel(randomAccessFile); - randomBytes = randomUnicodeOfLength(scaledRandomIntBetween(10, 100000)).getBytes("UTF-8"); + randomBytes = randomUnicodeOfLength(scaledRandomIntBetween(10, 100000)).getBytes(StandardCharsets.UTF_8); } @Override diff --git a/server/src/test/java/org/elasticsearch/common/compress/DeflateCompressedXContentTests.java b/server/src/test/java/org/elasticsearch/common/compress/DeflateCompressedXContentTests.java index 703d222017b68..72f8017950674 100644 --- a/server/src/test/java/org/elasticsearch/common/compress/DeflateCompressedXContentTests.java +++ b/server/src/test/java/org/elasticsearch/common/compress/DeflateCompressedXContentTests.java @@ -20,6 +20,7 @@ import java.io.IOException; import java.io.OutputStream; +import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Random; @@ -61,7 +62,7 @@ public void testRandom() throws IOException { } public void testDifferentCompressedRepresentation() throws Exception { - byte[] b = "---\nf:abcdefghijabcdefghij".getBytes("UTF-8"); + byte[] b = "---\nf:abcdefghijabcdefghij".getBytes(StandardCharsets.UTF_8); BytesStreamOutput bout = new BytesStreamOutput(); try (OutputStream out = compressor.threadLocalOutputStream(bout)) { out.write(b); diff --git a/server/src/test/java/org/elasticsearch/common/settings/LocallyMountedSecretsTests.java b/server/src/test/java/org/elasticsearch/common/settings/LocallyMountedSecretsTests.java index 0c2dc68a01464..893df1b782773 100644 --- a/server/src/test/java/org/elasticsearch/common/settings/LocallyMountedSecretsTests.java +++ b/server/src/test/java/org/elasticsearch/common/settings/LocallyMountedSecretsTests.java @@ -236,7 +236,7 @@ public void testResolveSecretsFile() { private void writeTestFile(Path path, String contents) throws IOException { Path tempFilePath = createTempFile(); - Files.write(tempFilePath, contents.getBytes(StandardCharsets.UTF_8)); + Files.writeString(tempFilePath, contents); Files.createDirectories(path.getParent()); Files.move(tempFilePath, path, StandardCopyOption.ATOMIC_MOVE); } diff --git a/server/src/test/java/org/elasticsearch/common/xcontent/BaseXContentTestCase.java b/server/src/test/java/org/elasticsearch/common/xcontent/BaseXContentTestCase.java index b3af430cc43e2..20f33b9f71d19 100644 --- a/server/src/test/java/org/elasticsearch/common/xcontent/BaseXContentTestCase.java +++ b/server/src/test/java/org/elasticsearch/common/xcontent/BaseXContentTestCase.java @@ -43,6 +43,7 @@ import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; +import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.time.DayOfWeek; import java.time.Duration; @@ -1192,7 +1193,7 @@ private static void assertResult(String expected, Builder builder) throws IOExce } private static byte[] randomBytes() throws Exception { - return randomUnicodeOfLength(scaledRandomIntBetween(10, 1000)).getBytes("UTF-8"); + return randomUnicodeOfLength(scaledRandomIntBetween(10, 1000)).getBytes(StandardCharsets.UTF_8); } @FunctionalInterface diff --git a/server/src/test/java/org/elasticsearch/common/xcontent/XContentParserUtilsTests.java b/server/src/test/java/org/elasticsearch/common/xcontent/XContentParserUtilsTests.java index 4573e71d2c3f8..a0e1c73c08e46 100644 --- a/server/src/test/java/org/elasticsearch/common/xcontent/XContentParserUtilsTests.java +++ b/server/src/test/java/org/elasticsearch/common/xcontent/XContentParserUtilsTests.java @@ -92,7 +92,7 @@ public void testStoredFieldsValueBoolean() 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) -> { if (xcontentType.canonical() == XContentType.JSON) { // binary values will be parsed back and returned as base64 strings when reading from json diff --git a/server/src/test/java/org/elasticsearch/common/xcontent/builder/XContentBuilderTests.java b/server/src/test/java/org/elasticsearch/common/xcontent/builder/XContentBuilderTests.java index 575382c7fb441..30cf982c72674 100644 --- a/server/src/test/java/org/elasticsearch/common/xcontent/builder/XContentBuilderTests.java +++ b/server/src/test/java/org/elasticsearch/common/xcontent/builder/XContentBuilderTests.java @@ -167,7 +167,7 @@ public void testWritingBinaryToStream() throws Exception { gen.writeStartObject(); gen.writeStringField("name", "something"); gen.flush(); - bos.write(", source : { test : \"value\" }".getBytes("UTF8")); + bos.write(", source : { test : \"value\" }".getBytes(StandardCharsets.UTF_8)); gen.writeStringField("name2", "something2"); gen.writeEndObject(); gen.close(); diff --git a/server/src/test/java/org/elasticsearch/index/mapper/NumberFieldTypeTests.java b/server/src/test/java/org/elasticsearch/index/mapper/NumberFieldTypeTests.java index d4420f4baa0f4..38c64ec989117 100644 --- a/server/src/test/java/org/elasticsearch/index/mapper/NumberFieldTypeTests.java +++ b/server/src/test/java/org/elasticsearch/index/mapper/NumberFieldTypeTests.java @@ -848,7 +848,7 @@ static OutOfRangeSpec of(NumberType t, Object v, String m) { public void write(XContentBuilder b) throws IOException { 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 { b.field("field", value); } diff --git a/test/fixtures/krb5kdc-fixture/src/main/java/org/elasticsearch/test/fixtures/krb5kdc/Krb5kDcContainer.java b/test/fixtures/krb5kdc-fixture/src/main/java/org/elasticsearch/test/fixtures/krb5kdc/Krb5kDcContainer.java index f44058d0ebcc4..d71b4eab8e0fa 100644 --- a/test/fixtures/krb5kdc-fixture/src/main/java/org/elasticsearch/test/fixtures/krb5kdc/Krb5kDcContainer.java +++ b/test/fixtures/krb5kdc-fixture/src/main/java/org/elasticsearch/test/fixtures/krb5kdc/Krb5kDcContainer.java @@ -158,7 +158,7 @@ public Path getConfPath() { } try { krb5ConfFile = temporaryFolder.newFile("krb5.conf").toPath(); - Files.write(krb5ConfFile, getConf().getBytes(StandardCharsets.UTF_8)); + Files.writeString(krb5ConfFile, getConf()); return krb5ConfFile; } catch (IOException e) { throw new RuntimeException(e); diff --git a/test/fixtures/old-elasticsearch/src/main/java/oldes/OldElasticsearch.java b/test/fixtures/old-elasticsearch/src/main/java/oldes/OldElasticsearch.java index 35676eb143920..43000361452d9 100644 --- a/test/fixtures/old-elasticsearch/src/main/java/oldes/OldElasticsearch.java +++ b/test/fixtures/old-elasticsearch/src/main/java/oldes/OldElasticsearch.java @@ -128,11 +128,11 @@ public static void main(String[] args) throws IOException { } 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); 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); } } diff --git a/test/framework/src/main/java/org/elasticsearch/index/mapper/NumberTypeOutOfRangeSpec.java b/test/framework/src/main/java/org/elasticsearch/index/mapper/NumberTypeOutOfRangeSpec.java index e0b87f3e9d524..45e0c720f84dd 100644 --- a/test/framework/src/main/java/org/elasticsearch/index/mapper/NumberTypeOutOfRangeSpec.java +++ b/test/framework/src/main/java/org/elasticsearch/index/mapper/NumberTypeOutOfRangeSpec.java @@ -15,6 +15,7 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.math.BigInteger; +import java.nio.charset.StandardCharsets; public class NumberTypeOutOfRangeSpec { @@ -34,7 +35,7 @@ public static NumberTypeOutOfRangeSpec of(NumberFieldMapper.NumberType t, Object public void write(XContentBuilder b) throws IOException { 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 { b.field("field", value); } diff --git a/test/framework/src/main/java/org/elasticsearch/test/store/MockFSDirectoryFactory.java b/test/framework/src/main/java/org/elasticsearch/test/store/MockFSDirectoryFactory.java index 368eeff8af117..fadd64420900c 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/store/MockFSDirectoryFactory.java +++ b/test/framework/src/main/java/org/elasticsearch/test/store/MockFSDirectoryFactory.java @@ -83,7 +83,7 @@ public static void checkIndex(Logger logger, Store store, ShardId shardId) { } try { 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) { diff --git a/x-pack/license-tools/src/test/java/org/elasticsearch/license/licensor/tools/LicenseGenerationToolTests.java b/x-pack/license-tools/src/test/java/org/elasticsearch/license/licensor/tools/LicenseGenerationToolTests.java index 82292c7b3263f..a3057667974a5 100644 --- a/x-pack/license-tools/src/test/java/org/elasticsearch/license/licensor/tools/LicenseGenerationToolTests.java +++ b/x-pack/license-tools/src/test/java/org/elasticsearch/license/licensor/tools/LicenseGenerationToolTests.java @@ -81,7 +81,7 @@ public void testLicenseSpecFile() throws Exception { TestUtils.LicenseSpec inputLicenseSpec = TestUtils.generateRandomLicenseSpec(License.VERSION_CURRENT); String licenseSpecString = TestUtils.generateLicenseSpecString(inputLicenseSpec); Path licenseSpecFile = createTempFile(); - Files.write(licenseSpecFile, licenseSpecString.getBytes(StandardCharsets.UTF_8)); + Files.writeString(licenseSpecFile, licenseSpecString); String output = execute( "--publicKeyPath", pubKeyPath.toString(), diff --git a/x-pack/license-tools/src/test/java/org/elasticsearch/license/licensor/tools/LicenseVerificationToolTests.java b/x-pack/license-tools/src/test/java/org/elasticsearch/license/licensor/tools/LicenseVerificationToolTests.java index e31413950b077..ca104581c54f9 100644 --- a/x-pack/license-tools/src/test/java/org/elasticsearch/license/licensor/tools/LicenseVerificationToolTests.java +++ b/x-pack/license-tools/src/test/java/org/elasticsearch/license/licensor/tools/LicenseVerificationToolTests.java @@ -15,7 +15,6 @@ import org.elasticsearch.license.licensor.TestUtils; import org.junit.Before; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -74,7 +73,7 @@ public void testLicenseSpecFile() throws Exception { final TimeValue oneHour = TimeValue.timeValueHours(1); License signedLicense = TestUtils.generateSignedLicense(oneHour, pubKeyPath, priKeyPath); 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()); assertFalse(output, output.isEmpty()); } diff --git a/x-pack/plugin/autoscaling/src/internalClusterTest/java/org/elasticsearch/xpack/autoscaling/AutoscalingFileSettingsIT.java b/x-pack/plugin/autoscaling/src/internalClusterTest/java/org/elasticsearch/xpack/autoscaling/AutoscalingFileSettingsIT.java index 59144df93834b..6df58b1673ad6 100644 --- a/x-pack/plugin/autoscaling/src/internalClusterTest/java/org/elasticsearch/xpack/autoscaling/AutoscalingFileSettingsIT.java +++ b/x-pack/plugin/autoscaling/src/internalClusterTest/java/org/elasticsearch/xpack/autoscaling/AutoscalingFileSettingsIT.java @@ -103,7 +103,7 @@ private void writeJSONFile(String node, String json) throws Exception { Path tempFilePath = createTempFile(); 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); } diff --git a/x-pack/plugin/ml/qa/no-bootstrap-tests/src/test/java/org/elasticsearch/xpack/ml/utils/NamedPipeHelperNoBootstrapTests.java b/x-pack/plugin/ml/qa/no-bootstrap-tests/src/test/java/org/elasticsearch/xpack/ml/utils/NamedPipeHelperNoBootstrapTests.java index 59f909f972d2f..99cba55266d9a 100644 --- a/x-pack/plugin/ml/qa/no-bootstrap-tests/src/test/java/org/elasticsearch/xpack/ml/utils/NamedPipeHelperNoBootstrapTests.java +++ b/x-pack/plugin/ml/qa/no-bootstrap-tests/src/test/java/org/elasticsearch/xpack/ml/utils/NamedPipeHelperNoBootstrapTests.java @@ -192,7 +192,7 @@ private static void writeLineToPipe(String pipeName, Pointer handle, String line } 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 { diff --git a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/datafeed/extractor/aggregation/AggregationToJsonProcessorTests.java b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/datafeed/extractor/aggregation/AggregationToJsonProcessorTests.java index ab1dee3b91236..72543b95114ff 100644 --- a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/datafeed/extractor/aggregation/AggregationToJsonProcessorTests.java +++ b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/datafeed/extractor/aggregation/AggregationToJsonProcessorTests.java @@ -701,7 +701,7 @@ private String aggToString(Set fields, InternalAggregations aggregations processor.process(aggregations); processor.writeAllDocsCancellable(_timestamp -> false, outputStream); keyValuePairsWritten = processor.getKeyValueCount(); - return outputStream.toString(StandardCharsets.UTF_8.name()); + return outputStream.toString(StandardCharsets.UTF_8); } private String aggToStringComposite(Set fields, List buckets) throws IOException { diff --git a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/datafeed/extractor/scroll/SearchHitToJsonProcessorTests.java b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/datafeed/extractor/scroll/SearchHitToJsonProcessorTests.java index a19634e227616..55df3d49c299f 100644 --- a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/datafeed/extractor/scroll/SearchHitToJsonProcessorTests.java +++ b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/datafeed/extractor/scroll/SearchHitToJsonProcessorTests.java @@ -79,6 +79,6 @@ private String searchHitToString(ExtractedFields fields, SearchHit... searchHits hitProcessor.process(searchHits[i], new SourceSupplier(searchHits[i])); } } - return outputStream.toString(StandardCharsets.UTF_8.name()); + return outputStream.toString(StandardCharsets.UTF_8); } } diff --git a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/persistence/StateStreamerTests.java b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/persistence/StateStreamerTests.java index 47f7d8c65a27a..02c13a0b097c9 100644 --- a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/persistence/StateStreamerTests.java +++ b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/persistence/StateStreamerTests.java @@ -80,7 +80,7 @@ public void testRestoreStateToStream() throws Exception { StateStreamer stateStreamer = new StateStreamer(clientBuilder.build()); 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("{\"modName1\":\"modVal1\"}", restoreData[0]); assertEquals("{\"modName2\":\"modVal2\"}", restoreData[1]); diff --git a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/process/NativeControllerTests.java b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/process/NativeControllerTests.java index 9a851d5d8afa4..fa11097755f3d 100644 --- a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/process/NativeControllerTests.java +++ b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/process/NativeControllerTests.java @@ -77,7 +77,7 @@ public void testStartProcessCommandSucceeds() throws Exception { assertEquals( "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(); @@ -115,7 +115,7 @@ public void testStartProcessCommandFails() throws Exception { assertEquals( "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()); diff --git a/x-pack/plugin/monitoring/src/internalClusterTest/java/org/elasticsearch/xpack/monitoring/integration/MonitoringIT.java b/x-pack/plugin/monitoring/src/internalClusterTest/java/org/elasticsearch/xpack/monitoring/integration/MonitoringIT.java index a0679c90e0f9b..8e6ca8a2ad55c 100644 --- a/x-pack/plugin/monitoring/src/internalClusterTest/java/org/elasticsearch/xpack/monitoring/integration/MonitoringIT.java +++ b/x-pack/plugin/monitoring/src/internalClusterTest/java/org/elasticsearch/xpack/monitoring/integration/MonitoringIT.java @@ -52,6 +52,7 @@ import java.lang.management.ManagementFactory; import java.lang.management.MonitorInfo; import java.lang.management.ThreadInfo; +import java.nio.charset.StandardCharsets; import java.time.Instant; import java.time.ZoneOffset; import java.util.Arrays; @@ -130,7 +131,7 @@ public void testMonitoringBulk() throws Exception { final MonitoringBulkResponse bulkResponse = new MonitoringBulkRequestBuilder(client()).add( system, - new BytesArray(createBulkEntity().getBytes("UTF-8")), + new BytesArray(createBulkEntity().getBytes(StandardCharsets.UTF_8)), XContentType.JSON, System.currentTimeMillis(), interval.millis() diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/file/FileUserRolesStoreTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/file/FileUserRolesStoreTests.java index 759f57a4e0174..befd3e4c0dd47 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/file/FileUserRolesStoreTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/file/FileUserRolesStoreTests.java @@ -280,7 +280,7 @@ public void testParseFileLenientWhenCannotReadFile() throws Exception { private Path writeUsersRoles(String input) throws Exception { Path file = getUsersRolesPath(); - Files.write(file, input.getBytes(StandardCharsets.UTF_8)); + Files.writeString(file, input); return file; } @@ -292,7 +292,7 @@ private Path getUsersRolesPath() throws IOException { private void assertInvalidInputIsSilentlyIgnored(String input) throws Exception { Path file = createTempFile(); - Files.write(file, input.getBytes(StandardCharsets.UTF_8)); + Files.writeString(file, input); Map usersRoles = FileUserRolesStore.parseFile(file, null); String reason = Strings.format("Expected userRoles to be empty, but was %s", usersRoles.keySet()); assertThat(reason, usersRoles.keySet(), hasSize(0)); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/saml/SamlRealmTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/saml/SamlRealmTests.java index 917325dff31ef..da06221432bbb 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/saml/SamlRealmTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/saml/SamlRealmTests.java @@ -59,7 +59,6 @@ import java.io.IOException; import java.io.OutputStream; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.security.GeneralSecurityException; @@ -145,7 +144,7 @@ public void testReadIdpMetadataFromFile() throws Exception { public void testReadIdpMetadataFromHttps() throws Exception { 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(); try (MockWebServer proxyServer = new MockWebServer(sslService.sslContext("xpack.security.http.ssl"), false)) { proxyServer.start(); @@ -204,7 +203,7 @@ public void testFailOnErrorForInvalidHttpsMetadata() throws Exception { public void testRetryFailedHttpsMetadata() throws Exception { 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(); doTestReloadFailedHttpsMetadata(body, sslService, true); doTestReloadFailedHttpsMetadata(body, sslService, false); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/operator/FileOperatorUsersStoreTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/operator/FileOperatorUsersStoreTests.java index 972c00b59b1f2..6d219078df784 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/operator/FileOperatorUsersStoreTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/operator/FileOperatorUsersStoreTests.java @@ -491,7 +491,7 @@ private Path getOperatorUsersPath() throws IOException { private Path writeOperatorUsers(String input) throws IOException { Path file = getOperatorUsersPath(); - Files.write(file, input.getBytes(StandardCharsets.UTF_8)); + Files.writeString(file, input); return file; } diff --git a/x-pack/plugin/slm/src/internalClusterTest/java/org/elasticsearch/xpack/slm/SLMFileSettingsIT.java b/x-pack/plugin/slm/src/internalClusterTest/java/org/elasticsearch/xpack/slm/SLMFileSettingsIT.java index 30dcd339b43b7..66c8a7d4337d6 100644 --- a/x-pack/plugin/slm/src/internalClusterTest/java/org/elasticsearch/xpack/slm/SLMFileSettingsIT.java +++ b/x-pack/plugin/slm/src/internalClusterTest/java/org/elasticsearch/xpack/slm/SLMFileSettingsIT.java @@ -164,7 +164,7 @@ private void writeJSONFile(String node, String json) throws Exception { Files.createDirectories(fileSettingsService.watchedFileDir()); 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); } diff --git a/x-pack/plugin/watcher/src/internalClusterTest/java/org/elasticsearch/xpack/watcher/transform/TransformIntegrationTests.java b/x-pack/plugin/watcher/src/internalClusterTest/java/org/elasticsearch/xpack/watcher/transform/TransformIntegrationTests.java index 19d5bfa8ca678..7e0c76047e1e5 100644 --- a/x-pack/plugin/watcher/src/internalClusterTest/java/org/elasticsearch/xpack/watcher/transform/TransformIntegrationTests.java +++ b/x-pack/plugin/watcher/src/internalClusterTest/java/org/elasticsearch/xpack/watcher/transform/TransformIntegrationTests.java @@ -68,7 +68,7 @@ protected Path nodeConfigPath(int nodeOrdinal) { // 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 // 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) { throw new UncheckedIOException(e); } diff --git a/x-pack/qa/evil-tests/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/SimpleKdcLdapServer.java b/x-pack/qa/evil-tests/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/SimpleKdcLdapServer.java index 30b1744962e35..1fba6c90ea6ac 100644 --- a/x-pack/qa/evil-tests/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/SimpleKdcLdapServer.java +++ b/x-pack/qa/evil-tests/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/SimpleKdcLdapServer.java @@ -25,7 +25,6 @@ import java.net.DatagramSocket; import java.net.InetAddress; import java.net.ServerSocket; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.security.AccessController; @@ -154,7 +153,7 @@ private void createLdapBackendConf() throws IOException { + "admin_pw=secret\n" + "base_dn=" + 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")); } diff --git a/x-pack/qa/security-tools-tests/src/test/java/org/elasticsearch/xpack/security/support/SecurityFilesTests.java b/x-pack/qa/security-tools-tests/src/test/java/org/elasticsearch/xpack/security/support/SecurityFilesTests.java index dc98d37d26bf0..638ba349c6c86 100644 --- a/x-pack/qa/security-tools-tests/src/test/java/org/elasticsearch/xpack/security/support/SecurityFilesTests.java +++ b/x-pack/qa/security-tools-tests/src/test/java/org/elasticsearch/xpack/security/support/SecurityFilesTests.java @@ -15,7 +15,6 @@ import java.io.IOException; import java.io.UncheckedIOException; -import java.nio.charset.StandardCharsets; import java.nio.file.FileSystem; import java.nio.file.FileVisitResult; import java.nio.file.Files; @@ -52,7 +51,7 @@ public void testThatOriginalPermissionsAreKept() throws Exception { boolean supportsPosixPermissions = Environment.getFileStore(path).supportsFileAttributeView(PosixFileAttributeView.class); assumeTrue("Ignoring because posix file attributes are not supported", supportsPosixPermissions); - Files.write(path, "foo".getBytes(StandardCharsets.UTF_8)); + Files.writeString(path, "foo"); Set perms = Sets.newHashSet(OWNER_READ, OWNER_WRITE); if (randomBoolean()) perms.add(OWNER_EXECUTE); @@ -78,7 +77,7 @@ public void testThatOriginalPermissionsAreKept() throws Exception { public void testFailure() throws IOException { 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 RuntimeException re = expectThrows( @@ -138,8 +137,8 @@ public void testThatOwnerAndGroupAreChanged() throws Exception { try (FileSystem fs = Jimfs.newFileSystem(jimFsConfiguration)) { Path path = fs.getPath("foo"); Path tempPath = fs.getPath("bar"); - Files.write(path, "foo".getBytes(StandardCharsets.UTF_8)); - Files.write(tempPath, "bar".getBytes(StandardCharsets.UTF_8)); + Files.writeString(path, "foo"); + Files.writeString(tempPath, "bar"); PosixFileAttributeView view = Files.getFileAttributeView(path, PosixFileAttributeView.class); view.setGroup(fs.getUserPrincipalLookupService().lookupPrincipalByGroupName(randomAlphaOfLength(10)));