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;
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 class ConcatFilesTask extends DefaultTask {
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 class ConcatFilesTask extends DefaultTask {
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
);
}
}

View file

@ -155,7 +155,7 @@ public class DependenciesInfoTask extends ConventionTask {
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

View file

@ -24,6 +24,7 @@ import org.gradle.api.tasks.OutputDirectory;
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 @@ public abstract class RestTestsFromDocSnippetTask extends DocSnippetTask {
// 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);

View file

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

View file

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

View file

@ -364,7 +364,7 @@ public abstract class ThirdPartyAuditTask extends DefaultTask {
}
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 @@ public abstract class ThirdPartyAuditTask extends DefaultTask {
}
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")));
}

View file

@ -60,8 +60,8 @@ public class ConcatFilesTaskTests {
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()));

View file

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

View file

@ -18,7 +18,7 @@ import org.junit.Assert;
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 class FilePermissionsTaskTests {
filePermissionsTask.checkInvalidPermissions();
File outputMarker = new File(project.getBuildDir(), "markers/filePermissions");
List<String> result = Files.readAllLines(outputMarker.toPath(), Charset.forName("UTF-8"));
List<String> result = Files.readAllLines(outputMarker.toPath(), StandardCharsets.UTF_8);
assertEquals("done", result.get(0));
}
@ -80,7 +80,7 @@ public class FilePermissionsTaskTests {
filePermissionsTask.checkInvalidPermissions();
File outputMarker = new File(project.getBuildDir(), "markers/filePermissions");
List<String> result = Files.readAllLines(outputMarker.toPath(), Charset.forName("UTF-8"));
List<String> result = Files.readAllLines(outputMarker.toPath(), StandardCharsets.UTF_8);
assertEquals("done", result.get(0));
file.delete();

View file

@ -38,7 +38,6 @@ import java.io.File;
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 abstract class LoggedExec extends DefaultTask implements FileSystemOperat
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();

View file

@ -42,7 +42,6 @@ import org.gradle.process.ExecOperations;
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 class ElasticsearchCluster implements TestClusterConfiguration, Named {
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);
}

View file

@ -317,7 +317,7 @@ public class InstallPluginActionTests extends ESTestCase {
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 class InstallPluginActionTests extends ESTestCase {
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 @@ public class InstallPluginActionTests extends ESTestCase {
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;

View file

@ -426,7 +426,7 @@ class NioFilesActions {
@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)

View file

@ -48,7 +48,7 @@ public class URLDecodeProcessorTests extends AbstractStringProcessorTestCase<Str
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;

View file

@ -425,7 +425,7 @@ public class MustacheTests extends ESTestCase {
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))
);
}

View file

@ -46,7 +46,7 @@ public class ContextApiSpecGenerator {
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 class ContextApiSpecGenerator {
PrintStream jsonStream = new PrintStream(
Files.newOutputStream(json, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE),
false,
StandardCharsets.UTF_8.name()
StandardCharsets.UTF_8
)
) {

View file

@ -95,7 +95,6 @@ import org.junit.Before;
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 class Netty4HttpServerTransportTests extends AbstractHttpServerTransportT
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 {

View file

@ -21,7 +21,7 @@ import org.elasticsearch.index.IndexSettings;
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 class IcuCollationTokenFilterFactory extends AbstractTokenFilterFactory {
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;
}

View file

@ -45,6 +45,7 @@ import org.elasticsearch.search.fetch.subphase.highlight.LimitTokenOffsetAnalyze
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 class AnnotatedTextHighlighterTests extends ESTestCase {
// 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

View file

@ -27,7 +27,6 @@ import org.elasticsearch.test.GraalVMThreadsFilter;
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 class SpawnerNoBootstrapTests extends LuceneTestCase {
private void createControllerProgram(final Path outputFile) throws IOException {
final Path outputDir = outputFile.getParent();
Files.createDirectories(outputDir);
Files.write(outputFile, CONTROLLER_SOURCE.getBytes(StandardCharsets.UTF_8));
Files.writeString(outputFile, CONTROLLER_SOURCE);
final PosixFileAttributeView view = Files.getFileAttributeView(outputFile, PosixFileAttributeView.class);
if (view != null) {
final Set<PosixFilePermission> perms = new HashSet<>();

View file

@ -208,7 +208,7 @@ public class FileUtils {
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));

View file

@ -217,7 +217,7 @@ public class CorruptedFileIT extends ESIntegTestCase {
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) {

View file

@ -129,7 +129,7 @@ public class IngestFileSettingsIT extends ESIntegTestCase {
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);
}

View file

@ -29,7 +29,6 @@ import org.elasticsearch.test.InternalTestCluster;
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 @@ public class ReadinessClusterIT extends ESIntegTestCase {
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));
}

View file

@ -332,13 +332,10 @@ public class ScriptedMetricIT extends ESIntegTestCase {
// 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");
}

View file

@ -37,6 +37,7 @@ import org.elasticsearch.xcontent.XContentBuilder;
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 class SearchFieldsIT extends ESIntegTestCase {
.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 class SearchFieldsIT extends ESIntegTestCase {
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)))
);
}
);
}

View file

@ -3280,7 +3280,7 @@ public class IndexShard extends AbstractIndexShardComponent implements IndicesCl
} 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) {

View file

@ -92,7 +92,7 @@ import java.io.File;
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 @@ public class Node implements Closeable {
*/
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");

View file

@ -25,6 +25,7 @@ import java.nio.channels.FileChannel;
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 class ChannelsTests extends ESTestCase {
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

View file

@ -20,6 +20,7 @@ import org.junit.Assert;
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 class DeflateCompressedXContentTests extends ESTestCase {
}
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);

View file

@ -236,7 +236,7 @@ public class LocallyMountedSecretsTests extends ESTestCase {
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);
}

View file

@ -43,6 +43,7 @@ import java.io.ByteArrayOutputStream;
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 @@ public abstract class BaseXContentTestCase extends ESTestCase {
}
private static byte[] randomBytes() throws Exception {
return randomUnicodeOfLength(scaledRandomIntBetween(10, 1000)).getBytes("UTF-8");
return randomUnicodeOfLength(scaledRandomIntBetween(10, 1000)).getBytes(StandardCharsets.UTF_8);
}
@FunctionalInterface

View file

@ -92,7 +92,7 @@ public class XContentParserUtilsTests extends ESTestCase {
}
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

View file

@ -167,7 +167,7 @@ public class XContentBuilderTests extends ESTestCase {
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();

View file

@ -848,7 +848,7 @@ public class NumberFieldTypeTests extends FieldTypeTestCase {
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);
}

View file

@ -158,7 +158,7 @@ public final class Krb5kDcContainer extends DockerEnvironmentAwareTestContainer
}
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);

View file

@ -128,11 +128,11 @@ public class OldElasticsearch {
}
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);
}
}

View file

@ -15,6 +15,7 @@ import org.elasticsearch.xcontent.XContentType;
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 class NumberTypeOutOfRangeSpec {
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);
}

View file

@ -83,7 +83,7 @@ public class MockFSDirectoryFactory implements IndexStorePlugin.DirectoryFactory
}
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) {

View file

@ -81,7 +81,7 @@ public class LicenseGenerationToolTests extends CommandTestCase {
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(),

View file

@ -15,7 +15,6 @@ import org.elasticsearch.license.License;
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 class LicenseVerificationToolTests extends CommandTestCase {
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());
}

View file

@ -103,7 +103,7 @@ public class AutoscalingFileSettingsIT extends AutoscalingIntegTestCase {
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);
}

View file

@ -192,7 +192,7 @@ public class NamedPipeHelperNoBootstrapTests extends LuceneTestCase {
}
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 {

View file

@ -701,7 +701,7 @@ public class AggregationToJsonProcessorTests extends ESTestCase {
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<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]));
}
}
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.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]);

View file

@ -77,7 +77,7 @@ public class NativeControllerTests extends ESTestCase {
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 class NativeControllerTests extends ESTestCase {
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());

View file

@ -52,6 +52,7 @@ import java.lang.management.LockInfo;
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 class MonitoringIT extends ESSingleNodeTestCase {
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()

View file

@ -280,7 +280,7 @@ public class FileUserRolesStoreTests extends ESTestCase {
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 @@ public class FileUserRolesStoreTests extends ESTestCase {
private void assertInvalidInputIsSilentlyIgnored(String input) throws Exception {
Path file = createTempFile();
Files.write(file, input.getBytes(StandardCharsets.UTF_8));
Files.writeString(file, input);
Map<String, String[]> 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));

View file

@ -59,7 +59,6 @@ import org.opensaml.security.x509.X509Credential;
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 class SamlRealmTests extends SamlTestCase {
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 class SamlRealmTests extends SamlTestCase {
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);

View file

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

View file

@ -164,7 +164,7 @@ public class SLMFileSettingsIT extends AbstractSnapshotIntegTestCase {
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);
}

View file

@ -68,7 +68,7 @@ public class TransformIntegrationTests extends AbstractWatcherIntegrationTestCas
// 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);
}

View file

@ -25,7 +25,6 @@ import java.io.IOException;
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 @@ public class SimpleKdcLdapServer {
+ "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"));
}

View file

@ -15,7 +15,6 @@ import org.elasticsearch.test.ESTestCase;
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 class SecurityFilesTests extends ESTestCase {
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<PosixFilePermission> perms = Sets.newHashSet(OWNER_READ, OWNER_WRITE);
if (randomBoolean()) perms.add(OWNER_EXECUTE);
@ -78,7 +77,7 @@ public class SecurityFilesTests extends ESTestCase {
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 class SecurityFilesTests extends ESTestCase {
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)));