diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/BwcSetupExtension.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/BwcSetupExtension.java index 7a57aabfe5f1..b5e3ea074ca8 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/BwcSetupExtension.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/BwcSetupExtension.java @@ -70,7 +70,7 @@ public class BwcSetupExtension { @Override public void execute(Task t) { // Execution time so that the checkouts are available - String compilerVersionInfoPath = minimumCompilerVersionPath(unreleasedVersionInfo.get().version); + String compilerVersionInfoPath = minimumCompilerVersionPath(unreleasedVersionInfo.get().version()); String minimumCompilerVersion = readFromFile(new File(checkoutDir.get(), compilerVersionInfoPath)); loggedExec.environment("JAVA_HOME", getJavaHome(Integer.parseInt(minimumCompilerVersion))); } @@ -108,8 +108,8 @@ public class BwcSetupExtension { if (project.getGradle().getStartParameter().isParallelProjectExecutionEnabled()) { loggedExec.args("--parallel"); } - loggedExec.setStandardOutput(new IndentingOutputStream(System.out, unreleasedVersionInfo.get().version)); - loggedExec.setErrorOutput(new IndentingOutputStream(System.err, unreleasedVersionInfo.get().version)); + loggedExec.setStandardOutput(new IndentingOutputStream(System.out, unreleasedVersionInfo.get().version())); + loggedExec.setErrorOutput(new IndentingOutputStream(System.err, unreleasedVersionInfo.get().version())); configAction.execute(loggedExec); }); } diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/BwcVersions.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/BwcVersions.java index e7d1425caee8..83db6a69b09b 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/BwcVersions.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/BwcVersions.java @@ -18,7 +18,6 @@ import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Objects; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; @@ -280,39 +279,9 @@ public class BwcVersions { return MINIMUM_WIRE_COMPATIBLE_VERSION; } - public static class UnreleasedVersionInfo { - public final Version version; - public final String branch; - public final String gradleProjectPath; + public record UnreleasedVersionInfo(Version version, String branch, String gradleProjectPath) {} - public UnreleasedVersionInfo(Version version, String branch, String gradleProjectPath) { - this.version = version; - this.branch = branch; - this.gradleProjectPath = gradleProjectPath; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - UnreleasedVersionInfo that = (UnreleasedVersionInfo) o; - return version.equals(that.version) && branch.equals(that.branch) && gradleProjectPath.equals(that.gradleProjectPath); - } - - @Override - public int hashCode() { - return Objects.hash(version, branch, gradleProjectPath); - } - } - - public static class VersionPair implements Comparable { - public final Version elasticsearch; - public final Version lucene; - - public VersionPair(Version elasticsearch, Version lucene) { - this.elasticsearch = elasticsearch; - this.lucene = lucene; - } + public record VersionPair(Version elasticsearch, Version lucene) implements Comparable { @Override public int compareTo(@NotNull VersionPair o) { 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 70c4866e0996..6d4a4906d90f 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 @@ -181,20 +181,20 @@ public class DependenciesInfoTask extends ConventionTask { String licenseType; final LicenseAnalyzer.LicenseInfo licenseInfo = LicenseAnalyzer.licenseType(license); - if (licenseInfo.isSpdxLicense() == false) { + if (licenseInfo.spdxLicense() == false) { // License has not be identified as SPDX. // As we have the license file, we create a Custom entry with the URL to this license file. final String gitBranch = System.getProperty("build.branch", "master"); final String githubBaseURL = "https://raw.githubusercontent.com/elastic/elasticsearch/" + gitBranch + "/"; - licenseType = licenseInfo.getIdentifier() + licenseType = licenseInfo.identifier() + ";" + license.getCanonicalPath().replaceFirst(".*/elasticsearch/", githubBaseURL) + ","; } else { - licenseType = licenseInfo.getIdentifier() + ","; + licenseType = licenseInfo.identifier() + ","; } - if (licenseInfo.isSourceRedistributionRequired()) { + if (licenseInfo.sourceRedistributionRequired()) { final File sources = getDependencyInfoFile(group, name, "SOURCES"); licenseType += Files.readString(sources.toPath()).trim(); } diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/InternalDistributionBwcSetupPlugin.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/InternalDistributionBwcSetupPlugin.java index a41ce13daf24..7eeff518e21c 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/InternalDistributionBwcSetupPlugin.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/InternalDistributionBwcSetupPlugin.java @@ -59,7 +59,7 @@ public class InternalDistributionBwcSetupPlugin implements InternalPlugin { BuildParams.getBwcVersions() .forPreviousUnreleased( (BwcVersions.UnreleasedVersionInfo unreleasedVersion) -> { - configureBwcProject(project.project(unreleasedVersion.gradleProjectPath), unreleasedVersion, bwcTaskThrottleProvider); + configureBwcProject(project.project(unreleasedVersion.gradleProjectPath()), unreleasedVersion, bwcTaskThrottleProvider); } ); } @@ -70,13 +70,13 @@ public class InternalDistributionBwcSetupPlugin implements InternalPlugin { Provider bwcTaskThrottleProvider ) { Provider versionInfoProvider = providerFactory.provider(() -> versionInfo); - Provider checkoutDir = versionInfoProvider.map(info -> new File(project.getBuildDir(), "bwc/checkout-" + info.branch)); + Provider checkoutDir = versionInfoProvider.map(info -> new File(project.getBuildDir(), "bwc/checkout-" + info.branch())); BwcSetupExtension bwcSetupExtension = project.getExtensions() .create("bwcSetup", BwcSetupExtension.class, project, versionInfoProvider, bwcTaskThrottleProvider, checkoutDir); BwcGitExtension gitExtension = project.getPlugins().apply(InternalBwcGitPlugin.class).getGitExtension(); - Provider bwcVersion = versionInfoProvider.map(info -> info.version); - gitExtension.setBwcVersion(versionInfoProvider.map(info -> info.version)); - gitExtension.setBwcBranch(versionInfoProvider.map(info -> info.branch)); + Provider bwcVersion = versionInfoProvider.map(info -> info.version()); + gitExtension.setBwcVersion(versionInfoProvider.map(info -> info.version())); + gitExtension.setBwcBranch(versionInfoProvider.map(info -> info.branch())); gitExtension.getCheckoutDir().set(checkoutDir); // we want basic lifecycle tasks like `clean` here. diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/InternalDistributionDownloadPlugin.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/InternalDistributionDownloadPlugin.java index df88e1b86035..6cb8334ff4f0 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/InternalDistributionDownloadPlugin.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/InternalDistributionDownloadPlugin.java @@ -50,7 +50,7 @@ public class InternalDistributionDownloadPlugin implements InternalPlugin { DockerSupportPlugin.DOCKER_SUPPORT_SERVICE_NAME ); distributionDownloadPlugin.setDockerAvailability( - dockerSupport.map(dockerSupportService -> dockerSupportService.getDockerAvailability().isAvailable) + dockerSupport.map(dockerSupportService -> dockerSupportService.getDockerAvailability().isAvailable()) ); registerInternalDistributionResolutions(DistributionDownloadPlugin.getRegistrationsContainer(project)); } @@ -88,7 +88,7 @@ public class InternalDistributionDownloadPlugin implements InternalPlugin { } String projectConfig = getProjectConfig(distribution, unreleasedInfo); return new ProjectBasedDistributionDependency( - (config) -> projectDependency(project, unreleasedInfo.gradleProjectPath, projectConfig) + (config) -> projectDependency(project, unreleasedInfo.gradleProjectPath(), projectConfig) ); } return null; @@ -107,7 +107,7 @@ public class InternalDistributionDownloadPlugin implements InternalPlugin { private static String getProjectConfig(ElasticsearchDistribution distribution, BwcVersions.UnreleasedVersionInfo info) { String distributionProjectName = distributionProjectName(distribution); if (distribution.getType().shouldExtract()) { - return (info.gradleProjectPath.equals(":distribution") || info.version.before("7.10.0")) + return (info.gradleProjectPath().equals(":distribution") || info.version().before("7.10.0")) ? distributionProjectName : "expanded-" + distributionProjectName; } else { diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/docker/DockerSupportService.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/docker/DockerSupportService.java index 4a50f8dd9196..4d78a0a7c36d 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/docker/DockerSupportService.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/docker/DockerSupportService.java @@ -308,8 +308,8 @@ public abstract class DockerSupportService implements BuildService @@ -319,71 +319,32 @@ public abstract class DockerSupportService implements BuildServiceCan execute a command that requires privileges * */ - public final boolean isAvailable; + boolean isAvailable, - /** - * True if docker-compose is available. - */ - public final boolean isComposeAvailable; + // True if docker-compose is available. + boolean isComposeAvailable, - /** - * True if the installed Docker version is >= 17.05 - */ - public final boolean isVersionHighEnough; + // True if the installed Docker version is >,= 17.05 + boolean isVersionHighEnough, - /** - * The path to the Docker CLI, or null - */ - public final String path; + // The path to the Docker CLI, or null + String path, - /** - * The installed Docker version, or null - */ - public final Version version; + // The installed Docker version, or null + Version version, - /** - * Information about the last command executes while probing Docker, or null. - */ - final Result lastCommand; - - DockerAvailability( - boolean isAvailable, - boolean isComposeAvailable, - boolean isVersionHighEnough, - String path, - Version version, - Result lastCommand - ) { - this.isAvailable = isAvailable; - this.isComposeAvailable = isComposeAvailable; - this.isVersionHighEnough = isVersionHighEnough; - this.path = path; - this.version = version; - this.lastCommand = lastCommand; - } - } + // Information about the last command executes while probing Docker, or null. + Result lastCommand + ) {} /** * This class models the result of running a command. It captures the exit code, standard output and standard error. */ - private static class Result { - final int exitCode; - final String stdout; - final String stderr; - - Result(int exitCode, String stdout, String stderr) { - this.exitCode = exitCode; - this.stdout = stdout; - this.stderr = stderr; - } + private record Result(int exitCode, String stdout, String stderr) { boolean isSuccess() { return exitCode == 0; } - - public String toString() { - return "exitCode = [" + exitCode + "] " + "stdout = [" + stdout.trim() + "] " + "stderr = [" + stderr.trim() + "]"; - } } interface Parameters extends BuildServiceParameters { diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/precommit/DependencyLicensesTask.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/precommit/DependencyLicensesTask.java index 7b1bb283290d..4d1b0c76598d 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/precommit/DependencyLicensesTask.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/precommit/DependencyLicensesTask.java @@ -266,7 +266,7 @@ public class DependencyLicensesTask extends DefaultTask { File licenseFile = new File(licensesDir, getFileName(dependencyName, licenses, "LICENSE")); LicenseInfo licenseInfo = LicenseAnalyzer.licenseType(licenseFile); - if (licenseInfo.isSourceRedistributionRequired()) { + if (licenseInfo.sourceRedistributionRequired()) { checkFile(dependencyName, jarName, sources, "SOURCES"); } } diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/precommit/LicenseAnalyzer.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/precommit/LicenseAnalyzer.java index 0e999484d16e..c52ea9aaeb6f 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/precommit/LicenseAnalyzer.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/precommit/LicenseAnalyzer.java @@ -147,53 +147,16 @@ public class LicenseAnalyzer { for (LicenseMatcher matcher : matchers) { boolean matches = matcher.matches(licenseFile); if (matches) { - return new LicenseInfo(matcher.getIdentifier(), matcher.spdxLicense, matcher.sourceRedistributionRequired); + return new LicenseInfo(matcher.identifier(), matcher.spdxLicense, matcher.sourceRedistributionRequired); } } throw new IllegalStateException("Unknown license for license file: " + licenseFile); } - public static class LicenseInfo { - private final String identifier; - private final boolean spdxLicense; - private final boolean sourceRedistributionRequired; + public record LicenseInfo(String identifier, boolean spdxLicense, boolean sourceRedistributionRequired) {} - public LicenseInfo(String identifier, boolean spdxLicense, boolean sourceRedistributionRequired) { - this.identifier = identifier; - this.spdxLicense = spdxLicense; - this.sourceRedistributionRequired = sourceRedistributionRequired; - } - - public String getIdentifier() { - return identifier; - } - - public boolean isSpdxLicense() { - return spdxLicense; - } - - public boolean isSourceRedistributionRequired() { - return sourceRedistributionRequired; - } - } - - private static class LicenseMatcher { - private final String identifier; - private final boolean spdxLicense; - private final boolean sourceRedistributionRequired; - private final Pattern pattern; - - LicenseMatcher(String identifier, boolean spdxLicense, boolean sourceRedistributionRequired, Pattern pattern) { - this.identifier = identifier; - this.spdxLicense = spdxLicense; - this.sourceRedistributionRequired = sourceRedistributionRequired; - this.pattern = pattern; - } - - public String getIdentifier() { - return identifier; - } + private record LicenseMatcher(String identifier, boolean spdxLicense, boolean sourceRedistributionRequired, Pattern pattern) { public boolean matches(File licenseFile) { try { diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/release/BreakingChangesGenerator.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/release/BreakingChangesGenerator.java index 286f23d83e5b..e98b338e6089 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/release/BreakingChangesGenerator.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/release/BreakingChangesGenerator.java @@ -125,9 +125,9 @@ public class BreakingChangesGenerator { bindings.put("breakingIncludeList", breakingIncludeList); bindings.put("deprecationsByArea", deprecationsByArea); bindings.put("isElasticsearchSnapshot", version.isSnapshot()); - bindings.put("majorDotMinor", version.getMajor() + "." + version.getMinor()); - bindings.put("majorMinor", String.valueOf(version.getMajor()) + version.getMinor()); - bindings.put("nextMajor", (version.getMajor() + 1) + ".0"); + bindings.put("majorDotMinor", version.major() + "." + version.minor()); + bindings.put("majorMinor", String.valueOf(version.major()) + version.minor()); + bindings.put("nextMajor", (version.major() + 1) + ".0"); bindings.put("version", version); return TemplateUtils.render(template, bindings); @@ -152,7 +152,7 @@ public class BreakingChangesGenerator { bindings.put("breakingArea", breakingArea); bindings.put("breakingEntriesByNotability", breakingEntriesByNotability); bindings.put("breakingAreaAnchor", breakingArea.toLowerCase(Locale.ROOT).replaceFirst(" and", "").replaceAll(" ", "_")); - bindings.put("majorMinor", String.valueOf(version.getMajor()) + version.getMinor()); + bindings.put("majorMinor", String.valueOf(version.major()) + version.minor()); return TemplateUtils.render(template, bindings); } diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/release/GenerateReleaseNotesTask.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/release/GenerateReleaseNotesTask.java index 7f09dbb87d3f..7c49ab10c8be 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/release/GenerateReleaseNotesTask.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/release/GenerateReleaseNotesTask.java @@ -152,7 +152,7 @@ public class GenerateReleaseNotesTask extends DefaultTask { @VisibleForTesting static Set getVersions(GitWrapper gitWrapper, String currentVersion) { QualifiedVersion v = QualifiedVersion.of(currentVersion); - Set versions = gitWrapper.listVersions("v" + v.getMajor() + '.' + v.getMinor() + ".*").collect(toSet()); + Set versions = gitWrapper.listVersions("v" + v.major() + '.' + v.minor() + ".*").collect(toSet()); versions.add(v); return versions; } @@ -183,7 +183,7 @@ public class GenerateReleaseNotesTask extends DefaultTask { QualifiedVersion currentVersion = QualifiedVersion.of(versionString); // Find all tags for this minor series, using a wildcard tag pattern. - String tagWildcard = "v%d.%d*".formatted(currentVersion.getMajor(), currentVersion.getMinor()); + String tagWildcard = "v%d.%d*".formatted(currentVersion.major(), currentVersion.minor()); final List earlierVersions = gitWrapper.listVersions(tagWildcard) // Only keep earlier versions, and if `currentVersion` is a prerelease, then only prereleases too. diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/release/PruneChangelogsTask.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/release/PruneChangelogsTask.java index 45d85ec61cec..a2a1c58d67cc 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/release/PruneChangelogsTask.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/release/PruneChangelogsTask.java @@ -162,7 +162,7 @@ public class PruneChangelogsTask extends DefaultTask { */ @VisibleForTesting static Stream findPreviousVersion(GitWrapper gitWrapper, QualifiedVersion version) { - final int majorSeries = version.getMinor() == 0 && version.getRevision() == 0 ? version.getMajor() - 1 : version.getMajor(); + final int majorSeries = version.minor() == 0 && version.revision() == 0 ? version.major() - 1 : version.major(); final String tagPattern = "v" + majorSeries + ".*"; return gitWrapper.listVersions(tagPattern).filter(v -> v.isBefore(version)); diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/release/QualifiedVersion.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/release/QualifiedVersion.java index 0cc579e68d52..df22f0b804d3 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/release/QualifiedVersion.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/release/QualifiedVersion.java @@ -21,26 +21,21 @@ import java.util.regex.Pattern; * with how {@link Version} is used in the build. It also retains any qualifier (prerelease) information, and uses * that information when comparing instances. */ -public final class QualifiedVersion implements Comparable { - private final int major; - private final int minor; - private final int revision; - private final Qualifier qualifier; +public record QualifiedVersion( + int major, + int minor, + int revision, + org.elasticsearch.gradle.internal.release.QualifiedVersion.Qualifier qualifier +) implements Comparable { private static final Pattern pattern = Pattern.compile( "^v? (\\d+) \\. (\\d+) \\. (\\d+) (?: - (alpha\\d+ | beta\\d+ | rc\\d+ | SNAPSHOT ) )? $", Pattern.COMMENTS ); - private QualifiedVersion(int major, int minor, int revision, String qualifier) { - this.major = major; - this.minor = minor; - this.revision = revision; - this.qualifier = qualifier == null ? null : Qualifier.of(qualifier); - } - /** * Parses the supplied string into an object. + * * @param s a version string in strict semver * @return a new instance */ @@ -55,7 +50,7 @@ public final class QualifiedVersion implements Comparable { Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2)), Integer.parseInt(matcher.group(3)), - matcher.group(4) + matcher.group(4) == null ? null : Qualifier.of(matcher.group(4)) ); } @@ -64,42 +59,10 @@ public final class QualifiedVersion implements Comparable { return "%d.%d.%d%s".formatted(major, minor, revision, qualifier == null ? "" : "-" + qualifier); } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - QualifiedVersion version = (QualifiedVersion) o; - return major == version.major - && minor == version.minor - && revision == version.revision - && Objects.equals(qualifier, version.qualifier); - } - - @Override - public int hashCode() { - return Objects.hash(major, minor, revision, qualifier); - } - - public int getMajor() { - return major; - } - - public int getMinor() { - return minor; - } - - public int getRevision() { - return revision; - } - public boolean hasQualifier() { return qualifier != null; } - public Qualifier getQualifier() { - return qualifier; - } - public boolean isSnapshot() { return this.qualifier != null && this.qualifier.level == QualifierLevel.SNAPSHOT; } @@ -129,22 +92,10 @@ public final class QualifiedVersion implements Comparable { SNAPSHOT } - private static class Qualifier implements Comparable { - private final QualifierLevel level; - private final int number; - - private Qualifier(QualifierLevel level, int number) { - this.level = level; - this.number = number; - } + private record Qualifier(QualifierLevel level, int number) implements Comparable { private static final Comparator COMPARATOR = Comparator.comparing((Qualifier p) -> p.level).thenComparing(p -> p.number); - @Override - public int compareTo(Qualifier other) { - return COMPARATOR.compare(this, other); - } - private static Qualifier of(String qualifier) { if ("SNAPSHOT".equals(qualifier)) { return new Qualifier(QualifierLevel.SNAPSHOT, 0); @@ -162,21 +113,14 @@ public final class QualifiedVersion implements Comparable { } } + @Override + public int compareTo(Qualifier other) { + return COMPARATOR.compare(this, other); + } + + @Override public String toString() { return level == QualifierLevel.SNAPSHOT ? level.name() : level.name() + number; } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - Qualifier that = (Qualifier) o; - return number == that.number && level == that.level; - } - - @Override - public int hashCode() { - return Objects.hash(level, number); - } } } diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/release/ReleaseHighlightsGenerator.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/release/ReleaseHighlightsGenerator.java index e8e807f301a2..3d86e0ae9f2b 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/release/ReleaseHighlightsGenerator.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/release/ReleaseHighlightsGenerator.java @@ -39,9 +39,9 @@ public class ReleaseHighlightsGenerator { static String generateFile(QualifiedVersion version, String template, List entries) throws IOException { final List priorVersions = new ArrayList<>(); - if (version.getMinor() > 0) { - final int major = version.getMajor(); - for (int minor = version.getMinor(); minor >= 0; minor--) { + if (version.minor() > 0) { + final int major = version.major(); + for (int minor = version.minor(); minor >= 0; minor--) { String majorMinor = major + "." + minor; String fileSuffix = ""; if (major == 7 && minor < 7) { diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/release/ReleaseNotesIndexGenerator.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/release/ReleaseNotesIndexGenerator.java index 839c318f3278..03c01f5d8e24 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/release/ReleaseNotesIndexGenerator.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/release/ReleaseNotesIndexGenerator.java @@ -43,7 +43,7 @@ public class ReleaseNotesIndexGenerator { versionsSet.stream().map(v -> v.isSnapshot() ? v.withoutQualifier() : v).forEach(versions::add); final List includeVersions = versions.stream() - .map(v -> v.hasQualifier() ? v.toString() : v.getMajor() + "." + v.getMinor()) + .map(v -> v.hasQualifier() ? v.toString() : v.major() + "." + v.minor()) .distinct() .collect(Collectors.toList()); diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/DistroTestPlugin.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/DistroTestPlugin.java index 16c531113410..7510e0ff90a8 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/DistroTestPlugin.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/DistroTestPlugin.java @@ -117,7 +117,7 @@ public class DistroTestPlugin implements Plugin { depsTask.configure(t -> t.dependsOn(examplePlugin.getDependencies())); depsTasks.put(taskname, depsTask); TaskProvider destructiveTask = configureTestTask(project, taskname, distribution, t -> { - t.onlyIf(t2 -> distribution.isDocker() == false || dockerSupport.get().getDockerAvailability().isAvailable); + t.onlyIf(t2 -> distribution.isDocker() == false || dockerSupport.get().getDockerAvailability().isAvailable()); addDistributionSysprop(t, DISTRIBUTION_SYSPROP, distribution::getFilepath); addDistributionSysprop(t, EXAMPLE_PLUGIN_SYSPROP, () -> examplePlugin.getSingleFile().toString()); t.exclude("**/PackageUpgradeTests.class"); diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/ErrorReportingTestListener.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/ErrorReportingTestListener.java index 65f29fbbf747..d00301e96fab 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/ErrorReportingTestListener.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/ErrorReportingTestListener.java @@ -32,7 +32,6 @@ import java.util.Deque; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.Map; -import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; @@ -184,41 +183,15 @@ public class ErrorReportingTestListener implements TestOutputListener, TestListe * use this a the key for our HashMap, it's best to control the implementation as there's no guarantee that Gradle's * various {@link TestDescriptor} implementations reliably implement equals and hashCode. */ - public static class Descriptor { - private final String name; - private final String className; - private final String parent; - - private Descriptor(String name, String className, String parent) { - this.name = name; - this.className = className; - this.parent = parent; - } + public record Descriptor(String name, String className, String parent) { public static Descriptor of(TestDescriptor d) { return new Descriptor(d.getName(), d.getClassName(), d.getParent() == null ? null : d.getParent().toString()); } - public String getClassName() { - return className; - } - public String getFullName() { return className + "." + name; } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - Descriptor that = (Descriptor) o; - return Objects.equals(name, that.name) && Objects.equals(className, that.className) && Objects.equals(parent, that.parent); - } - - @Override - public int hashCode() { - return Objects.hash(name, className, parent); - } } private class EventWriter implements Closeable { @@ -226,7 +199,7 @@ public class ErrorReportingTestListener implements TestOutputListener, TestListe private final Writer writer; EventWriter(Descriptor descriptor) { - this.outputFile = new File(outputDirectory, descriptor.getClassName() + ".out"); + this.outputFile = new File(outputDirectory, descriptor.className() + ".out"); FileOutputStream fos; try { diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/ReplaceByKey.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/ReplaceByKey.java index d4c367fe0b88..6bb0f8f6db0a 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/ReplaceByKey.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/ReplaceByKey.java @@ -54,7 +54,7 @@ public abstract class ReplaceByKey implements RestTestTransformByParentObject { @Override public boolean shouldApply(RestTestContext testContext) { - return testName == null || testContext.getTestName().equals(testName); + return testName == null || testContext.testName().equals(testName); } @Input diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/RestTestContext.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/RestTestContext.java index 9b17a3cd81f3..80b780e65606 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/RestTestContext.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/RestTestContext.java @@ -11,15 +11,4 @@ package org.elasticsearch.gradle.internal.test.rest.transform; /** * A place to stash information about a test that is being transformed. */ -public class RestTestContext { - - private final String testName; - - public RestTestContext(String testName) { - this.testName = testName; - } - - public String getTestName() { - return testName; - } -} +public record RestTestContext(String testName) {} diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/match/AddMatch.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/match/AddMatch.java index cfaf795a5780..40d2cf6d24ad 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/match/AddMatch.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/match/AddMatch.java @@ -37,7 +37,7 @@ public class AddMatch implements RestTestTransformByParentArray { @Override public boolean shouldApply(RestTestContext testContext) { - return testContext.getTestName().equals(testName); + return testContext.testName().equals(testName); } @Override diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/match/RemoveMatch.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/match/RemoveMatch.java index 853ae5c88979..10c5152ba537 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/match/RemoveMatch.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/match/RemoveMatch.java @@ -47,7 +47,7 @@ public class RemoveMatch implements RestTestTransformByParentObject { @Override public boolean shouldApply(RestTestContext testContext) { - return testName == null || testContext.getTestName().equals(testName); + return testName == null || testContext.testName().equals(testName); } @Override diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/text/ReplaceTextual.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/text/ReplaceTextual.java index c99c01c6d922..a02da6902602 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/text/ReplaceTextual.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/text/ReplaceTextual.java @@ -54,7 +54,7 @@ public class ReplaceTextual implements RestTestTransformByParentObject { @Override public boolean shouldApply(RestTestContext testContext) { - return testName == null || testContext.getTestName().equals(testName); + return testName == null || testContext.testName().equals(testName); } @Override diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/warnings/InjectAllowedWarnings.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/warnings/InjectAllowedWarnings.java index 8bfbadbe86ad..f8116d14f2bf 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/warnings/InjectAllowedWarnings.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/warnings/InjectAllowedWarnings.java @@ -88,7 +88,7 @@ public class InjectAllowedWarnings extends FeatureInjector implements RestTestTr @Override public boolean shouldApply(RestTestContext testContext) { - return testName == null || testContext.getTestName().equals(testName); + return testName == null || testContext.testName().equals(testName); } @Input diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/warnings/InjectWarnings.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/warnings/InjectWarnings.java index b95881643fbb..2cff61de0ac1 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/warnings/InjectWarnings.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/warnings/InjectWarnings.java @@ -76,7 +76,7 @@ public class InjectWarnings extends FeatureInjector implements RestTestTransform @Override public boolean shouldApply(RestTestContext testContext) { - return testName.equals(testContext.getTestName()); + return testName.equals(testContext.testName()); } @Input diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/warnings/RemoveWarnings.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/warnings/RemoveWarnings.java index a00901a2b141..13e40f6f0079 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/warnings/RemoveWarnings.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/warnings/RemoveWarnings.java @@ -82,7 +82,7 @@ public class RemoveWarnings implements RestTestTransformByParentObject { @Override public boolean shouldApply(RestTestContext testContext) { - return testName == null || testContext.getTestName().equals(testName); + return testName == null || testContext.testName().equals(testName); } @Input diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/testfixtures/TestFixturesPlugin.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/testfixtures/TestFixturesPlugin.java index 0112e3431595..9a2e931824a6 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/testfixtures/TestFixturesPlugin.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/testfixtures/TestFixturesPlugin.java @@ -169,7 +169,7 @@ public class TestFixturesPlugin implements Plugin { private void maybeSkipTask(Provider dockerSupport, Task task) { task.onlyIf(spec -> { - boolean isComposeAvailable = dockerSupport.get().getDockerAvailability().isComposeAvailable; + boolean isComposeAvailable = dockerSupport.get().getDockerAvailability().isComposeAvailable(); if (isComposeAvailable == false) { LOGGER.info("Task {} requires docker-compose but it is unavailable. Task will be skipped.", task.getPath()); } diff --git a/build-tools-internal/src/test/java/org/elasticsearch/gradle/AbstractDistributionDownloadPluginTests.java b/build-tools-internal/src/test/java/org/elasticsearch/gradle/AbstractDistributionDownloadPluginTests.java index 64b5268d451c..cad9b19895c5 100644 --- a/build-tools-internal/src/test/java/org/elasticsearch/gradle/AbstractDistributionDownloadPluginTests.java +++ b/build-tools-internal/src/test/java/org/elasticsearch/gradle/AbstractDistributionDownloadPluginTests.java @@ -31,19 +31,19 @@ public class AbstractDistributionDownloadPluginTests extends GradleUnitTestCase protected static final VersionPair BWC_MAINTENANCE_VERSION = new VersionPair(Version.fromString("0.90.1"), Version.fromString("1.1.3")); protected static final BwcVersions BWC_MINOR = new BwcVersions( - BWC_MAJOR_VERSION.elasticsearch, + BWC_MAJOR_VERSION.elasticsearch(), Arrays.asList(BWC_BUGFIX_VERSION, BWC_MINOR_VERSION, BWC_MAJOR_VERSION) ); protected static final BwcVersions BWC_STAGED = new BwcVersions( - BWC_MAJOR_VERSION.elasticsearch, + BWC_MAJOR_VERSION.elasticsearch(), Arrays.asList(BWC_MAINTENANCE_VERSION, BWC_STAGED_VERSION, BWC_MINOR_VERSION, BWC_MAJOR_VERSION) ); protected static final BwcVersions BWC_BUGFIX = new BwcVersions( - BWC_MAJOR_VERSION.elasticsearch, + BWC_MAJOR_VERSION.elasticsearch(), Arrays.asList(BWC_BUGFIX_VERSION, BWC_MINOR_VERSION, BWC_MAJOR_VERSION) ); protected static final BwcVersions BWC_MAINTENANCE = new BwcVersions( - BWC_MINOR_VERSION.elasticsearch, + BWC_MINOR_VERSION.elasticsearch(), Arrays.asList(BWC_MAINTENANCE_VERSION, BWC_BUGFIX_VERSION, BWC_MINOR_VERSION) ); diff --git a/build-tools-internal/src/test/java/org/elasticsearch/gradle/DistributionDownloadPluginTests.java b/build-tools-internal/src/test/java/org/elasticsearch/gradle/DistributionDownloadPluginTests.java index e66ccab543a3..be66847144ff 100644 --- a/build-tools-internal/src/test/java/org/elasticsearch/gradle/DistributionDownloadPluginTests.java +++ b/build-tools-internal/src/test/java/org/elasticsearch/gradle/DistributionDownloadPluginTests.java @@ -132,10 +132,10 @@ public class DistributionDownloadPluginTests extends AbstractDistributionDownloa String configName = projectName(platform.toString(), true); configName += (platform == Platform.WINDOWS ? "-zip" : "-tar"); ElasticsearchDistributionType archiveType = ElasticsearchDistributionTypes.ARCHIVE; - checkBwc("minor", configName, BWC_MINOR_VERSION.elasticsearch, archiveType, platform, BWC_MINOR); - checkBwc("staged", configName, BWC_STAGED_VERSION.elasticsearch, archiveType, platform, BWC_STAGED); - checkBwc("bugfix", configName, BWC_BUGFIX_VERSION.elasticsearch, archiveType, platform, BWC_BUGFIX); - checkBwc("maintenance", configName, BWC_MAINTENANCE_VERSION.elasticsearch, archiveType, platform, BWC_MAINTENANCE); + checkBwc("minor", configName, BWC_MINOR_VERSION.elasticsearch(), archiveType, platform, BWC_MINOR); + checkBwc("staged", configName, BWC_STAGED_VERSION.elasticsearch(), archiveType, platform, BWC_STAGED); + checkBwc("bugfix", configName, BWC_BUGFIX_VERSION.elasticsearch(), archiveType, platform, BWC_BUGFIX); + checkBwc("maintenance", configName, BWC_MAINTENANCE_VERSION.elasticsearch(), archiveType, platform, BWC_MAINTENANCE); } } diff --git a/build-tools-internal/src/test/java/org/elasticsearch/gradle/internal/InternalDistributionDownloadPluginTests.java b/build-tools-internal/src/test/java/org/elasticsearch/gradle/internal/InternalDistributionDownloadPluginTests.java index 4ff64ca31c1c..ef19c385f25d 100644 --- a/build-tools-internal/src/test/java/org/elasticsearch/gradle/internal/InternalDistributionDownloadPluginTests.java +++ b/build-tools-internal/src/test/java/org/elasticsearch/gradle/internal/InternalDistributionDownloadPluginTests.java @@ -38,10 +38,10 @@ public class InternalDistributionDownloadPluginTests extends AbstractDistributio for (ElasticsearchDistributionType packageType : types) { // note: no non bundled jdk for bwc String configName = projectName(packageType.toString(), true); - checkBwc("minor", configName, BWC_MINOR_VERSION.elasticsearch, packageType, null, BWC_MINOR); - checkBwc("staged", configName, BWC_STAGED_VERSION.elasticsearch, packageType, null, BWC_STAGED); - checkBwc("bugfix", configName, BWC_BUGFIX_VERSION.elasticsearch, packageType, null, BWC_BUGFIX); - checkBwc("maintenance", configName, BWC_MAINTENANCE_VERSION.elasticsearch, packageType, null, BWC_MAINTENANCE); + checkBwc("minor", configName, BWC_MINOR_VERSION.elasticsearch(), packageType, null, BWC_MINOR); + checkBwc("staged", configName, BWC_STAGED_VERSION.elasticsearch(), packageType, null, BWC_STAGED); + checkBwc("bugfix", configName, BWC_BUGFIX_VERSION.elasticsearch(), packageType, null, BWC_BUGFIX); + checkBwc("maintenance", configName, BWC_MAINTENANCE_VERSION.elasticsearch(), packageType, null, BWC_MAINTENANCE); } } } diff --git a/build-tools/src/main/java/org/elasticsearch/gradle/util/Pair.java b/build-tools/src/main/java/org/elasticsearch/gradle/util/Pair.java index 0f78e81dd4b2..84001b845c9a 100644 --- a/build-tools/src/main/java/org/elasticsearch/gradle/util/Pair.java +++ b/build-tools/src/main/java/org/elasticsearch/gradle/util/Pair.java @@ -8,24 +8,9 @@ package org.elasticsearch.gradle.util; -public class Pair { - private final L left; - private final R right; - - private Pair(L left, R right) { - this.left = left; - this.right = right; - } +public record Pair (L left, R right) { public static Pair of(L left, R right) { return new Pair<>(left, right); } - - public L left() { - return left; - } - - public R right() { - return right; - } } diff --git a/client/benchmark/src/main/java/org/elasticsearch/client/benchmark/BenchmarkRunner.java b/client/benchmark/src/main/java/org/elasticsearch/client/benchmark/BenchmarkRunner.java index 19aa5ed98a3d..a442f20f3f58 100644 --- a/client/benchmark/src/main/java/org/elasticsearch/client/benchmark/BenchmarkRunner.java +++ b/client/benchmark/src/main/java/org/elasticsearch/client/benchmark/BenchmarkRunner.java @@ -57,26 +57,26 @@ public final class BenchmarkRunner { } for (Metrics metrics : summaryMetrics) { - String throughput = String.format(Locale.ROOT, "Throughput [ops/s]: %f", metrics.throughput); + String throughput = String.format(Locale.ROOT, "Throughput [ops/s]: %f", metrics.throughput()); String serviceTimes = String.format( Locale.ROOT, "Service time [ms]: p50 = %f, p90 = %f, p95 = %f, p99 = %f, p99.9 = %f, p99.99 = %f", - metrics.serviceTimeP50, - metrics.serviceTimeP90, - metrics.serviceTimeP95, - metrics.serviceTimeP99, - metrics.serviceTimeP999, - metrics.serviceTimeP9999 + metrics.serviceTimeP50(), + metrics.serviceTimeP90(), + metrics.serviceTimeP95(), + metrics.serviceTimeP99(), + metrics.serviceTimeP999(), + metrics.serviceTimeP9999() ); String latencies = String.format( Locale.ROOT, "Latency [ms]: p50 = %f, p90 = %f, p95 = %f, p99 = %f, p99.9 = %f, p99.99 = %f", - metrics.latencyP50, - metrics.latencyP90, - metrics.latencyP95, - metrics.latencyP99, - metrics.latencyP999, - metrics.latencyP9999 + metrics.latencyP50(), + metrics.latencyP90(), + metrics.latencyP95(), + metrics.latencyP99(), + metrics.latencyP999(), + metrics.latencyP9999() ); int lineLength = Math.max(serviceTimes.length(), latencies.length()); @@ -85,7 +85,7 @@ public final class BenchmarkRunner { System.out.println(throughput); System.out.println(serviceTimes); System.out.println(latencies); - System.out.printf("success count = %d, error count = %d%n", metrics.successCount, metrics.errorCount); + System.out.printf("success count = %d, error count = %d%n", metrics.successCount(), metrics.errorCount()); System.out.println(repeat(lineLength, '-')); } } diff --git a/client/benchmark/src/main/java/org/elasticsearch/client/benchmark/metrics/Metrics.java b/client/benchmark/src/main/java/org/elasticsearch/client/benchmark/metrics/Metrics.java index cff540d665ef..deff0c7d23ef 100644 --- a/client/benchmark/src/main/java/org/elasticsearch/client/benchmark/metrics/Metrics.java +++ b/client/benchmark/src/main/java/org/elasticsearch/client/benchmark/metrics/Metrics.java @@ -7,57 +7,21 @@ */ package org.elasticsearch.client.benchmark.metrics; -public final class Metrics { - public final String operation; - public final long successCount; - public final long errorCount; - public final double throughput; - public final double serviceTimeP50; - public final double serviceTimeP90; - public final double serviceTimeP95; - public final double serviceTimeP99; - public final double serviceTimeP999; - public final double serviceTimeP9999; - public final double latencyP50; - public final double latencyP90; - public final double latencyP95; - public final double latencyP99; - public final double latencyP999; - public final double latencyP9999; - - public Metrics( - String operation, - long successCount, - long errorCount, - double throughput, - double serviceTimeP50, - double serviceTimeP90, - double serviceTimeP95, - double serviceTimeP99, - double serviceTimeP999, - double serviceTimeP9999, - double latencyP50, - double latencyP90, - double latencyP95, - double latencyP99, - double latencyP999, - double latencyP9999 - ) { - this.operation = operation; - this.successCount = successCount; - this.errorCount = errorCount; - this.throughput = throughput; - this.serviceTimeP50 = serviceTimeP50; - this.serviceTimeP90 = serviceTimeP90; - this.serviceTimeP95 = serviceTimeP95; - this.serviceTimeP99 = serviceTimeP99; - this.serviceTimeP999 = serviceTimeP999; - this.serviceTimeP9999 = serviceTimeP9999; - this.latencyP50 = latencyP50; - this.latencyP90 = latencyP90; - this.latencyP95 = latencyP95; - this.latencyP99 = latencyP99; - this.latencyP999 = latencyP999; - this.latencyP9999 = latencyP9999; - } -} +public record Metrics( + String operation, + long successCount, + long errorCount, + double throughput, + double serviceTimeP50, + double serviceTimeP90, + double serviceTimeP95, + double serviceTimeP99, + double serviceTimeP999, + double serviceTimeP9999, + double latencyP50, + double latencyP90, + double latencyP95, + double latencyP99, + double latencyP999, + double latencyP9999 +) {} diff --git a/client/benchmark/src/main/java/org/elasticsearch/client/benchmark/metrics/Sample.java b/client/benchmark/src/main/java/org/elasticsearch/client/benchmark/metrics/Sample.java index 26e6c47dbc0c..ae8da1444d3c 100644 --- a/client/benchmark/src/main/java/org/elasticsearch/client/benchmark/metrics/Sample.java +++ b/client/benchmark/src/main/java/org/elasticsearch/client/benchmark/metrics/Sample.java @@ -7,20 +7,7 @@ */ package org.elasticsearch.client.benchmark.metrics; -public final class Sample { - private final String operation; - private final long expectedStartTimestamp; - private final long startTimestamp; - private final long stopTimestamp; - private final boolean success; - - public Sample(String operation, long expectedStartTimestamp, long startTimestamp, long stopTimestamp, boolean success) { - this.operation = operation; - this.expectedStartTimestamp = expectedStartTimestamp; - this.startTimestamp = startTimestamp; - this.stopTimestamp = stopTimestamp; - this.success = success; - } +public record Sample(String operation, long expectedStartTimestamp, long startTimestamp, long stopTimestamp, boolean success) { public String getOperation() { return operation; diff --git a/distribution/tools/launchers/src/main/java/org/elasticsearch/tools/launchers/BootstrapJvmOptions.java b/distribution/tools/launchers/src/main/java/org/elasticsearch/tools/launchers/BootstrapJvmOptions.java index 190e5e318d2c..3a1392005a83 100644 --- a/distribution/tools/launchers/src/main/java/org/elasticsearch/tools/launchers/BootstrapJvmOptions.java +++ b/distribution/tools/launchers/src/main/java/org/elasticsearch/tools/launchers/BootstrapJvmOptions.java @@ -99,13 +99,5 @@ public class BootstrapJvmOptions { } // package-private for testing - static class PluginInfo { - public final List jarFiles; - public final Properties properties; - - PluginInfo(List jarFiles, Properties properties) { - this.jarFiles = jarFiles; - this.properties = properties; - } - } + record PluginInfo(List jarFiles, Properties properties) {} } diff --git a/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/SslConfiguration.java b/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/SslConfiguration.java index 97e6f53278f7..2af3c5076959 100644 --- a/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/SslConfiguration.java +++ b/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/SslConfiguration.java @@ -28,11 +28,19 @@ import javax.net.ssl.X509ExtendedTrustManager; /** * A object encapsulating all necessary configuration for an SSL context (client or server). - * The configuration itself is immutable, but the {@link #getKeyConfig() key config} and - * {@link #getTrustConfig() trust config} may depend on reading key and certificate material + * The configuration itself is immutable, but the {@link #keyConfig() key config} and + * {@link #trustConfig() trust config} may depend on reading key and certificate material * from files (see {@link #getDependentFiles()}, and the content of those files may change. */ -public class SslConfiguration { +public record SslConfiguration( + boolean explicitlyConfigured, + SslTrustConfig trustConfig, + SslKeyConfig keyConfig, + SslVerificationMode verificationMode, + SslClientAuthenticationMode clientAuth, + List ciphers, + List supportedProtocols +) { /** * An ordered map of protocol algorithms to SSLContext algorithms. The map is ordered from most @@ -41,6 +49,7 @@ public class SslConfiguration { * Java Security Standard Algorithm Names Documentation for Java 11. */ static final Map ORDERED_PROTOCOL_ALGORITHM_MAP; + static { LinkedHashMap protocolAlgorithmMap = new LinkedHashMap<>(); try { @@ -58,14 +67,6 @@ public class SslConfiguration { ORDERED_PROTOCOL_ALGORITHM_MAP = Collections.unmodifiableMap(protocolAlgorithmMap); } - private final boolean explicitlyConfigured; - private final SslTrustConfig trustConfig; - private final SslKeyConfig keyConfig; - private final SslVerificationMode verificationMode; - private final SslClientAuthenticationMode clientAuth; - private final List ciphers; - private final List supportedProtocols; - public SslConfiguration( boolean explicitlyConfigured, SslTrustConfig trustConfig, @@ -90,30 +91,10 @@ public class SslConfiguration { this.supportedProtocols = Collections.unmodifiableList(supportedProtocols); } - public SslTrustConfig getTrustConfig() { - return trustConfig; - } - - public SslKeyConfig getKeyConfig() { - return keyConfig; - } - - public SslVerificationMode getVerificationMode() { - return verificationMode; - } - - public SslClientAuthenticationMode getClientAuth() { - return clientAuth; - } - public List getCipherSuites() { return ciphers; } - public List getSupportedProtocols() { - return supportedProtocols; - } - /** * @return A collection of files that are used by this SSL configuration. If the contents of these files change, then any * subsequent call to {@link #createSslContext()} (or similar methods) may create a context with different behaviour. @@ -139,7 +120,7 @@ public class SslConfiguration { /** * Dynamically create a new SSL context based on the current state of the configuration. - * Because the {@link #getKeyConfig() key config} and {@link #getTrustConfig() trust config} may change based on the + * Because the {@link #keyConfig() key config} and {@link #trustConfig() trust config} may change based on the * contents of their referenced files (see {@link #getDependentFiles()}, consecutive calls to this method may * return ssl-contexts with different configurations. */ @@ -157,7 +138,7 @@ public class SslConfiguration { /** * Picks the best (highest security / most recent standard) SSL/TLS protocol (/version) that is supported by the - * {@link #getSupportedProtocols() configured protocols}. + * {@link #supportedProtocols() configured protocols}. */ private String contextProtocol() { if (supportedProtocols.isEmpty()) { @@ -173,25 +154,7 @@ public class SslConfiguration { ); } - @Override - public String toString() { - return getClass().getSimpleName() - + '{' - + "trustConfig=" - + trustConfig - + ", keyConfig=" - + keyConfig - + ", verificationMode=" - + verificationMode - + ", clientAuth=" - + clientAuth - + ", ciphers=" - + ciphers - + ", supportedProtocols=" - + supportedProtocols - + '}'; - } - + // TODO Add explicitlyConfigured to equals&hashCode? @Override public boolean equals(Object o) { if (this == o) return true; @@ -210,7 +173,4 @@ public class SslConfiguration { return Objects.hash(trustConfig, keyConfig, verificationMode, clientAuth, ciphers, supportedProtocols); } - public boolean isExplicitlyConfigured() { - return explicitlyConfigured; - } } diff --git a/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/SslConfigurationLoader.java b/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/SslConfigurationLoader.java index e8d3fbcdc828..0bed81106c67 100644 --- a/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/SslConfigurationLoader.java +++ b/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/SslConfigurationLoader.java @@ -252,7 +252,7 @@ public abstract class SslConfigurationLoader { /** * Clients of this class should implement this method to determine whether there are any settings for a given prefix. - * This is used to populate {@link SslConfiguration#isExplicitlyConfigured()}. + * This is used to populate {@link SslConfiguration#explicitlyConfigured()}. */ protected abstract boolean hasSettings(String prefix); diff --git a/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/SslDiagnostics.java b/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/SslDiagnostics.java index e2fc4b65e0a0..b8cb6707d7b5 100644 --- a/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/SslDiagnostics.java +++ b/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/SslDiagnostics.java @@ -61,14 +61,7 @@ public class SslDiagnostics { SERVER } - private static class IssuerTrust { - private final List issuerCerts; - private final boolean verified; - - private IssuerTrust(List issuerCerts, boolean verified) { - this.issuerCerts = issuerCerts; - this.verified = verified; - } + private record IssuerTrust(List issuerCerts, boolean verified) { private static IssuerTrust noMatchingCertificate() { return new IssuerTrust(null, false); diff --git a/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/StoredCertificate.java b/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/StoredCertificate.java index 24f33a1118b5..9b66b04acdc4 100644 --- a/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/StoredCertificate.java +++ b/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/StoredCertificate.java @@ -17,64 +17,15 @@ import java.util.Objects; * Information about a certificate that is locally stored.It includes a reference to the {@link X509Certificate} itself, * as well as information about where it was loaded from. */ -public final class StoredCertificate { - - private final X509Certificate certificate; - - @Nullable - // Will be null in PKCS#11 - private final String path; - - private final String format; - - @Nullable - // Will be null in PEM - private final String alias; - - private final boolean hasPrivateKey; - - public StoredCertificate(X509Certificate certificate, String path, String format, String alias, boolean hasPrivateKey) { - this.certificate = Objects.requireNonNull(certificate, "Certificate may not be null"); - this.path = path; - this.format = Objects.requireNonNull(format, "Format may not be null"); - this.alias = alias; - this.hasPrivateKey = hasPrivateKey; - } - - public X509Certificate getCertificate() { - return certificate; - } - - public String getPath() { - return path; - } - - public String getFormat() { - return format; - } - - public String getAlias() { - return alias; - } - - public boolean hasPrivateKey() { - return hasPrivateKey; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - StoredCertificate that = (StoredCertificate) o; - return hasPrivateKey == that.hasPrivateKey - && certificate.equals(that.certificate) - && Objects.equals(path, that.path) - && format.equals(that.format) - && Objects.equals(alias, that.alias); - } - - @Override - public int hashCode() { - return Objects.hash(certificate, path, format, alias, hasPrivateKey); +public record StoredCertificate( + X509Certificate certificate, + @Nullable String path, + String format, + @Nullable String alias, + boolean hasPrivateKey +) { + public StoredCertificate { + Objects.requireNonNull(certificate, "Certificate may not be null"); + Objects.requireNonNull(format, "Format may not be null"); } } diff --git a/libs/ssl-config/src/test/java/org/elasticsearch/common/ssl/PemKeyConfigTests.java b/libs/ssl-config/src/test/java/org/elasticsearch/common/ssl/PemKeyConfigTests.java index 95d8900296bf..78aeca09ef2b 100644 --- a/libs/ssl-config/src/test/java/org/elasticsearch/common/ssl/PemKeyConfigTests.java +++ b/libs/ssl-config/src/test/java/org/elasticsearch/common/ssl/PemKeyConfigTests.java @@ -102,17 +102,17 @@ public class PemKeyConfigTests extends ESTestCase { StoredCertificate c1 = iterator.next(); StoredCertificate c2 = iterator.next(); - assertThat(c1.getCertificate().getSubjectDN().toString(), equalTo("CN=cert1")); + assertThat(c1.certificate().getSubjectDN().toString(), equalTo("CN=cert1")); assertThat(c1.hasPrivateKey(), equalTo(true)); - assertThat(c1.getAlias(), nullValue()); - assertThat(c1.getFormat(), equalTo("PEM")); - assertThat(c1.getPath(), equalTo(chain.toString())); + assertThat(c1.alias(), nullValue()); + assertThat(c1.format(), equalTo("PEM")); + assertThat(c1.path(), equalTo(chain.toString())); - assertThat(c2.getCertificate().getSubjectDN().toString(), equalTo("CN=Test CA 1")); + assertThat(c2.certificate().getSubjectDN().toString(), equalTo("CN=Test CA 1")); assertThat(c2.hasPrivateKey(), equalTo(false)); - assertThat(c2.getAlias(), nullValue()); - assertThat(c2.getFormat(), equalTo("PEM")); - assertThat(c2.getPath(), equalTo(chain.toString())); + assertThat(c2.alias(), nullValue()); + assertThat(c2.format(), equalTo("PEM")); + assertThat(c2.path(), equalTo(chain.toString())); final List> keys = keyConfig.getKeys(); assertThat(keys, iterableWithSize(1)); diff --git a/libs/ssl-config/src/test/java/org/elasticsearch/common/ssl/SslConfigurationLoaderTests.java b/libs/ssl-config/src/test/java/org/elasticsearch/common/ssl/SslConfigurationLoaderTests.java index 07cff7c180d7..5c2f24acd42b 100644 --- a/libs/ssl-config/src/test/java/org/elasticsearch/common/ssl/SslConfigurationLoaderTests.java +++ b/libs/ssl-config/src/test/java/org/elasticsearch/common/ssl/SslConfigurationLoaderTests.java @@ -75,12 +75,12 @@ public class SslConfigurationLoaderTests extends ESTestCase { .putList("test.ssl.supported_protocols", protocols) .build(); final SslConfiguration configuration = loader.load(certRoot); - assertThat(configuration.getClientAuth(), is(clientAuth)); - assertThat(configuration.getVerificationMode(), is(verificationMode)); + assertThat(configuration.clientAuth(), is(clientAuth)); + assertThat(configuration.verificationMode(), is(verificationMode)); assertThat(configuration.getCipherSuites(), equalTo(Arrays.asList(ciphers))); - assertThat(configuration.getSupportedProtocols(), equalTo(Arrays.asList(protocols))); + assertThat(configuration.supportedProtocols(), equalTo(Arrays.asList(protocols))); if (verificationMode == SslVerificationMode.NONE) { - final SslTrustConfig trustConfig = configuration.getTrustConfig(); + final SslTrustConfig trustConfig = configuration.trustConfig(); assertThat(trustConfig, instanceOf(TrustEverythingConfig.class)); } } @@ -88,7 +88,7 @@ public class SslConfigurationLoaderTests extends ESTestCase { public void testLoadTrustFromPemCAs() { settings = Settings.builder().putList("test.ssl.certificate_authorities", "ca1/ca.crt", "ca2/ca.crt", "ca3/ca.crt").build(); final SslConfiguration configuration = loader.load(certRoot); - final SslTrustConfig trustConfig = configuration.getTrustConfig(); + final SslTrustConfig trustConfig = configuration.trustConfig(); assertThat(trustConfig, instanceOf(PemTrustConfig.class)); assertThat( trustConfig.getDependentFiles(), @@ -114,7 +114,7 @@ public class SslConfigurationLoaderTests extends ESTestCase { } settings = builder.build(); final SslConfiguration configuration = loader.load(certRoot); - final SslTrustConfig trustConfig = configuration.getTrustConfig(); + final SslTrustConfig trustConfig = configuration.trustConfig(); assertThat(trustConfig, instanceOf(StoreTrustConfig.class)); assertThat(trustConfig.getDependentFiles(), containsInAnyOrder(getDataPath("/certs/ca-all/ca.p12"))); assertThat(trustConfig.createTrustManager(), notNullValue()); @@ -137,7 +137,7 @@ public class SslConfigurationLoaderTests extends ESTestCase { } settings = builder.build(); final SslConfiguration configuration = loader.load(certRoot); - final SslTrustConfig trustConfig = configuration.getTrustConfig(); + final SslTrustConfig trustConfig = configuration.trustConfig(); assertThat(trustConfig, instanceOf(StoreTrustConfig.class)); assertThat(trustConfig.getDependentFiles(), containsInAnyOrder(getDataPath("/certs/ca-all/ca.jks"))); assertThat(trustConfig.createTrustManager(), notNullValue()); @@ -159,7 +159,7 @@ public class SslConfigurationLoaderTests extends ESTestCase { } settings = builder.build(); final SslConfiguration configuration = loader.load(certRoot); - final SslKeyConfig keyConfig = configuration.getKeyConfig(); + final SslKeyConfig keyConfig = configuration.keyConfig(); assertThat(keyConfig, instanceOf(PemKeyConfig.class)); assertThat( keyConfig.getDependentFiles(), @@ -188,7 +188,7 @@ public class SslConfigurationLoaderTests extends ESTestCase { } settings = builder.build(); final SslConfiguration configuration = loader.load(certRoot); - final SslKeyConfig keyConfig = configuration.getKeyConfig(); + final SslKeyConfig keyConfig = configuration.keyConfig(); assertThat(keyConfig, instanceOf(StoreKeyConfig.class)); assertThat(keyConfig.getDependentFiles(), containsInAnyOrder(getDataPath("/certs/cert-all/certs.p12"))); assertThat(keyConfig.createKeyManager(), notNullValue()); @@ -216,7 +216,7 @@ public class SslConfigurationLoaderTests extends ESTestCase { } settings = builder.build(); final SslConfiguration configuration = loader.load(certRoot); - final SslKeyConfig keyConfig = configuration.getKeyConfig(); + final SslKeyConfig keyConfig = configuration.keyConfig(); assertThat(keyConfig, instanceOf(StoreKeyConfig.class)); assertThat(keyConfig.getDependentFiles(), containsInAnyOrder(getDataPath("/certs/cert-all/certs.jks"))); assertThat(keyConfig.createKeyManager(), notNullValue()); diff --git a/libs/ssl-config/src/test/java/org/elasticsearch/common/ssl/SslConfigurationTests.java b/libs/ssl-config/src/test/java/org/elasticsearch/common/ssl/SslConfigurationTests.java index 55aae27d659f..50e2b62cbba7 100644 --- a/libs/ssl-config/src/test/java/org/elasticsearch/common/ssl/SslConfigurationTests.java +++ b/libs/ssl-config/src/test/java/org/elasticsearch/common/ssl/SslConfigurationTests.java @@ -48,12 +48,12 @@ public class SslConfigurationTests extends ESTestCase { protocols ); - assertThat(configuration.getTrustConfig(), is(trustConfig)); - assertThat(configuration.getKeyConfig(), is(keyConfig)); - assertThat(configuration.getVerificationMode(), is(verificationMode)); - assertThat(configuration.getClientAuth(), is(clientAuth)); + assertThat(configuration.trustConfig(), is(trustConfig)); + assertThat(configuration.keyConfig(), is(keyConfig)); + assertThat(configuration.verificationMode(), is(verificationMode)); + assertThat(configuration.clientAuth(), is(clientAuth)); assertThat(configuration.getCipherSuites(), is(ciphers)); - assertThat(configuration.getSupportedProtocols(), is(protocols)); + assertThat(configuration.supportedProtocols(), is(protocols)); assertThat(configuration.toString(), containsString("TEST-TRUST")); assertThat(configuration.toString(), containsString("TEST-KEY")); @@ -84,12 +84,12 @@ public class SslConfigurationTests extends ESTestCase { configuration, orig -> new SslConfiguration( true, - orig.getTrustConfig(), - orig.getKeyConfig(), - orig.getVerificationMode(), - orig.getClientAuth(), + orig.trustConfig(), + orig.keyConfig(), + orig.verificationMode(), + orig.clientAuth(), orig.getCipherSuites(), - orig.getSupportedProtocols() + orig.supportedProtocols() ), this::mutateSslConfiguration ); @@ -99,37 +99,37 @@ public class SslConfigurationTests extends ESTestCase { return switch (randomIntBetween(1, 4)) { case 1 -> new SslConfiguration( true, - orig.getTrustConfig(), - orig.getKeyConfig(), - randomValueOtherThan(orig.getVerificationMode(), () -> randomFrom(SslVerificationMode.values())), - orig.getClientAuth(), + orig.trustConfig(), + orig.keyConfig(), + randomValueOtherThan(orig.verificationMode(), () -> randomFrom(SslVerificationMode.values())), + orig.clientAuth(), orig.getCipherSuites(), - orig.getSupportedProtocols() + orig.supportedProtocols() ); case 2 -> new SslConfiguration( true, - orig.getTrustConfig(), - orig.getKeyConfig(), - orig.getVerificationMode(), - randomValueOtherThan(orig.getClientAuth(), () -> randomFrom(SslClientAuthenticationMode.values())), + orig.trustConfig(), + orig.keyConfig(), + orig.verificationMode(), + randomValueOtherThan(orig.clientAuth(), () -> randomFrom(SslClientAuthenticationMode.values())), orig.getCipherSuites(), - orig.getSupportedProtocols() + orig.supportedProtocols() ); case 3 -> new SslConfiguration( true, - orig.getTrustConfig(), - orig.getKeyConfig(), - orig.getVerificationMode(), - orig.getClientAuth(), + orig.trustConfig(), + orig.keyConfig(), + orig.verificationMode(), + orig.clientAuth(), DEFAULT_CIPHERS, - orig.getSupportedProtocols() + orig.supportedProtocols() ); default -> new SslConfiguration( true, - orig.getTrustConfig(), - orig.getKeyConfig(), - orig.getVerificationMode(), - orig.getClientAuth(), + orig.trustConfig(), + orig.keyConfig(), + orig.verificationMode(), + orig.clientAuth(), orig.getCipherSuites(), Arrays.asList(VALID_PROTOCOLS) ); diff --git a/libs/x-content/src/main/java/org/elasticsearch/xcontent/XContentLocation.java b/libs/x-content/src/main/java/org/elasticsearch/xcontent/XContentLocation.java index 9c8ae28d05cc..e821b3893d26 100644 --- a/libs/x-content/src/main/java/org/elasticsearch/xcontent/XContentLocation.java +++ b/libs/x-content/src/main/java/org/elasticsearch/xcontent/XContentLocation.java @@ -14,19 +14,10 @@ package org.elasticsearch.xcontent; * position of a parsing error to end users and consequently have line and * column numbers starting from 1. */ -public final class XContentLocation { +public record XContentLocation(int lineNumber, int columnNumber) { public static final XContentLocation UNKNOWN = new XContentLocation(-1, -1); - public final int lineNumber; - public final int columnNumber; - - public XContentLocation(int lineNumber, int columnNumber) { - super(); - this.lineNumber = lineNumber; - this.columnNumber = columnNumber; - } - @Override public String toString() { return lineNumber + ":" + columnNumber; diff --git a/libs/x-content/src/main/java/org/elasticsearch/xcontent/XContentParseException.java b/libs/x-content/src/main/java/org/elasticsearch/xcontent/XContentParseException.java index d628cad4152c..cc2af6b52d77 100644 --- a/libs/x-content/src/main/java/org/elasticsearch/xcontent/XContentParseException.java +++ b/libs/x-content/src/main/java/org/elasticsearch/xcontent/XContentParseException.java @@ -34,11 +34,11 @@ public class XContentParseException extends IllegalArgumentException { } public int getLineNumber() { - return location.map(l -> l.lineNumber).orElse(-1); + return location.map(l -> l.lineNumber()).orElse(-1); } public int getColumnNumber() { - return location.map(l -> l.columnNumber).orElse(-1); + return location.map(l -> l.columnNumber()).orElse(-1); } @Nullable diff --git a/libs/x-content/src/test/java/org/elasticsearch/xcontent/SimpleStruct.java b/libs/x-content/src/test/java/org/elasticsearch/xcontent/SimpleStruct.java index afba4514bda8..c8e5547a45ba 100644 --- a/libs/x-content/src/test/java/org/elasticsearch/xcontent/SimpleStruct.java +++ b/libs/x-content/src/test/java/org/elasticsearch/xcontent/SimpleStruct.java @@ -8,10 +8,7 @@ package org.elasticsearch.xcontent; -import org.elasticsearch.common.Strings; - import java.io.IOException; -import java.util.Objects; import static org.elasticsearch.xcontent.ConstructingObjectParser.constructorArg; @@ -19,7 +16,7 @@ import static org.elasticsearch.xcontent.ConstructingObjectParser.constructorArg * Simple structure with 3 fields: int, double and String. * Used for testing parsers. */ -class SimpleStruct implements ToXContentObject { +record SimpleStruct(int i, double d, String s) implements ToXContentObject { static SimpleStruct fromXContent(XContentParser parser) { return PARSER.apply(parser, null); @@ -42,16 +39,6 @@ class SimpleStruct implements ToXContentObject { PARSER.declareString(constructorArg(), S); } - private final int i; - private final double d; - private final String s; - - SimpleStruct(int i, double d, String s) { - this.i = i; - this.d = d; - this.s = s; - } - @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { return builder.startObject() @@ -60,22 +47,4 @@ class SimpleStruct implements ToXContentObject { .field(S.getPreferredName(), s) .endObject(); } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - SimpleStruct other = (SimpleStruct) o; - return i == other.i && d == other.d && Objects.equals(s, other.s); - } - - @Override - public int hashCode() { - return Objects.hash(i, d, s); - } - - @Override - public String toString() { - return Strings.toString(this); - } } diff --git a/modules/ingest-geoip/src/internalClusterTest/java/org/elasticsearch/ingest/geoip/GeoIpDownloaderIT.java b/modules/ingest-geoip/src/internalClusterTest/java/org/elasticsearch/ingest/geoip/GeoIpDownloaderIT.java index 9f353a45544e..29509eb7cfad 100644 --- a/modules/ingest-geoip/src/internalClusterTest/java/org/elasticsearch/ingest/geoip/GeoIpDownloaderIT.java +++ b/modules/ingest-geoip/src/internalClusterTest/java/org/elasticsearch/ingest/geoip/GeoIpDownloaderIT.java @@ -217,14 +217,14 @@ public class GeoIpDownloaderIT extends AbstractGeoIpIT { public void testUpdatedTimestamp() throws Exception { assumeTrue("only test with fixture to have stable results", ENDPOINT != null); testGeoIpDatabasesDownload(); - long lastCheck = getGeoIpTaskState().getDatabases().get("GeoLite2-ASN.mmdb").getLastCheck(); + long lastCheck = getGeoIpTaskState().getDatabases().get("GeoLite2-ASN.mmdb").lastCheck(); ClusterUpdateSettingsResponse settingsResponse = client().admin() .cluster() .prepareUpdateSettings() .setPersistentSettings(Settings.builder().put(GeoIpDownloader.POLL_INTERVAL_SETTING.getKey(), TimeValue.timeValueDays(2))) .get(); assertTrue(settingsResponse.isAcknowledged()); - assertBusy(() -> assertNotEquals(lastCheck, getGeoIpTaskState().getDatabases().get("GeoLite2-ASN.mmdb").getLastCheck())); + assertBusy(() -> assertNotEquals(lastCheck, getGeoIpTaskState().getDatabases().get("GeoLite2-ASN.mmdb").lastCheck())); testGeoIpDatabasesDownload(); } @@ -247,8 +247,8 @@ public class GeoIpDownloaderIT extends AbstractGeoIpIT { assertEquals(Set.of("GeoLite2-ASN.mmdb", "GeoLite2-City.mmdb", "GeoLite2-Country.mmdb"), state.getDatabases().keySet()); GeoIpTaskState.Metadata metadata = state.get(id); BoolQueryBuilder queryBuilder = new BoolQueryBuilder().filter(new MatchQueryBuilder("name", id)) - .filter(new RangeQueryBuilder("chunk").from(metadata.getFirstChunk()).to(metadata.getLastChunk(), true)); - int size = metadata.getLastChunk() - metadata.getFirstChunk() + 1; + .filter(new RangeQueryBuilder("chunk").from(metadata.firstChunk()).to(metadata.lastChunk(), true)); + int size = metadata.lastChunk() - metadata.firstChunk() + 1; SearchResponse res = client().prepareSearch(GeoIpDownloader.DATABASES_INDEX) .setSize(size) .setQuery(queryBuilder) @@ -268,7 +268,7 @@ public class GeoIpDownloaderIT extends AbstractGeoIpIT { TarInputStream stream = new TarInputStream(new GZIPInputStream(new MultiByteArrayInputStream(data))); TarInputStream.TarEntry entry; while ((entry = stream.getNextEntry()) != null) { - if (entry.getName().endsWith(".mmdb")) { + if (entry.name().endsWith(".mmdb")) { break; } } diff --git a/modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/DatabaseNodeService.java b/modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/DatabaseNodeService.java index a6ac4b0a390b..aab5923f139b 100644 --- a/modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/DatabaseNodeService.java +++ b/modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/DatabaseNodeService.java @@ -207,7 +207,7 @@ public final class DatabaseNodeService implements Closeable { String name = e.getKey(); GeoIpTaskState.Metadata metadata = e.getValue(); DatabaseReaderLazyLoader reference = databases.get(name); - String remoteMd5 = metadata.getMd5(); + String remoteMd5 = metadata.md5(); String localMd5 = reference != null ? reference.getMd5() : null; if (Objects.equals(localMd5, remoteMd5)) { LOGGER.debug("Current reference of [{}] is up to date [{}] with was recorded in CS [{}]", name, localMd5, remoteMd5); @@ -234,7 +234,7 @@ public final class DatabaseNodeService implements Closeable { } void retrieveAndUpdateDatabase(String databaseName, GeoIpTaskState.Metadata metadata) throws IOException { - final String recordedMd5 = metadata.getMd5(); + final String recordedMd5 = metadata.md5(); // This acts as a lock, if this method for a specific db is executed later and downloaded for this db is still ongoing then // FileAlreadyExistsException is thrown and this method silently returns. @@ -281,11 +281,11 @@ public final class DatabaseNodeService implements Closeable { TarInputStream.TarEntry entry; while ((entry = is.getNextEntry()) != null) { // there might be ./ entry in tar, we should skip it - if (entry.isNotFile()) { + if (entry.notFile()) { continue; } // flatten structure, remove any directories present from the path (should be ./ only) - String name = entry.getName().substring(entry.getName().lastIndexOf('/') + 1); + String name = entry.name().substring(entry.name().lastIndexOf('/') + 1); if (name.startsWith(databaseName)) { Files.copy(is, databaseTmpFile, StandardCopyOption.REPLACE_EXISTING); } else { @@ -378,15 +378,15 @@ public final class DatabaseNodeService implements Closeable { // Need to run the search from a different thread, since this is executed from cluster state applier thread: genericExecutor.accept(() -> { MessageDigest md = MessageDigests.md5(); - int firstChunk = metadata.getFirstChunk(); - int lastChunk = metadata.getLastChunk(); + int firstChunk = metadata.firstChunk(); + int lastChunk = metadata.lastChunk(); try { // TODO: invoke open point in time api when this api is moved from xpack core to server module. // (so that we have a consistent view of the chunk documents while doing the lookups) // (the chance that the documents change is rare, given the low frequency of the updates for these databases) for (int chunk = firstChunk; chunk <= lastChunk; chunk++) { SearchRequest searchRequest = new SearchRequest(GeoIpDownloader.DATABASES_INDEX); - String id = String.format(Locale.ROOT, "%s_%d_%d", databaseName, chunk, metadata.getLastUpdate()); + String id = String.format(Locale.ROOT, "%s_%d_%d", databaseName, chunk, metadata.lastUpdate()); searchRequest.source().query(new TermQueryBuilder("_id", id)); // At most once a day a few searches may be executed to fetch the new files, diff --git a/modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/GeoIpDownloader.java b/modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/GeoIpDownloader.java index 767ab7c1626c..4d1c594ab7b7 100644 --- a/modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/GeoIpDownloader.java +++ b/modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/GeoIpDownloader.java @@ -147,7 +147,7 @@ public class GeoIpDownloader extends AllocatedPersistentTask { void processDatabase(Map databaseInfo) { String name = databaseInfo.get("name").toString().replace(".tgz", "") + ".mmdb"; String md5 = (String) databaseInfo.get("md5_hash"); - if (state.contains(name) && Objects.equals(md5, state.get(name).getMd5())) { + if (state.contains(name) && Objects.equals(md5, state.get(name).md5())) { updateTimestamp(name, state.get(name)); return; } @@ -160,7 +160,7 @@ public class GeoIpDownloader extends AllocatedPersistentTask { } long start = System.currentTimeMillis(); try (InputStream is = httpClient.get(url)) { - int firstChunk = state.contains(name) ? state.get(name).getLastChunk() + 1 : 0; + int firstChunk = state.contains(name) ? state.get(name).lastChunk() + 1 : 0; int lastChunk = indexChunks(name, is, firstChunk, md5, start); if (lastChunk > firstChunk) { state = state.put(name, new Metadata(start, firstChunk, lastChunk - 1, md5, start)); @@ -192,10 +192,7 @@ public class GeoIpDownloader extends AllocatedPersistentTask { // visible for testing protected void updateTimestamp(String name, Metadata old) { logger.debug("geoip database [{}] is up to date, updated timestamp", name); - state = state.put( - name, - new Metadata(old.getLastUpdate(), old.getFirstChunk(), old.getLastChunk(), old.getMd5(), System.currentTimeMillis()) - ); + state = state.put(name, new Metadata(old.lastUpdate(), old.firstChunk(), old.lastChunk(), old.md5(), System.currentTimeMillis())); stats = stats.skippedDownload(); updateTaskState(); } @@ -279,10 +276,10 @@ public class GeoIpDownloader extends AllocatedPersistentTask { .peek(e -> { String name = e.getKey(); Metadata meta = e.getValue(); - deleteOldChunks(name, meta.getLastChunk() + 1); + deleteOldChunks(name, meta.lastChunk() + 1); state = state.put( name, - new Metadata(meta.getLastUpdate(), meta.getFirstChunk(), meta.getLastChunk(), meta.getMd5(), meta.getLastCheck() - 1) + new Metadata(meta.lastUpdate(), meta.firstChunk(), meta.lastChunk(), meta.md5(), meta.lastCheck() - 1) ); updateTaskState(); }) diff --git a/modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/GeoIpTaskState.java b/modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/GeoIpTaskState.java index f18f1e10af32..2d767a4eed44 100644 --- a/modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/GeoIpTaskState.java +++ b/modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/GeoIpTaskState.java @@ -139,7 +139,7 @@ class GeoIpTaskState implements PersistentTaskState, VersionedNamedWriteable { }); } - static class Metadata implements ToXContentObject { + record Metadata(long lastUpdate, int firstChunk, int lastChunk, String md5, long lastCheck) implements ToXContentObject { static final String NAME = GEOIP_DOWNLOADER + "-metadata"; private static final ParseField LAST_CHECK = new ParseField("last_check"); @@ -176,22 +176,8 @@ class GeoIpTaskState implements PersistentTaskState, VersionedNamedWriteable { } } - private final long lastUpdate; - private final int firstChunk; - private final int lastChunk; - private final String md5; - private final long lastCheck; - - Metadata(long lastUpdate, int firstChunk, int lastChunk, String md5, long lastCheck) { - this.lastUpdate = lastUpdate; - this.firstChunk = firstChunk; - this.lastChunk = lastChunk; - this.md5 = Objects.requireNonNull(md5); - this.lastCheck = lastCheck; - } - - public long getLastUpdate() { - return lastUpdate; + Metadata { + Objects.requireNonNull(md5); } public boolean isCloseToExpiration() { @@ -203,39 +189,6 @@ class GeoIpTaskState implements PersistentTaskState, VersionedNamedWriteable { return Instant.ofEpochMilli(lastCheck).isAfter(Instant.now().minus(valid.getMillis(), ChronoUnit.MILLIS)); } - public int getFirstChunk() { - return firstChunk; - } - - public int getLastChunk() { - return lastChunk; - } - - public String getMd5() { - return md5; - } - - public long getLastCheck() { - return lastCheck; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - Metadata metadata = (Metadata) o; - return lastUpdate == metadata.lastUpdate - && firstChunk == metadata.firstChunk - && lastChunk == metadata.lastChunk - && lastCheck == metadata.lastCheck - && md5.equals(metadata.md5); - } - - @Override - public int hashCode() { - return Objects.hash(lastUpdate, firstChunk, lastChunk, md5, lastCheck); - } - @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); diff --git a/modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/TarInputStream.java b/modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/TarInputStream.java index a9fc2f20503a..22d8e6c01a3e 100644 --- a/modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/TarInputStream.java +++ b/modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/TarInputStream.java @@ -103,21 +103,5 @@ class TarInputStream extends FilterInputStream { } } - static class TarEntry { - private final String name; - private final boolean notFile; - - TarEntry(String name, boolean notFile) { - this.name = name; - this.notFile = notFile; - } - - public String getName() { - return name; - } - - public boolean isNotFile() { - return notFile; - } - } + record TarEntry(String name, boolean notFile) {} } diff --git a/modules/ingest-geoip/src/test/java/org/elasticsearch/ingest/geoip/GeoIpDownloaderTests.java b/modules/ingest-geoip/src/test/java/org/elasticsearch/ingest/geoip/GeoIpDownloaderTests.java index 5d9ec2183513..2ac85ab891ff 100644 --- a/modules/ingest-geoip/src/test/java/org/elasticsearch/ingest/geoip/GeoIpDownloaderTests.java +++ b/modules/ingest-geoip/src/test/java/org/elasticsearch/ingest/geoip/GeoIpDownloaderTests.java @@ -249,8 +249,8 @@ public class GeoIpDownloaderTests extends ESTestCase { ) { @Override void updateTaskState() { - assertEquals(0, state.get("test").getFirstChunk()); - assertEquals(10, state.get("test").getLastChunk()); + assertEquals(0, state.get("test").firstChunk()); + assertEquals(10, state.get("test").lastChunk()); } @Override @@ -295,8 +295,8 @@ public class GeoIpDownloaderTests extends ESTestCase { ) { @Override void updateTaskState() { - assertEquals(9, state.get("test.mmdb").getFirstChunk()); - assertEquals(10, state.get("test.mmdb").getLastChunk()); + assertEquals(9, state.get("test.mmdb").firstChunk()); + assertEquals(10, state.get("test.mmdb").lastChunk()); } @Override diff --git a/modules/ingest-geoip/src/test/java/org/elasticsearch/ingest/geoip/TarInputStreamTests.java b/modules/ingest-geoip/src/test/java/org/elasticsearch/ingest/geoip/TarInputStreamTests.java index ec3487cb92b8..8ebf4b1cb740 100644 --- a/modules/ingest-geoip/src/test/java/org/elasticsearch/ingest/geoip/TarInputStreamTests.java +++ b/modules/ingest-geoip/src/test/java/org/elasticsearch/ingest/geoip/TarInputStreamTests.java @@ -36,11 +36,11 @@ public class TarInputStreamTests extends ESTestCase { assertNotNull(is); for (Entry entry : entries) { TarInputStream.TarEntry tarEntry = tis.getNextEntry(); - assertEquals(entry.name, tarEntry.getName()); + assertEquals(entry.name, tarEntry.name()); if (entry.notFile == false) { assertEquals(entry.data, new String(tis.readAllBytes(), StandardCharsets.UTF_8)); } - assertEquals(entry.notFile, tarEntry.isNotFile()); + assertEquals(entry.notFile, tarEntry.notFile()); } assertNull(tis.getNextEntry()); } diff --git a/modules/ingest-user-agent/src/main/java/org/elasticsearch/ingest/useragent/DeviceTypeParser.java b/modules/ingest-user-agent/src/main/java/org/elasticsearch/ingest/useragent/DeviceTypeParser.java index 6ca60cb709a1..2ab7bbbb1b32 100644 --- a/modules/ingest-user-agent/src/main/java/org/elasticsearch/ingest/useragent/DeviceTypeParser.java +++ b/modules/ingest-user-agent/src/main/java/org/elasticsearch/ingest/useragent/DeviceTypeParser.java @@ -92,18 +92,18 @@ public class DeviceTypeParser { String deviceType = null; switch (patternKey) { case OS_PARSERS: - if (os != null && os.name != null) { - deviceType = findMatch(deviceTypePatterns.get(patternKey), os.name); + if (os != null && os.name() != null) { + deviceType = findMatch(deviceTypePatterns.get(patternKey), os.name()); } break; case BROWSER_PARSER: - if (userAgent != null && userAgent.name != null) { - deviceType = findMatch(deviceTypePatterns.get(patternKey), userAgent.name); + if (userAgent != null && userAgent.name() != null) { + deviceType = findMatch(deviceTypePatterns.get(patternKey), userAgent.name()); } break; case DEVICE_PARSER: - if (device != null && device.name != null) { - deviceType = findMatch(deviceTypePatterns.get(patternKey), device.name); + if (device != null && device.name() != null) { + deviceType = findMatch(deviceTypePatterns.get(patternKey), device.name()); } break; default: diff --git a/modules/ingest-user-agent/src/main/java/org/elasticsearch/ingest/useragent/UserAgentCache.java b/modules/ingest-user-agent/src/main/java/org/elasticsearch/ingest/useragent/UserAgentCache.java index 01196a5e40b3..53dee030111c 100644 --- a/modules/ingest-user-agent/src/main/java/org/elasticsearch/ingest/useragent/UserAgentCache.java +++ b/modules/ingest-user-agent/src/main/java/org/elasticsearch/ingest/useragent/UserAgentCache.java @@ -12,8 +12,6 @@ import org.elasticsearch.common.cache.Cache; import org.elasticsearch.common.cache.CacheBuilder; import org.elasticsearch.ingest.useragent.UserAgentParser.Details; -import java.util.Objects; - class UserAgentCache { private final Cache cache; @@ -29,26 +27,5 @@ class UserAgentCache { cache.put(new CompositeCacheKey(parserName, userAgent), details); } - private static final class CompositeCacheKey { - private final String parserName; - private final String userAgent; - - CompositeCacheKey(String parserName, String userAgent) { - this.parserName = parserName; - this.userAgent = userAgent; - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof CompositeCacheKey cck) { - return parserName.equals(cck.parserName) && userAgent.equals(cck.userAgent); - } - return false; - } - - @Override - public int hashCode() { - return Objects.hash(parserName, userAgent); - } - } + private record CompositeCacheKey(String parserName, String userAgent) {} } diff --git a/modules/ingest-user-agent/src/main/java/org/elasticsearch/ingest/useragent/UserAgentParser.java b/modules/ingest-user-agent/src/main/java/org/elasticsearch/ingest/useragent/UserAgentParser.java index 65dac3af76db..6eba8501f882 100644 --- a/modules/ingest-user-agent/src/main/java/org/elasticsearch/ingest/useragent/UserAgentParser.java +++ b/modules/ingest-user-agent/src/main/java/org/elasticsearch/ingest/useragent/UserAgentParser.java @@ -202,58 +202,21 @@ final class UserAgentParser { return null; } - static final class Details { - public final VersionedName userAgent; - public final VersionedName operatingSystem; - public final VersionedName device; - public final String deviceType; + record Details(VersionedName userAgent, VersionedName operatingSystem, VersionedName device, String deviceType) {} - Details(VersionedName userAgent, VersionedName operatingSystem, VersionedName device, String deviceType) { - this.userAgent = userAgent; - this.operatingSystem = operatingSystem; - this.device = device; - this.deviceType = deviceType; - } - } - - static final class VersionedName { - public final String name; - public final String major; - public final String minor; - public final String patch; - public final String build; - - VersionedName(String name, String major, String minor, String patch, String build) { - this.name = name; - this.major = major; - this.minor = minor; - this.patch = patch; - this.build = build; - } - } + record VersionedName(String name, String major, String minor, String patch, String build) {} /** * One of: user agent, operating system, device */ - static final class UserAgentSubpattern { - private final Pattern pattern; - private final String nameReplacement, v1Replacement, v2Replacement, v3Replacement, v4Replacement; - - UserAgentSubpattern( - Pattern pattern, - String nameReplacement, - String v1Replacement, - String v2Replacement, - String v3Replacement, - String v4Replacement - ) { - this.pattern = pattern; - this.nameReplacement = nameReplacement; - this.v1Replacement = v1Replacement; - this.v2Replacement = v2Replacement; - this.v3Replacement = v3Replacement; - this.v4Replacement = v4Replacement; - } + record UserAgentSubpattern( + Pattern pattern, + String nameReplacement, + String v1Replacement, + String v2Replacement, + String v3Replacement, + String v4Replacement + ) { public VersionedName match(String agentString) { String name = null, major = null, minor = null, patch = null, build = null; diff --git a/modules/ingest-user-agent/src/main/java/org/elasticsearch/ingest/useragent/UserAgentProcessor.java b/modules/ingest-user-agent/src/main/java/org/elasticsearch/ingest/useragent/UserAgentProcessor.java index 869563f58854..203d3c422f4e 100644 --- a/modules/ingest-user-agent/src/main/java/org/elasticsearch/ingest/useragent/UserAgentProcessor.java +++ b/modules/ingest-user-agent/src/main/java/org/elasticsearch/ingest/useragent/UserAgentProcessor.java @@ -89,22 +89,22 @@ public class UserAgentProcessor extends AbstractProcessor { uaDetails.put("original", userAgent); break; case NAME: - if (uaClient.userAgent != null && uaClient.userAgent.name != null) { - uaDetails.put("name", uaClient.userAgent.name); + if (uaClient.userAgent() != null && uaClient.userAgent().name() != null) { + uaDetails.put("name", uaClient.userAgent().name()); } else { uaDetails.put("name", "Other"); } break; case VERSION: StringBuilder version = new StringBuilder(); - if (uaClient.userAgent != null && uaClient.userAgent.major != null) { - version.append(uaClient.userAgent.major); - if (uaClient.userAgent.minor != null) { - version.append(".").append(uaClient.userAgent.minor); - if (uaClient.userAgent.patch != null) { - version.append(".").append(uaClient.userAgent.patch); - if (uaClient.userAgent.build != null) { - version.append(".").append(uaClient.userAgent.build); + if (uaClient.userAgent() != null && uaClient.userAgent().major() != null) { + version.append(uaClient.userAgent().major()); + if (uaClient.userAgent().minor() != null) { + version.append(".").append(uaClient.userAgent().minor()); + if (uaClient.userAgent().patch() != null) { + version.append(".").append(uaClient.userAgent().patch()); + if (uaClient.userAgent().build() != null) { + version.append(".").append(uaClient.userAgent().build()); } } } @@ -112,24 +112,24 @@ public class UserAgentProcessor extends AbstractProcessor { } break; case OS: - if (uaClient.operatingSystem != null) { + if (uaClient.operatingSystem() != null) { Map osDetails = new HashMap<>(3); - if (uaClient.operatingSystem.name != null) { - osDetails.put("name", uaClient.operatingSystem.name); + if (uaClient.operatingSystem().name() != null) { + osDetails.put("name", uaClient.operatingSystem().name()); StringBuilder sb = new StringBuilder(); - if (uaClient.operatingSystem.major != null) { - sb.append(uaClient.operatingSystem.major); - if (uaClient.operatingSystem.minor != null) { - sb.append(".").append(uaClient.operatingSystem.minor); - if (uaClient.operatingSystem.patch != null) { - sb.append(".").append(uaClient.operatingSystem.patch); - if (uaClient.operatingSystem.build != null) { - sb.append(".").append(uaClient.operatingSystem.build); + if (uaClient.operatingSystem().major() != null) { + sb.append(uaClient.operatingSystem().major()); + if (uaClient.operatingSystem().minor() != null) { + sb.append(".").append(uaClient.operatingSystem().minor()); + if (uaClient.operatingSystem().patch() != null) { + sb.append(".").append(uaClient.operatingSystem().patch()); + if (uaClient.operatingSystem().build() != null) { + sb.append(".").append(uaClient.operatingSystem().build()); } } } osDetails.put("version", sb.toString()); - osDetails.put("full", uaClient.operatingSystem.name + " " + sb.toString()); + osDetails.put("full", uaClient.operatingSystem().name() + " " + sb.toString()); } uaDetails.put("os", osDetails); } @@ -137,16 +137,16 @@ public class UserAgentProcessor extends AbstractProcessor { break; case DEVICE: Map deviceDetails = new HashMap<>(1); - if (uaClient.device != null && uaClient.device.name != null) { - deviceDetails.put("name", uaClient.device.name); + if (uaClient.device() != null && uaClient.device().name() != null) { + deviceDetails.put("name", uaClient.device().name()); if (extractDeviceType) { - deviceDetails.put("type", uaClient.deviceType); + deviceDetails.put("type", uaClient.deviceType()); } } else { deviceDetails.put("name", "Other"); if (extractDeviceType) { - if (uaClient.deviceType != null) { - deviceDetails.put("type", uaClient.deviceType); + if (uaClient.deviceType() != null) { + deviceDetails.put("type", uaClient.deviceType()); } else { deviceDetails.put("type", "Other"); } diff --git a/modules/lang-painless/spi/src/main/java/org/elasticsearch/painless/spi/annotation/AugmentedAnnotation.java b/modules/lang-painless/spi/src/main/java/org/elasticsearch/painless/spi/annotation/AugmentedAnnotation.java index c9ce8cd1b17b..1c4f7f084ff5 100644 --- a/modules/lang-painless/spi/src/main/java/org/elasticsearch/painless/spi/annotation/AugmentedAnnotation.java +++ b/modules/lang-painless/spi/src/main/java/org/elasticsearch/painless/spi/annotation/AugmentedAnnotation.java @@ -37,17 +37,6 @@ package org.elasticsearch.painless.spi.annotation; * ... * } */ -public class AugmentedAnnotation { - +public record AugmentedAnnotation(String augmentedCanonicalClassName) { public static final String NAME = "augmented"; - - private final String augmentedCanonicalClassName; - - public AugmentedAnnotation(String augmentedCanonicalClassName) { - this.augmentedCanonicalClassName = augmentedCanonicalClassName; - } - - public String getAugmentedCanonicalClassName() { - return augmentedCanonicalClassName; - } } diff --git a/modules/lang-painless/spi/src/main/java/org/elasticsearch/painless/spi/annotation/DeprecatedAnnotation.java b/modules/lang-painless/spi/src/main/java/org/elasticsearch/painless/spi/annotation/DeprecatedAnnotation.java index 4c38c4361ae3..832f74c67235 100644 --- a/modules/lang-painless/spi/src/main/java/org/elasticsearch/painless/spi/annotation/DeprecatedAnnotation.java +++ b/modules/lang-painless/spi/src/main/java/org/elasticsearch/painless/spi/annotation/DeprecatedAnnotation.java @@ -8,17 +8,6 @@ package org.elasticsearch.painless.spi.annotation; -public class DeprecatedAnnotation { - +public record DeprecatedAnnotation(String message) { public static final String NAME = "deprecated"; - - private final String message; - - public DeprecatedAnnotation(String message) { - this.message = message; - } - - public String getMessage() { - return message; - } } diff --git a/modules/lang-painless/spi/src/main/java/org/elasticsearch/painless/spi/annotation/InjectConstantAnnotation.java b/modules/lang-painless/spi/src/main/java/org/elasticsearch/painless/spi/annotation/InjectConstantAnnotation.java index d33426fe0ef4..5fb86313665e 100644 --- a/modules/lang-painless/spi/src/main/java/org/elasticsearch/painless/spi/annotation/InjectConstantAnnotation.java +++ b/modules/lang-painless/spi/src/main/java/org/elasticsearch/painless/spi/annotation/InjectConstantAnnotation.java @@ -16,9 +16,8 @@ import java.util.List; * Format: {@code inject_constant["1=foo_compiler_setting", 2="bar_compiler_setting"]} injects "foo_compiler_setting and * "bar_compiler_setting" as the first two arguments (other than receiver reference for instance methods) to the annotated method. */ -public class InjectConstantAnnotation { +public record InjectConstantAnnotation(List injects) { public static final String NAME = "inject_constant"; - public final List injects; public InjectConstantAnnotation(List injects) { this.injects = Collections.unmodifiableList(injects); diff --git a/modules/lang-painless/spi/src/test/java/org/elasticsearch/painless/AnnotationTestObject.java b/modules/lang-painless/spi/src/test/java/org/elasticsearch/painless/AnnotationTestObject.java index 4ee91eaa4a31..f6a8dcd8e9ed 100644 --- a/modules/lang-painless/spi/src/test/java/org/elasticsearch/painless/AnnotationTestObject.java +++ b/modules/lang-painless/spi/src/test/java/org/elasticsearch/painless/AnnotationTestObject.java @@ -14,31 +14,8 @@ import java.util.Map; public class AnnotationTestObject { - public static class TestAnnotation { - + public record TestAnnotation(String one, String two, String three) { public static final String NAME = "test_annotation"; - - private final String one; - private final String two; - private final String three; - - public TestAnnotation(String one, String two, String three) { - this.one = one; - this.two = two; - this.three = three; - } - - public String getOne() { - return one; - } - - public String getTwo() { - return two; - } - - public String getThree() { - return three; - } } public static class TestAnnotationParser implements WhitelistAnnotationParser { diff --git a/modules/lang-painless/spi/src/test/java/org/elasticsearch/painless/WhitelistLoaderTests.java b/modules/lang-painless/spi/src/test/java/org/elasticsearch/painless/WhitelistLoaderTests.java index ddd69bb828a6..2968ffc171e4 100644 --- a/modules/lang-painless/spi/src/test/java/org/elasticsearch/painless/WhitelistLoaderTests.java +++ b/modules/lang-painless/spi/src/test/java/org/elasticsearch/painless/WhitelistLoaderTests.java @@ -68,7 +68,7 @@ public class WhitelistLoaderTests extends ESTestCase { if ("deprecatedMethod".equals(whitelistMethod.methodName)) { assertEquals( "use another method", - ((DeprecatedAnnotation) whitelistMethod.painlessAnnotations.get(DeprecatedAnnotation.class)).getMessage() + ((DeprecatedAnnotation) whitelistMethod.painlessAnnotations.get(DeprecatedAnnotation.class)).message() ); assertEquals(1, whitelistMethod.painlessAnnotations.size()); ++count; @@ -78,9 +78,9 @@ public class WhitelistLoaderTests extends ESTestCase { AnnotationTestObject.TestAnnotation ta = ((AnnotationTestObject.TestAnnotation) whitelistMethod.painlessAnnotations.get( AnnotationTestObject.TestAnnotation.class )); - assertEquals("one", ta.getOne()); - assertEquals("two", ta.getTwo()); - assertEquals("three", ta.getThree()); + assertEquals("one", ta.one()); + assertEquals("two", ta.two()); + assertEquals("three", ta.three()); assertEquals(1, whitelistMethod.painlessAnnotations.size()); ++count; } @@ -88,14 +88,14 @@ public class WhitelistLoaderTests extends ESTestCase { if ("annotatedMultipleMethod".equals(whitelistMethod.methodName)) { assertEquals( "test", - ((DeprecatedAnnotation) whitelistMethod.painlessAnnotations.get(DeprecatedAnnotation.class)).getMessage() + ((DeprecatedAnnotation) whitelistMethod.painlessAnnotations.get(DeprecatedAnnotation.class)).message() ); AnnotationTestObject.TestAnnotation ta = ((AnnotationTestObject.TestAnnotation) whitelistMethod.painlessAnnotations.get( AnnotationTestObject.TestAnnotation.class )); - assertEquals("one", ta.getOne()); - assertEquals("two", ta.getTwo()); - assertEquals("three", ta.getThree()); + assertEquals("one", ta.one()); + assertEquals("two", ta.two()); + assertEquals("three", ta.three()); assertEquals(2, whitelistMethod.painlessAnnotations.size()); ++count; } diff --git a/modules/lang-painless/src/doc/java/org/elasticsearch/painless/JavadocExtractor.java b/modules/lang-painless/src/doc/java/org/elasticsearch/painless/JavadocExtractor.java index fd74c2f7752c..56d5262fe14b 100644 --- a/modules/lang-painless/src/doc/java/org/elasticsearch/painless/JavadocExtractor.java +++ b/modules/lang-painless/src/doc/java/org/elasticsearch/painless/JavadocExtractor.java @@ -35,7 +35,6 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Objects; import java.util.Optional; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -193,14 +192,7 @@ public class JavadocExtractor { return type; } - public static class MethodSignature { - public final String name; - public final List parameterTypes; - - public MethodSignature(String name, List parameterTypes) { - this.name = name; - this.parameterTypes = parameterTypes; - } + public record MethodSignature(String name, List parameterTypes) { public static MethodSignature fromDeclaration(MethodDeclaration declaration) { return new MethodSignature( @@ -208,29 +200,9 @@ public class JavadocExtractor { declaration.getParameters().stream().map(p -> stripTypeParameters(p.getType().asString())).collect(Collectors.toList()) ); } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if ((o instanceof MethodSignature) == false) return false; - MethodSignature that = (MethodSignature) o; - return Objects.equals(name, that.name) && Objects.equals(parameterTypes, that.parameterTypes); - } - - @Override - public int hashCode() { - return Objects.hash(name, parameterTypes); - } } - public static class ParsedMethod { - public final ParsedJavadoc javadoc; - public final List parameterNames; - - public ParsedMethod(ParsedJavadoc javadoc, List parameterNames) { - this.javadoc = javadoc; - this.parameterNames = parameterNames; - } + public record ParsedMethod(ParsedJavadoc javadoc, List parameterNames) { public ParsedMethod asAugmented() { if (parameterNames.size() == 0) { diff --git a/modules/lang-painless/src/doc/java/org/elasticsearch/painless/PainlessInfoJson.java b/modules/lang-painless/src/doc/java/org/elasticsearch/painless/PainlessInfoJson.java index 9dcfdba314f9..5797ac85cede 100644 --- a/modules/lang-painless/src/doc/java/org/elasticsearch/painless/PainlessInfoJson.java +++ b/modules/lang-painless/src/doc/java/org/elasticsearch/painless/PainlessInfoJson.java @@ -232,8 +232,8 @@ public class PainlessInfoJson { } } if (parsedMethod != null) { - javadoc = parsedMethod.javadoc; - parameterNames = parsedMethod.parameterNames; + javadoc = parsedMethod.javadoc(); + parameterNames = parsedMethod.parameterNames(); } methods.add( @@ -317,8 +317,8 @@ public class PainlessInfoJson { parsedMethod = extractor.parseClass(info.getDeclaring()).getConstructor(parameterTypes); } if (parsedMethod != null) { - parameterNames = parsedMethod.parameterNames; - javadoc = parsedMethod.javadoc; + parameterNames = parsedMethod.parameterNames(); + javadoc = parsedMethod.javadoc(); } constructors.add(new Constructor(info.getDeclaring(), parameterTypes, parameterNames, javadoc)); diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/Compiler.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/Compiler.java index 718f8e809257..87ae3a8eabeb 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/Compiler.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/Compiler.java @@ -214,7 +214,7 @@ final class Compiler { new PainlessSemanticHeaderPhase().visitClass(root, scriptScope); new PainlessSemanticAnalysisPhase().visitClass(root, scriptScope); new PainlessUserTreeToIRTreePhase().visitClass(root, scriptScope); - ClassNode classNode = (ClassNode) scriptScope.getDecoration(root, IRNodeDecoration.class).getIRNode(); + ClassNode classNode = (ClassNode) scriptScope.getDecoration(root, IRNodeDecoration.class).irNode(); new DefaultStringConcatenationOptimizationPhase().visitClass(classNode, null); new DefaultConstantFoldingOptimizationPhase().visitClass(classNode, null); new DefaultStaticConstantExtractionPhase().visitClass(classNode, scriptScope); @@ -249,7 +249,7 @@ final class Compiler { new PainlessSemanticHeaderPhase().visitClass(root, scriptScope); new PainlessSemanticAnalysisPhase().visitClass(root, scriptScope); new PainlessUserTreeToIRTreePhase().visitClass(root, scriptScope); - ClassNode classNode = (ClassNode) scriptScope.getDecoration(root, IRNodeDecoration.class).getIRNode(); + ClassNode classNode = (ClassNode) scriptScope.getDecoration(root, IRNodeDecoration.class).irNode(); new DefaultStringConcatenationOptimizationPhase().visitClass(classNode, null); new DefaultConstantFoldingOptimizationPhase().visitClass(classNode, null); new DefaultStaticConstantExtractionPhase().visitClass(classNode, scriptScope); @@ -287,7 +287,7 @@ final class Compiler { irPhaseVisitor.visitClass(root, scriptScope); } - ClassNode classNode = (ClassNode) scriptScope.getDecoration(root, IRNodeDecoration.class).getIRNode(); + ClassNode classNode = (ClassNode) scriptScope.getDecoration(root, IRNodeDecoration.class).irNode(); new DefaultStringConcatenationOptimizationPhase().visitClass(classNode, null); new DefaultConstantFoldingOptimizationPhase().visitClass(classNode, null); new DefaultStaticConstantExtractionPhase().visitClass(classNode, scriptScope); diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/Def.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/Def.java index a58125340c9b..7a9a9921c8fe 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/Def.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/Def.java @@ -256,7 +256,7 @@ public final class Def { ); } - MethodHandle handle = painlessMethod.methodHandle; + MethodHandle handle = painlessMethod.methodHandle(); Object[] injections = PainlessLookupUtility.buildInjections(painlessMethod, constants); if (injections.length > 0) { @@ -298,7 +298,7 @@ public final class Def { ); } - MethodHandle handle = method.methodHandle; + MethodHandle handle = method.methodHandle(); Object[] injections = PainlessLookupUtility.buildInjections(method, constants); if (injections.length > 0) { @@ -313,7 +313,7 @@ public final class Def { if (lambdaArgs.get(i - 1)) { Def.Encoding defEncoding = new Encoding((String) args[upTo++]); MethodHandle filter; - Class interfaceType = method.typeParameters.get(i - 1 - replaced - (defEncoding.needsInstance ? 1 : 0)); + Class interfaceType = method.typeParameters().get(i - 1 - replaced - (defEncoding.needsInstance ? 1 : 0)); if (defEncoding.isStatic) { // the implementation is strongly typed, now that we know the interface type, // we have everything. @@ -385,7 +385,7 @@ public final class Def { if (interfaceMethod == null) { throw new IllegalArgumentException("Class [" + interfaceClass + "] is not a functional interface"); } - int arity = interfaceMethod.typeParameters.size(); + int arity = interfaceMethod.typeParameters().size(); PainlessMethod implMethod = painlessLookup.lookupRuntimePainlessMethod(receiverClass, name, arity); if (implMethod == null) { throw new IllegalArgumentException( @@ -399,8 +399,8 @@ public final class Def { constants, methodHandlesLookup, interfaceType, - PainlessLookupUtility.typeToCanonicalTypeName(implMethod.targetClass), - implMethod.javaMethod.getName(), + PainlessLookupUtility.typeToCanonicalTypeName(implMethod.targetClass()), + implMethod.javaMethod().getName(), 1, false ); diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/FunctionRef.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/FunctionRef.java index 677199bdb908..816825a7700d 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/FunctionRef.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/FunctionRef.java @@ -84,8 +84,8 @@ public class FunctionRef { ); } - String interfaceMethodName = interfaceMethod.javaMethod.getName(); - MethodType interfaceMethodType = interfaceMethod.methodType.dropParameterTypes(0, 1); + String interfaceMethodName = interfaceMethod.javaMethod().getName(); + MethodType interfaceMethodType = interfaceMethod.methodType().dropParameterTypes(0, 1); String delegateClassName; boolean isDelegateInterface; boolean isDelegateAugmented; @@ -96,7 +96,7 @@ public class FunctionRef { Class delegateMethodReturnType; List> delegateMethodParameters; - int interfaceTypeParametersSize = interfaceMethod.typeParameters.size(); + int interfaceTypeParametersSize = interfaceMethod.typeParameters().size(); if ("this".equals(typeName)) { Objects.requireNonNull(functionTable); @@ -160,16 +160,16 @@ public class FunctionRef { ); } - delegateClassName = painlessConstructor.javaConstructor.getDeclaringClass().getName(); + delegateClassName = painlessConstructor.javaConstructor().getDeclaringClass().getName(); isDelegateInterface = false; isDelegateAugmented = false; delegateInvokeType = H_NEWINVOKESPECIAL; delegateMethodName = PainlessLookupUtility.CONSTRUCTOR_NAME; - delegateMethodType = painlessConstructor.methodType; + delegateMethodType = painlessConstructor.methodType(); delegateInjections = new Object[0]; - delegateMethodReturnType = painlessConstructor.javaConstructor.getDeclaringClass(); - delegateMethodParameters = painlessConstructor.typeParameters; + delegateMethodReturnType = painlessConstructor.javaConstructor().getDeclaringClass(); + delegateMethodParameters = painlessConstructor.typeParameters(); } else { if (numberOfCaptures != 0 && numberOfCaptures != 1) { throw new IllegalStateException("internal error"); @@ -225,11 +225,11 @@ public class FunctionRef { ); } - delegateClassName = painlessMethod.javaMethod.getDeclaringClass().getName(); - isDelegateInterface = painlessMethod.javaMethod.getDeclaringClass().isInterface(); - isDelegateAugmented = painlessMethod.javaMethod.getDeclaringClass() != painlessMethod.targetClass; + delegateClassName = painlessMethod.javaMethod().getDeclaringClass().getName(); + isDelegateInterface = painlessMethod.javaMethod().getDeclaringClass().isInterface(); + isDelegateAugmented = painlessMethod.javaMethod().getDeclaringClass() != painlessMethod.targetClass(); - if (Modifier.isStatic(painlessMethod.javaMethod.getModifiers())) { + if (Modifier.isStatic(painlessMethod.javaMethod().getModifiers())) { delegateInvokeType = H_INVOKESTATIC; } else if (isDelegateInterface) { delegateInvokeType = H_INVOKEINTERFACE; @@ -237,43 +237,43 @@ public class FunctionRef { delegateInvokeType = H_INVOKEVIRTUAL; } - delegateMethodName = painlessMethod.javaMethod.getName(); - delegateMethodType = painlessMethod.methodType; + delegateMethodName = painlessMethod.javaMethod().getName(); + delegateMethodType = painlessMethod.methodType(); // interfaces that override a method from Object receive the method handle for // Object rather than for the interface; we change the first parameter to match // the interface type so the constant interface method reference is correctly // written to the constant pool if (delegateInvokeType != H_INVOKESTATIC - && painlessMethod.javaMethod.getDeclaringClass() != painlessMethod.methodType.parameterType(0)) { - if (painlessMethod.methodType.parameterType(0) != Object.class) { + && painlessMethod.javaMethod().getDeclaringClass() != painlessMethod.methodType().parameterType(0)) { + if (painlessMethod.methodType().parameterType(0) != Object.class) { throw new IllegalStateException("internal error"); } - delegateMethodType = delegateMethodType.changeParameterType(0, painlessMethod.javaMethod.getDeclaringClass()); + delegateMethodType = delegateMethodType.changeParameterType(0, painlessMethod.javaMethod().getDeclaringClass()); } delegateInjections = PainlessLookupUtility.buildInjections(painlessMethod, constants); - delegateMethodReturnType = painlessMethod.returnType; + delegateMethodReturnType = painlessMethod.returnType(); - if (delegateMethodType.parameterList().size() > painlessMethod.typeParameters.size()) { - delegateMethodParameters = new ArrayList<>(painlessMethod.typeParameters); + if (delegateMethodType.parameterList().size() > painlessMethod.typeParameters().size()) { + delegateMethodParameters = new ArrayList<>(painlessMethod.typeParameters()); delegateMethodParameters.add(0, delegateMethodType.parameterType(0)); } else { - delegateMethodParameters = painlessMethod.typeParameters; + delegateMethodParameters = painlessMethod.typeParameters(); } } if (location != null) { for (int typeParameter = 0; typeParameter < interfaceTypeParametersSize; ++typeParameter) { - Class from = interfaceMethod.typeParameters.get(typeParameter); + Class from = interfaceMethod.typeParameters().get(typeParameter); Class to = delegateMethodParameters.get(numberOfCaptures + typeParameter); AnalyzerCaster.getLegalCast(location, from, to, false, true); } - if (interfaceMethod.returnType != void.class) { - AnalyzerCaster.getLegalCast(location, delegateMethodReturnType, interfaceMethod.returnType, false, true); + if (interfaceMethod.returnType() != void.class) { + AnalyzerCaster.getLegalCast(location, delegateMethodReturnType, interfaceMethod.returnType(), false, true); } } diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/MethodWriter.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/MethodWriter.java index 58d9444a3e94..878ff0e78b61 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/MethodWriter.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/MethodWriter.java @@ -440,26 +440,26 @@ public final class MethodWriter extends GeneratorAdapter { } public void invokeMethodCall(PainlessMethod painlessMethod) { - Type type = Type.getType(painlessMethod.javaMethod.getDeclaringClass()); - Method method = Method.getMethod(painlessMethod.javaMethod); + Type type = Type.getType(painlessMethod.javaMethod().getDeclaringClass()); + Method method = Method.getMethod(painlessMethod.javaMethod()); - if (Modifier.isStatic(painlessMethod.javaMethod.getModifiers())) { + if (Modifier.isStatic(painlessMethod.javaMethod().getModifiers())) { // invokeStatic assumes that the owner class is not an interface, so this is a // special case for interfaces where the interface method boolean needs to be set to // true to reference the appropriate class constant when calling a static interface // method since java 8 did not check, but java 9 and 10 do - if (painlessMethod.javaMethod.getDeclaringClass().isInterface()) { + if (painlessMethod.javaMethod().getDeclaringClass().isInterface()) { visitMethodInsn( Opcodes.INVOKESTATIC, type.getInternalName(), - painlessMethod.javaMethod.getName(), + painlessMethod.javaMethod().getName(), method.getDescriptor(), true ); } else { invokeStatic(type, method); } - } else if (painlessMethod.javaMethod.getDeclaringClass().isInterface()) { + } else if (painlessMethod.javaMethod().getDeclaringClass().isInterface()) { invokeInterface(type, method); } else { invokeVirtual(type, method); diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextClassBindingInfo.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextClassBindingInfo.java index 2e3a56d2af98..4f7741b29cca 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextClassBindingInfo.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextClassBindingInfo.java @@ -56,11 +56,11 @@ public class PainlessContextClassBindingInfo implements Writeable, ToXContentObj public PainlessContextClassBindingInfo(PainlessClassBinding painlessClassBinding) { this( - painlessClassBinding.javaMethod.getDeclaringClass().getName(), - painlessClassBinding.javaMethod.getName(), - painlessClassBinding.returnType.getName(), - painlessClassBinding.javaConstructor.getParameterCount(), - painlessClassBinding.typeParameters.stream().map(Class::getName).collect(Collectors.toList()) + painlessClassBinding.javaMethod().getDeclaringClass().getName(), + painlessClassBinding.javaMethod().getName(), + painlessClassBinding.returnType().getName(), + painlessClassBinding.javaConstructor().getParameterCount(), + painlessClassBinding.typeParameters().stream().map(Class::getName).collect(Collectors.toList()) ); } diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextConstructorInfo.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextConstructorInfo.java index 53fe0722a1f7..e8265c4efb6e 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextConstructorInfo.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextConstructorInfo.java @@ -47,8 +47,11 @@ public class PainlessContextConstructorInfo implements Writeable, ToXContentObje public PainlessContextConstructorInfo(PainlessConstructor painlessConstructor) { this( - painlessConstructor.javaConstructor.getDeclaringClass().getName(), - painlessConstructor.typeParameters.stream().map(c -> PainlessContextTypeInfo.getType(c.getName())).collect(Collectors.toList()) + painlessConstructor.javaConstructor().getDeclaringClass().getName(), + painlessConstructor.typeParameters() + .stream() + .map(c -> PainlessContextTypeInfo.getType(c.getName())) + .collect(Collectors.toList()) ); } diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextFieldInfo.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextFieldInfo.java index d43f3608949c..ea0866643717 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextFieldInfo.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextFieldInfo.java @@ -45,9 +45,9 @@ public class PainlessContextFieldInfo implements Writeable, ToXContentObject { public PainlessContextFieldInfo(PainlessField painlessField) { this( - painlessField.javaField.getDeclaringClass().getName(), - painlessField.javaField.getName(), - PainlessContextTypeInfo.getType(painlessField.typeParameter.getName()) + painlessField.javaField().getDeclaringClass().getName(), + painlessField.javaField().getName(), + PainlessContextTypeInfo.getType(painlessField.typeParameter().getName()) ); } diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextInstanceBindingInfo.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextInstanceBindingInfo.java index af5c98904149..d668ce5ab68f 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextInstanceBindingInfo.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextInstanceBindingInfo.java @@ -53,10 +53,10 @@ public class PainlessContextInstanceBindingInfo implements Writeable, ToXContent public PainlessContextInstanceBindingInfo(PainlessInstanceBinding painlessInstanceBinding) { this( - painlessInstanceBinding.javaMethod.getDeclaringClass().getName(), - painlessInstanceBinding.javaMethod.getName(), - painlessInstanceBinding.returnType.getName(), - painlessInstanceBinding.typeParameters.stream().map(Class::getName).collect(Collectors.toList()) + painlessInstanceBinding.javaMethod().getDeclaringClass().getName(), + painlessInstanceBinding.javaMethod().getName(), + painlessInstanceBinding.returnType().getName(), + painlessInstanceBinding.typeParameters().stream().map(Class::getName).collect(Collectors.toList()) ); } diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextMethodInfo.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextMethodInfo.java index 579cd8497478..71e49c59bf2a 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextMethodInfo.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextMethodInfo.java @@ -53,10 +53,10 @@ public class PainlessContextMethodInfo implements Writeable, ToXContentObject { public PainlessContextMethodInfo(PainlessMethod painlessMethod) { this( - painlessMethod.javaMethod.getDeclaringClass().getName(), - painlessMethod.javaMethod.getName(), - PainlessContextTypeInfo.getType(painlessMethod.returnType.getName()), - painlessMethod.typeParameters.stream().map(c -> PainlessContextTypeInfo.getType(c.getName())).collect(Collectors.toList()) + painlessMethod.javaMethod().getDeclaringClass().getName(), + painlessMethod.javaMethod().getName(), + PainlessContextTypeInfo.getType(painlessMethod.returnType().getName()), + painlessMethod.typeParameters().stream().map(c -> PainlessContextTypeInfo.getType(c.getName())).collect(Collectors.toList()) ); } diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/lookup/PainlessClassBinding.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/lookup/PainlessClassBinding.java index 185b8f573d2b..d63d4d2db424 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/lookup/PainlessClassBinding.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/lookup/PainlessClassBinding.java @@ -14,29 +14,13 @@ import java.util.List; import java.util.Map; import java.util.Objects; -public class PainlessClassBinding { - - public final Constructor javaConstructor; - public final Method javaMethod; - - public final Class returnType; - public final List> typeParameters; - public final Map, Object> annotations; - - PainlessClassBinding( - Constructor javaConstructor, - Method javaMethod, - Class returnType, - List> typeParameters, - Map, Object> annotations - ) { - this.javaConstructor = javaConstructor; - this.javaMethod = javaMethod; - - this.returnType = returnType; - this.typeParameters = typeParameters; - this.annotations = annotations; - } +public record PainlessClassBinding( + Constructor javaConstructor, + Method javaMethod, + Class returnType, + List> typeParameters, + Map, Object> annotations +) { @Override public boolean equals(Object object) { @@ -49,7 +33,6 @@ public class PainlessClassBinding { } PainlessClassBinding that = (PainlessClassBinding) object; - return Objects.equals(javaConstructor, that.javaConstructor) && Objects.equals(javaMethod, that.javaMethod) && Objects.equals(returnType, that.returnType) diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/lookup/PainlessConstructor.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/lookup/PainlessConstructor.java index 2e272d9c124a..17ff4076d784 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/lookup/PainlessConstructor.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/lookup/PainlessConstructor.java @@ -15,27 +15,13 @@ import java.util.List; import java.util.Map; import java.util.Objects; -public class PainlessConstructor { - - public final Constructor javaConstructor; - public final List> typeParameters; - public final MethodHandle methodHandle; - public final MethodType methodType; - public final Map, Object> annotations; - - PainlessConstructor( - Constructor javaConstructor, - List> typeParameters, - MethodHandle methodHandle, - MethodType methodType, - Map, Object> annotations - ) { - this.javaConstructor = javaConstructor; - this.typeParameters = typeParameters; - this.methodHandle = methodHandle; - this.methodType = methodType; - this.annotations = annotations; - } +public record PainlessConstructor( + Constructor javaConstructor, + List> typeParameters, + MethodHandle methodHandle, + MethodType methodType, + Map, Object> annotations +) { @Override public boolean equals(Object object) { @@ -48,7 +34,6 @@ public class PainlessConstructor { } PainlessConstructor that = (PainlessConstructor) object; - return Objects.equals(javaConstructor, that.javaConstructor) && Objects.equals(typeParameters, that.typeParameters) && Objects.equals(methodType, that.methodType) diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/lookup/PainlessField.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/lookup/PainlessField.java index 248f8fdd4ac0..49407fed32d4 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/lookup/PainlessField.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/lookup/PainlessField.java @@ -13,30 +13,13 @@ import java.lang.reflect.Field; import java.util.Map; import java.util.Objects; -public final class PainlessField { - - public final Field javaField; - public final Class typeParameter; - public final Map, Object> annotations; - - public final MethodHandle getterMethodHandle; - public final MethodHandle setterMethodHandle; - - PainlessField( - Field javaField, - Class typeParameter, - Map, Object> annotations, - MethodHandle getterMethodHandle, - MethodHandle setterMethodHandle - ) { - - this.javaField = javaField; - this.typeParameter = typeParameter; - this.annotations = annotations; - - this.getterMethodHandle = getterMethodHandle; - this.setterMethodHandle = setterMethodHandle; - } +public record PainlessField( + Field javaField, + Class typeParameter, + Map, Object> annotations, + MethodHandle getterMethodHandle, + MethodHandle setterMethodHandle +) { @Override public boolean equals(Object object) { @@ -49,7 +32,6 @@ public final class PainlessField { } PainlessField that = (PainlessField) object; - return Objects.equals(javaField, that.javaField) && Objects.equals(typeParameter, that.typeParameter) && Objects.equals(annotations, that.annotations); diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/lookup/PainlessInstanceBinding.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/lookup/PainlessInstanceBinding.java index da1305ebb354..d0343b0812dd 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/lookup/PainlessInstanceBinding.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/lookup/PainlessInstanceBinding.java @@ -11,53 +11,13 @@ package org.elasticsearch.painless.lookup; import java.lang.reflect.Method; import java.util.List; import java.util.Map; -import java.util.Objects; -public class PainlessInstanceBinding { +public record PainlessInstanceBinding( + Object targetInstance, + Method javaMethod, + Class returnType, + List> typeParameters, + Map, Object> annotations +) { - public final Object targetInstance; - public final Method javaMethod; - - public final Class returnType; - public final List> typeParameters; - public final Map, Object> annotations; - - PainlessInstanceBinding( - Object targetInstance, - Method javaMethod, - Class returnType, - List> typeParameters, - Map, Object> annotations - ) { - this.targetInstance = targetInstance; - this.javaMethod = javaMethod; - - this.returnType = returnType; - this.typeParameters = typeParameters; - this.annotations = annotations; - } - - @Override - public boolean equals(Object object) { - if (this == object) { - return true; - } - - if (object == null || getClass() != object.getClass()) { - return false; - } - - PainlessInstanceBinding that = (PainlessInstanceBinding) object; - - return targetInstance == that.targetInstance - && Objects.equals(javaMethod, that.javaMethod) - && Objects.equals(returnType, that.returnType) - && Objects.equals(typeParameters, that.typeParameters) - && Objects.equals(annotations, that.annotations); - } - - @Override - public int hashCode() { - return Objects.hash(targetInstance, javaMethod, returnType, typeParameters); - } } diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/lookup/PainlessLookupBuilder.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/lookup/PainlessLookupBuilder.java index 985b0af36d94..0628978ab1e2 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/lookup/PainlessLookupBuilder.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/lookup/PainlessLookupBuilder.java @@ -523,7 +523,7 @@ public final class PainlessLookupBuilder { + "[[" + targetCanonicalClassName + "], " - + typesToCanonicalTypeNames(existingPainlessConstructor.typeParameters) + + typesToCanonicalTypeNames(existingPainlessConstructor.typeParameters()) + "]" ); } @@ -767,7 +767,7 @@ public final class PainlessLookupBuilder { // injections alter the type parameters required for the user to call this method, since some are injected by compiler if (annotations.containsKey(InjectConstantAnnotation.class)) { - int numInjections = ((InjectConstantAnnotation) annotations.get(InjectConstantAnnotation.class)).injects.size(); + int numInjections = ((InjectConstantAnnotation) annotations.get(InjectConstantAnnotation.class)).injects().size(); if (numInjections > 0) { typeParameters.subList(0, numInjections).clear(); @@ -880,9 +880,9 @@ public final class PainlessLookupBuilder { + methodName + "], " + "[" - + typeToCanonicalTypeName(existingPainlessMethod.returnType) + + typeToCanonicalTypeName(existingPainlessMethod.returnType()) + "], " - + typesToCanonicalTypeNames(existingPainlessMethod.typeParameters) + + typesToCanonicalTypeNames(existingPainlessMethod.typeParameters()) + "]" ); } @@ -920,7 +920,7 @@ public final class PainlessLookupBuilder { } String augmentedCanonicalClassName = annotations.containsKey(AugmentedAnnotation.class) - ? ((AugmentedAnnotation) annotations.get(AugmentedAnnotation.class)).getAugmentedCanonicalClassName() + ? ((AugmentedAnnotation) annotations.get(AugmentedAnnotation.class)).augmentedCanonicalClassName() : null; Class augmentedClass = null; @@ -1119,9 +1119,9 @@ public final class PainlessLookupBuilder { + "[[" + targetCanonicalClassName + "], [" - + existingPainlessField.javaField.getName() + + existingPainlessField.javaField().getName() + "], " - + typeToCanonicalTypeName(existingPainlessField.typeParameter) + + typeToCanonicalTypeName(existingPainlessField.typeParameter()) + "] " + "with the same name and different type parameters" ); @@ -1162,9 +1162,9 @@ public final class PainlessLookupBuilder { + "[[" + targetCanonicalClassName + "], [" - + existingPainlessField.javaField.getName() + + existingPainlessField.javaField().getName() + "], " - + typeToCanonicalTypeName(existingPainlessField.typeParameter) + + typeToCanonicalTypeName(existingPainlessField.typeParameter()) + "] " + "with the same name and different type parameters" ); @@ -1433,9 +1433,9 @@ public final class PainlessLookupBuilder { + methodName + "], " + "[" - + typeToCanonicalTypeName(existingImportedPainlessMethod.returnType) + + typeToCanonicalTypeName(existingImportedPainlessMethod.returnType()) + "], " - + typesToCanonicalTypeNames(existingImportedPainlessMethod.typeParameters) + + typesToCanonicalTypeNames(existingImportedPainlessMethod.typeParameters()) + "]" ); } @@ -1766,9 +1766,9 @@ public final class PainlessLookupBuilder { + methodName + "], " + "[" - + typeToCanonicalTypeName(existingPainlessClassBinding.returnType) + + typeToCanonicalTypeName(existingPainlessClassBinding.returnType()) + "], " - + typesToCanonicalTypeNames(existingPainlessClassBinding.typeParameters) + + typesToCanonicalTypeNames(existingPainlessClassBinding.typeParameters()) + "]" ); } @@ -2001,11 +2001,11 @@ public final class PainlessLookupBuilder { + methodName + "], " + "[" - + typeToCanonicalTypeName(existingPainlessInstanceBinding.returnType) + + typeToCanonicalTypeName(existingPainlessInstanceBinding.returnType()) + "], " - + typesToCanonicalTypeNames(existingPainlessInstanceBinding.typeParameters) + + typesToCanonicalTypeNames(existingPainlessInstanceBinding.typeParameters()) + "], " - + existingPainlessInstanceBinding.annotations + + existingPainlessInstanceBinding.annotations() ); } } @@ -2186,7 +2186,7 @@ public final class PainlessLookupBuilder { painlessClassBuilder.runtimeMethods.putAll(painlessClassBuilder.methods); for (PainlessMethod painlessMethod : painlessClassBuilder.runtimeMethods.values()) { - for (Class typeParameter : painlessMethod.typeParameters) { + for (Class typeParameter : painlessMethod.typeParameters()) { if (typeParameter == Byte.class || typeParameter == Short.class || typeParameter == Character.class @@ -2202,12 +2202,12 @@ public final class PainlessLookupBuilder { } private void generateBridgeMethod(PainlessClassBuilder painlessClassBuilder, PainlessMethod painlessMethod) { - String painlessMethodKey = buildPainlessMethodKey(painlessMethod.javaMethod.getName(), painlessMethod.typeParameters.size()); + String painlessMethodKey = buildPainlessMethodKey(painlessMethod.javaMethod().getName(), painlessMethod.typeParameters().size()); PainlessMethod bridgePainlessMethod = painlessBridgeCache.get(painlessMethod); if (bridgePainlessMethod == null) { - Method javaMethod = painlessMethod.javaMethod; - boolean isStatic = Modifier.isStatic(painlessMethod.javaMethod.getModifiers()); + Method javaMethod = painlessMethod.javaMethod(); + boolean isStatic = Modifier.isStatic(painlessMethod.javaMethod().getModifiers()); int bridgeClassFrames = ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS; int bridgeClassAccess = Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER | Opcodes.ACC_FINAL; @@ -2267,10 +2267,10 @@ public final class PainlessLookupBuilder { } } - MethodType bridgeMethodType = MethodType.methodType(painlessMethod.returnType, bridgeTypeParameters); + MethodType bridgeMethodType = MethodType.methodType(painlessMethod.returnType(), bridgeTypeParameters); MethodWriter bridgeMethodWriter = new MethodWriter( Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, - new org.objectweb.asm.commons.Method(painlessMethod.javaMethod.getName(), bridgeMethodType.toMethodDescriptorString()), + new org.objectweb.asm.commons.Method(painlessMethod.javaMethod().getName(), bridgeMethodType.toMethodDescriptorString()), bridgeClassWriter, null, null @@ -2310,14 +2310,14 @@ public final class PainlessLookupBuilder { Class bridgeClass = bridgeLoader.defineBridge(bridgeClassName.replace('/', '.'), bridgeClassWriter.toByteArray()); Method bridgeMethod = bridgeClass.getMethod( - painlessMethod.javaMethod.getName(), + painlessMethod.javaMethod().getName(), bridgeTypeParameters.toArray(new Class[0]) ); MethodHandle bridgeHandle = MethodHandles.publicLookup().in(bridgeClass).unreflect(bridgeClass.getMethods()[0]); bridgePainlessMethod = new PainlessMethod( bridgeMethod, bridgeClass, - painlessMethod.returnType, + painlessMethod.returnType(), bridgeTypeParameters, bridgeHandle, bridgeMethodType, @@ -2347,8 +2347,8 @@ public final class PainlessLookupBuilder { String methodKey = painlessMethodEntry.getKey(); PainlessMethod painlessMethod = painlessMethodEntry.getValue(); PainlessMethod bridgePainlessMethod = painlessClassBuilder.runtimeMethods.get(methodKey); - String methodName = painlessMethod.javaMethod.getName(); - int typeParametersSize = painlessMethod.typeParameters.size(); + String methodName = painlessMethod.javaMethod().getName(); + int typeParametersSize = painlessMethod.typeParameters().size(); if (typeParametersSize == 0 && methodName.startsWith("get") @@ -2356,7 +2356,7 @@ public final class PainlessLookupBuilder { && Character.isUpperCase(methodName.charAt(3))) { painlessClassBuilder.getterMethodHandles.putIfAbsent( Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4), - bridgePainlessMethod.methodHandle + bridgePainlessMethod.methodHandle() ); } else if (typeParametersSize == 0 && methodName.startsWith("is") @@ -2364,7 +2364,7 @@ public final class PainlessLookupBuilder { && Character.isUpperCase(methodName.charAt(2))) { painlessClassBuilder.getterMethodHandles.putIfAbsent( Character.toLowerCase(methodName.charAt(2)) + methodName.substring(3), - bridgePainlessMethod.methodHandle + bridgePainlessMethod.methodHandle() ); } else if (typeParametersSize == 1 && methodName.startsWith("set") @@ -2372,14 +2372,14 @@ public final class PainlessLookupBuilder { && Character.isUpperCase(methodName.charAt(3))) { painlessClassBuilder.setterMethodHandles.putIfAbsent( Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4), - bridgePainlessMethod.methodHandle + bridgePainlessMethod.methodHandle() ); } } for (PainlessField painlessField : painlessClassBuilder.fields.values()) { - painlessClassBuilder.getterMethodHandles.put(painlessField.javaField.getName().intern(), painlessField.getterMethodHandle); - painlessClassBuilder.setterMethodHandles.put(painlessField.javaField.getName().intern(), painlessField.setterMethodHandle); + painlessClassBuilder.getterMethodHandles.put(painlessField.javaField().getName().intern(), painlessField.getterMethodHandle()); + painlessClassBuilder.setterMethodHandles.put(painlessField.javaField().getName().intern(), painlessField.setterMethodHandle()); } } } diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/lookup/PainlessLookupUtility.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/lookup/PainlessLookupUtility.java index 391df4f227f3..7c12b89a81e2 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/lookup/PainlessLookupUtility.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/lookup/PainlessLookupUtility.java @@ -356,11 +356,11 @@ public final class PainlessLookupUtility { * derived from an {@link org.elasticsearch.painless.spi.annotation.InjectConstantAnnotation}. */ public static Object[] buildInjections(PainlessMethod painlessMethod, Map constants) { - if (painlessMethod.annotations.containsKey(InjectConstantAnnotation.class) == false) { + if (painlessMethod.annotations().containsKey(InjectConstantAnnotation.class) == false) { return new Object[0]; } - List names = ((InjectConstantAnnotation) painlessMethod.annotations.get(InjectConstantAnnotation.class)).injects; + List names = ((InjectConstantAnnotation) painlessMethod.annotations().get(InjectConstantAnnotation.class)).injects(); Object[] injections = new Object[names.size()]; for (int i = 0; i < names.size(); i++) { @@ -373,7 +373,7 @@ public final class PainlessLookupUtility { + name + "] not found for injection into method " + "[" - + buildPainlessMethodKey(painlessMethod.javaMethod.getName(), painlessMethod.typeParameters.size()) + + buildPainlessMethodKey(painlessMethod.javaMethod().getName(), painlessMethod.typeParameters().size()) + "]" ); } diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/lookup/PainlessMethod.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/lookup/PainlessMethod.java index d5710284d5e4..a6fe3deaefb3 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/lookup/PainlessMethod.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/lookup/PainlessMethod.java @@ -15,15 +15,15 @@ import java.util.List; import java.util.Map; import java.util.Objects; -public class PainlessMethod { - - public final Method javaMethod; - public final Class targetClass; - public final Class returnType; - public final List> typeParameters; - public final MethodHandle methodHandle; - public final MethodType methodType; - public final Map, Object> annotations; +public record PainlessMethod( + Method javaMethod, + Class targetClass, + Class returnType, + List> typeParameters, + MethodHandle methodHandle, + MethodType methodType, + Map, Object> annotations +) { public PainlessMethod( Method javaMethod, @@ -34,7 +34,6 @@ public class PainlessMethod { MethodType methodType, Map, Object> annotations ) { - this.javaMethod = javaMethod; this.targetClass = targetClass; this.returnType = returnType; @@ -55,7 +54,6 @@ public class PainlessMethod { } PainlessMethod that = (PainlessMethod) object; - return Objects.equals(javaMethod, that.javaMethod) && Objects.equals(targetClass, that.targetClass) && Objects.equals(returnType, that.returnType) diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/phase/DefaultConstantFoldingOptimizationPhase.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/phase/DefaultConstantFoldingOptimizationPhase.java index 33ec5e7e5e0f..27106d837f8a 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/phase/DefaultConstantFoldingOptimizationPhase.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/phase/DefaultConstantFoldingOptimizationPhase.java @@ -1085,13 +1085,13 @@ public class DefaultConstantFoldingOptimizationPhase extends IRTreeBaseVisitor irInvokeCallMemberNode.getArgumentNodes().set(j, e)); } PainlessMethod method = irInvokeCallMemberNode.getDecorationValue(IRDMethod.class); - if (method != null && method.annotations.containsKey(CompileTimeOnlyAnnotation.class)) { - replaceCallWithConstant(irInvokeCallMemberNode, scope, method.javaMethod, null); + if (method != null && method.annotations().containsKey(CompileTimeOnlyAnnotation.class)) { + replaceCallWithConstant(irInvokeCallMemberNode, scope, method.javaMethod(), null); return; } PainlessInstanceBinding instanceBinding = irInvokeCallMemberNode.getDecorationValue(IRDInstanceBinding.class); - if (instanceBinding != null && instanceBinding.annotations.containsKey(CompileTimeOnlyAnnotation.class)) { - replaceCallWithConstant(irInvokeCallMemberNode, scope, instanceBinding.javaMethod, instanceBinding.targetInstance); + if (instanceBinding != null && instanceBinding.annotations().containsKey(CompileTimeOnlyAnnotation.class)) { + replaceCallWithConstant(irInvokeCallMemberNode, scope, instanceBinding.javaMethod(), instanceBinding.targetInstance()); return; } } diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/phase/DefaultIRTreeToASMBytesPhase.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/phase/DefaultIRTreeToASMBytesPhase.java index f887f7c7e602..d7ece3428149 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/phase/DefaultIRTreeToASMBytesPhase.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/phase/DefaultIRTreeToASMBytesPhase.java @@ -1179,8 +1179,8 @@ public class DefaultIRTreeToASMBytesPhase implements IRTreeVisitor { methodWriter.newInstance(MethodWriter.getType(irListInitializationNode.getDecorationValue(IRDExpressionType.class))); methodWriter.dup(); methodWriter.invokeConstructor( - Type.getType(painlessConstructor.javaConstructor.getDeclaringClass()), - Method.getMethod(painlessConstructor.javaConstructor) + Type.getType(painlessConstructor.javaConstructor().getDeclaringClass()), + Method.getMethod(painlessConstructor.javaConstructor()) ); for (ExpressionNode irArgumentNode : irListInitializationNode.getArgumentNodes()) { @@ -1200,8 +1200,8 @@ public class DefaultIRTreeToASMBytesPhase implements IRTreeVisitor { methodWriter.newInstance(MethodWriter.getType(irMapInitializationNode.getDecorationValue(IRDExpressionType.class))); methodWriter.dup(); methodWriter.invokeConstructor( - Type.getType(painlessConstructor.javaConstructor.getDeclaringClass()), - Method.getMethod(painlessConstructor.javaConstructor) + Type.getType(painlessConstructor.javaConstructor().getDeclaringClass()), + Method.getMethod(painlessConstructor.javaConstructor()) ); for (int index = 0; index < irMapInitializationNode.getArgumentsSize(); ++index) { @@ -1262,8 +1262,8 @@ public class DefaultIRTreeToASMBytesPhase implements IRTreeVisitor { PainlessConstructor painlessConstructor = irNewObjectNode.getDecorationValue(IRDConstructor.class); methodWriter.invokeConstructor( - Type.getType(painlessConstructor.javaConstructor.getDeclaringClass()), - Method.getMethod(painlessConstructor.javaConstructor) + Type.getType(painlessConstructor.javaConstructor().getDeclaringClass()), + Method.getMethod(painlessConstructor.javaConstructor()) ); } @@ -1428,10 +1428,10 @@ public class DefaultIRTreeToASMBytesPhase implements IRTreeVisitor { methodWriter.writeDebugInfo(irLoadDotNode.getLocation()); PainlessField painlessField = irLoadDotNode.getDecorationValue(IRDField.class); - boolean isStatic = Modifier.isStatic(painlessField.javaField.getModifiers()); - Type asmOwnerType = Type.getType(painlessField.javaField.getDeclaringClass()); - String fieldName = painlessField.javaField.getName(); - Type asmFieldType = MethodWriter.getType(painlessField.typeParameter); + boolean isStatic = Modifier.isStatic(painlessField.javaField().getModifiers()); + Type asmOwnerType = Type.getType(painlessField.javaField().getDeclaringClass()); + String fieldName = painlessField.javaField().getName(); + Type asmFieldType = MethodWriter.getType(painlessField.typeParameter()); if (isStatic) { methodWriter.getStatic(asmOwnerType, fieldName, asmFieldType); @@ -1448,8 +1448,8 @@ public class DefaultIRTreeToASMBytesPhase implements IRTreeVisitor { PainlessMethod getterPainlessMethod = irDotSubShortcutNode.getDecorationValue(IRDMethod.class); methodWriter.invokeMethodCall(getterPainlessMethod); - if (getterPainlessMethod.returnType.equals(getterPainlessMethod.javaMethod.getReturnType()) == false) { - methodWriter.checkCast(MethodWriter.getType(getterPainlessMethod.returnType)); + if (getterPainlessMethod.returnType().equals(getterPainlessMethod.javaMethod().getReturnType()) == false) { + methodWriter.checkCast(MethodWriter.getType(getterPainlessMethod.returnType())); } } @@ -1461,8 +1461,8 @@ public class DefaultIRTreeToASMBytesPhase implements IRTreeVisitor { PainlessMethod getterPainlessMethod = irLoadListShortcutNode.getDecorationValue(IRDMethod.class); methodWriter.invokeMethodCall(getterPainlessMethod); - if (getterPainlessMethod.returnType == getterPainlessMethod.javaMethod.getReturnType()) { - methodWriter.checkCast(MethodWriter.getType(getterPainlessMethod.returnType)); + if (getterPainlessMethod.returnType() == getterPainlessMethod.javaMethod().getReturnType()) { + methodWriter.checkCast(MethodWriter.getType(getterPainlessMethod.returnType())); } } @@ -1474,8 +1474,8 @@ public class DefaultIRTreeToASMBytesPhase implements IRTreeVisitor { PainlessMethod getterPainlessMethod = irLoadMapShortcutNode.getDecorationValue(IRDMethod.class); methodWriter.invokeMethodCall(getterPainlessMethod); - if (getterPainlessMethod.returnType != getterPainlessMethod.javaMethod.getReturnType()) { - methodWriter.checkCast(MethodWriter.getType(getterPainlessMethod.returnType)); + if (getterPainlessMethod.returnType() != getterPainlessMethod.javaMethod().getReturnType()) { + methodWriter.checkCast(MethodWriter.getType(getterPainlessMethod.returnType())); } } @@ -1549,10 +1549,10 @@ public class DefaultIRTreeToASMBytesPhase implements IRTreeVisitor { methodWriter.writeDebugInfo(irStoreDotNode.getLocation()); PainlessField painlessField = irStoreDotNode.getDecorationValue(IRDField.class); - boolean isStatic = Modifier.isStatic(painlessField.javaField.getModifiers()); - Type asmOwnerType = Type.getType(painlessField.javaField.getDeclaringClass()); - String fieldName = painlessField.javaField.getName(); - Type asmFieldType = MethodWriter.getType(painlessField.typeParameter); + boolean isStatic = Modifier.isStatic(painlessField.javaField().getModifiers()); + Type asmOwnerType = Type.getType(painlessField.javaField().getDeclaringClass()); + String fieldName = painlessField.javaField().getName(); + Type asmFieldType = MethodWriter.getType(painlessField.typeParameter()); if (isStatic) { methodWriter.putStatic(asmOwnerType, fieldName, asmFieldType); @@ -1569,7 +1569,7 @@ public class DefaultIRTreeToASMBytesPhase implements IRTreeVisitor { methodWriter.writeDebugInfo(irDotSubShortcutNode.getLocation()); methodWriter.invokeMethodCall(irDotSubShortcutNode.getDecorationValue(IRDMethod.class)); - methodWriter.writePop(MethodWriter.getType(irDotSubShortcutNode.getDecorationValue(IRDMethod.class).returnType).getSize()); + methodWriter.writePop(MethodWriter.getType(irDotSubShortcutNode.getDecorationValue(IRDMethod.class).returnType()).getSize()); } @Override @@ -1580,7 +1580,7 @@ public class DefaultIRTreeToASMBytesPhase implements IRTreeVisitor { methodWriter.writeDebugInfo(irStoreListShortcutNode.getLocation()); methodWriter.invokeMethodCall(irStoreListShortcutNode.getDecorationValue(IRDMethod.class)); - methodWriter.writePop(MethodWriter.getType(irStoreListShortcutNode.getDecorationValue(IRDMethod.class).returnType).getSize()); + methodWriter.writePop(MethodWriter.getType(irStoreListShortcutNode.getDecorationValue(IRDMethod.class).returnType()).getSize()); } @Override @@ -1591,7 +1591,7 @@ public class DefaultIRTreeToASMBytesPhase implements IRTreeVisitor { methodWriter.writeDebugInfo(irStoreMapShortcutNode.getLocation()); methodWriter.invokeMethodCall(irStoreMapShortcutNode.getDecorationValue(IRDMethod.class)); - methodWriter.writePop(MethodWriter.getType(irStoreMapShortcutNode.getDecorationValue(IRDMethod.class).returnType).getSize()); + methodWriter.writePop(MethodWriter.getType(irStoreMapShortcutNode.getDecorationValue(IRDMethod.class).returnType()).getSize()); } @Override @@ -1769,8 +1769,8 @@ public class DefaultIRTreeToASMBytesPhase implements IRTreeVisitor { } Method asmMethod = new Method( - thisMethod.javaMethod.getName(), - thisMethod.methodType.dropParameterTypes(0, 1).toMethodDescriptorString() + thisMethod.javaMethod().getName(), + thisMethod.methodType().dropParameterTypes(0, 1).toMethodDescriptorString() ); methodWriter.invokeVirtual(CLASS_TYPE, asmMethod); } else if (importedMethod != null) { @@ -1778,13 +1778,13 @@ public class DefaultIRTreeToASMBytesPhase implements IRTreeVisitor { visit(irArgumentNode, writeScope); } - Type asmType = Type.getType(importedMethod.targetClass); - Method asmMethod = new Method(importedMethod.javaMethod.getName(), importedMethod.methodType.toMethodDescriptorString()); + Type asmType = Type.getType(importedMethod.targetClass()); + Method asmMethod = new Method(importedMethod.javaMethod().getName(), importedMethod.methodType().toMethodDescriptorString()); methodWriter.invokeStatic(asmType, asmMethod); } else if (classBinding != null) { - Type type = Type.getType(classBinding.javaConstructor.getDeclaringClass()); + Type type = Type.getType(classBinding.javaConstructor().getDeclaringClass()); int classBindingOffset = irInvokeCallMemberNode.hasCondition(IRCStatic.class) ? 0 : 1; - int javaConstructorParameterCount = classBinding.javaConstructor.getParameterCount() - classBindingOffset; + int javaConstructorParameterCount = classBinding.javaConstructor().getParameterCount() - classBindingOffset; String bindingName = irInvokeCallMemberNode.getDecorationValue(IRDName.class); Label nonNull = new Label(); @@ -1804,30 +1804,30 @@ public class DefaultIRTreeToASMBytesPhase implements IRTreeVisitor { visit(irArgumentNodes.get(argument), writeScope); } - methodWriter.invokeConstructor(type, Method.getMethod(classBinding.javaConstructor)); + methodWriter.invokeConstructor(type, Method.getMethod(classBinding.javaConstructor())); methodWriter.putField(CLASS_TYPE, bindingName, type); methodWriter.mark(nonNull); methodWriter.loadThis(); methodWriter.getField(CLASS_TYPE, bindingName, type); - for (int argument = 0; argument < classBinding.javaMethod.getParameterCount(); ++argument) { + for (int argument = 0; argument < classBinding.javaMethod().getParameterCount(); ++argument) { visit(irArgumentNodes.get(argument + javaConstructorParameterCount), writeScope); } - methodWriter.invokeVirtual(type, Method.getMethod(classBinding.javaMethod)); + methodWriter.invokeVirtual(type, Method.getMethod(classBinding.javaMethod())); } else if (instanceBinding != null) { - Type type = Type.getType(instanceBinding.targetInstance.getClass()); + Type type = Type.getType(instanceBinding.targetInstance().getClass()); String bindingName = irInvokeCallMemberNode.getDecorationValue(IRDName.class); methodWriter.loadThis(); methodWriter.getStatic(CLASS_TYPE, bindingName, type); - for (int argument = 0; argument < instanceBinding.javaMethod.getParameterCount(); ++argument) { + for (int argument = 0; argument < instanceBinding.javaMethod().getParameterCount(); ++argument) { visit(irArgumentNodes.get(argument), writeScope); } - methodWriter.invokeVirtual(type, Method.getMethod(instanceBinding.javaMethod)); + methodWriter.invokeVirtual(type, Method.getMethod(instanceBinding.javaMethod())); } else { throw new IllegalStateException("invalid unbound call"); } diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/phase/DefaultSemanticAnalysisPhase.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/phase/DefaultSemanticAnalysisPhase.java index 128b06672879..6004a4b3062e 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/phase/DefaultSemanticAnalysisPhase.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/phase/DefaultSemanticAnalysisPhase.java @@ -162,8 +162,8 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor valueType = semanticScope.getDecoration(userExpressionNode, ValueType.class).getValueType(); - Class targetType = semanticScope.getDecoration(userExpressionNode, TargetType.class).getTargetType(); + Class valueType = semanticScope.getDecoration(userExpressionNode, ValueType.class).valueType(); + Class targetType = semanticScope.getDecoration(userExpressionNode, TargetType.class).targetType(); boolean isExplicitCast = semanticScope.getCondition(userExpressionNode, Explicit.class); boolean isInternalCast = semanticScope.getCondition(userExpressionNode, Internal.class); @@ -196,7 +196,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor iterableValueType = semanticScope.getDecoration(userIterableNode, ValueType.class).getValueType(); + Class iterableValueType = semanticScope.getDecoration(userIterableNode, ValueType.class).valueType(); if (iterableValueType.isArray()) { PainlessCast painlessCast = AnalyzerCaster.getLegalCast( location, iterableValueType.getComponentType(), - variable.getType(), + variable.type(), true, true ); @@ -790,7 +790,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor expressionValueType = semanticScope.getDecoration(userStatementNode, ValueType.class).getValueType(); + Class expressionValueType = semanticScope.getDecoration(userStatementNode, ValueType.class).valueType(); boolean rtn = lastSource && isVoid == false && expressionValueType != void.class; if (rtn) { @@ -980,7 +980,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor leftValueType = semanticScope.getDecoration(userLeftNode, Decorations.ValueType.class).getValueType(); + Class leftValueType = semanticScope.getDecoration(userLeftNode, Decorations.ValueType.class).valueType(); AExpression userRightNode = userAssignmentNode.getRightNode(); semanticScope.setCondition(userRightNode, Read.class); @@ -989,7 +989,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor rightValueType = semanticScope.getDecoration(userRightNode, ValueType.class).getValueType(); + Class rightValueType = semanticScope.getDecoration(userRightNode, ValueType.class).valueType(); Class compoundType; boolean isConcatenation = false; @@ -1078,7 +1078,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor rightValueType = semanticScope.getDecoration(userRightNode, ValueType.class).getValueType(); + Class rightValueType = semanticScope.getDecoration(userRightNode, ValueType.class).valueType(); if (rightValueType == void.class) { throw userAssignmentNode.createError( @@ -1144,7 +1144,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor childValueType = semanticScope.getDecoration(userChildNode, ValueType.class).getValueType(); + Class childValueType = semanticScope.getDecoration(userChildNode, ValueType.class).valueType(); unaryType = AnalyzerCaster.promoteNumeric(childValueType, operation != Operation.BWNOT); @@ -1182,7 +1182,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor leftValueType = semanticScope.getDecoration(userLeftNode, ValueType.class).getValueType(); + Class leftValueType = semanticScope.getDecoration(userLeftNode, ValueType.class).valueType(); AExpression userRightNode = userBinaryNode.getRightNode(); semanticScope.setCondition(userRightNode, Read.class); checkedVisit(userRightNode, semanticScope); - Class rightValueType = semanticScope.getDecoration(userRightNode, ValueType.class).getValueType(); + Class rightValueType = semanticScope.getDecoration(userRightNode, ValueType.class).valueType(); Class valueType; Class binaryType; @@ -1290,7 +1290,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor leftValueType = semanticScope.getDecoration(userLeftNode, ValueType.class).getValueType(); + Class leftValueType = semanticScope.getDecoration(userLeftNode, ValueType.class).valueType(); AExpression userRightNode = userCompNode.getRightNode(); semanticScope.setCondition(userRightNode, Read.class); checkedVisit(userRightNode, semanticScope); - Class rightValueType = semanticScope.getDecoration(userRightNode, ValueType.class).getValueType(); + Class rightValueType = semanticScope.getDecoration(userRightNode, ValueType.class).valueType(); Class promotedType; @@ -1546,7 +1546,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor leftValueType = semanticScope.getDecoration(userTrueNode, ValueType.class).getValueType(); + Class leftValueType = semanticScope.getDecoration(userTrueNode, ValueType.class).valueType(); AExpression userFalseNode = userConditionalNode.getFalseNode(); semanticScope.setCondition(userFalseNode, Read.class); @@ -1554,7 +1554,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor rightValueType = semanticScope.getDecoration(userFalseNode, ValueType.class).getValueType(); + Class rightValueType = semanticScope.getDecoration(userFalseNode, ValueType.class).valueType(); TargetType targetType = semanticScope.getDecoration(userConditionalNode, TargetType.class); Class valueType; @@ -1580,7 +1580,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor leftValueType = semanticScope.getDecoration(userLeftNode, ValueType.class).getValueType(); + Class leftValueType = semanticScope.getDecoration(userLeftNode, ValueType.class).valueType(); AExpression userRightNode = userElvisNode.getRightNode(); semanticScope.setCondition(userRightNode, Read.class); @@ -1625,7 +1625,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor rightValueType = semanticScope.getDecoration(userRightNode, ValueType.class).getValueType(); + Class rightValueType = semanticScope.getDecoration(userRightNode, ValueType.class).valueType(); if (userLeftNode instanceof ENull) { throw userElvisNode.createError(new IllegalArgumentException("Extraneous elvis operator. LHS is null.")); @@ -1652,7 +1652,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor[] types = new Class[constructor.typeParameters.size()]; - constructor.typeParameters.toArray(types); + Class[] types = new Class[constructor.typeParameters().size()]; + constructor.typeParameters().toArray(types); - if (constructor.typeParameters.size() != userArgumentsSize) { + if (constructor.typeParameters().size() != userArgumentsSize) { throw userNewObjNode.createError( new IllegalArgumentException( "When calling constructor on type [" + PainlessLookupUtility.typeToCanonicalTypeName(valueType) + "] " + "expected [" - + constructor.typeParameters.size() + + constructor.typeParameters().size() + "] arguments, but found [" + userArgumentsSize + "]." @@ -1930,8 +1930,8 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor(thisMethod.typeParameters); - valueType = thisMethod.returnType; + scriptScope.markNonDeterministic(thisMethod.annotations().containsKey(NonDeterministicAnnotation.class)); + typeParameters = new ArrayList<>(thisMethod.typeParameters()); + valueType = thisMethod.returnType(); } else if (importedMethod != null) { semanticScope.putDecoration(userCallLocalNode, new StandardPainlessMethod(importedMethod)); - scriptScope.markNonDeterministic(importedMethod.annotations.containsKey(NonDeterministicAnnotation.class)); - typeParameters = new ArrayList<>(importedMethod.typeParameters); - valueType = importedMethod.returnType; + scriptScope.markNonDeterministic(importedMethod.annotations().containsKey(NonDeterministicAnnotation.class)); + typeParameters = new ArrayList<>(importedMethod.typeParameters()); + valueType = importedMethod.returnType(); } else if (classBinding != null) { semanticScope.putDecoration(userCallLocalNode, new StandardPainlessClassBinding(classBinding)); semanticScope.putDecoration(userCallLocalNode, new StandardConstant(classBindingOffset)); - scriptScope.markNonDeterministic(classBinding.annotations.containsKey(NonDeterministicAnnotation.class)); - typeParameters = new ArrayList<>(classBinding.typeParameters); - valueType = classBinding.returnType; + scriptScope.markNonDeterministic(classBinding.annotations().containsKey(NonDeterministicAnnotation.class)); + typeParameters = new ArrayList<>(classBinding.typeParameters()); + valueType = classBinding.returnType(); } else if (instanceBinding != null) { semanticScope.putDecoration(userCallLocalNode, new StandardPainlessInstanceBinding(instanceBinding)); - typeParameters = new ArrayList<>(instanceBinding.typeParameters); - valueType = instanceBinding.returnType; + typeParameters = new ArrayList<>(instanceBinding.typeParameters()); + valueType = instanceBinding.returnType(); } else { throw new IllegalStateException("Illegal tree structure."); } @@ -2103,7 +2103,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor sort = targetType == null ? int.class : targetType.getTargetType(); + Class sort = targetType == null ? int.class : targetType.targetType(); int integer = Integer.parseInt(numeric, radix); if (sort == byte.class && integer >= Byte.MIN_VALUE && integer <= Byte.MAX_VALUE) { @@ -2228,13 +2228,13 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor valueType; if (targetType != null) { - if (targetType.getTargetType().isPrimitive()) { + if (targetType.targetType().isPrimitive()) { throw userNullNode.createError( new IllegalArgumentException("Cannot cast null to a primitive type [" + targetType.getTargetCanonicalTypeName() + "].") ); } - valueType = targetType.getTargetType(); + valueType = targetType.targetType(); } else { valueType = Object.class; } @@ -2360,7 +2360,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor(canonicalTypeNameParameters.size()); for (int i = 0; i < canonicalTypeNameParameters.size(); i++) { String paramType = canonicalTypeNameParameters.get(i); if (paramType == null) { - typeParameters.add(interfaceMethod.typeParameters.get(i)); + typeParameters.add(interfaceMethod.typeParameters().get(i)); } else { Class typeParameter = scriptScope.getPainlessLookup().canonicalTypeNameToType(paramType); @@ -2433,8 +2433,8 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor parameterNamesWithCaptures = new ArrayList<>(capturedVariables.size() + parameterNames.size()); for (Variable capturedVariable : capturedVariables) { - typeParametersWithCaptures.add(capturedVariable.getType()); - parameterNamesWithCaptures.add(capturedVariable.getName()); + typeParametersWithCaptures.add(capturedVariable.type()); + parameterNamesWithCaptures.add(capturedVariable.name()); } typeParametersWithCaptures.addAll(typeParameters); @@ -2451,21 +2451,21 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor valueType = variable.getType(); + Class valueType = variable.type(); semanticScope.putDecoration(userSymbolNode, new ValueType(valueType)); } else { semanticScope.putDecoration(userSymbolNode, new PartialCanonicalTypeName(symbol)); @@ -2754,13 +2754,13 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor staticType = scriptScope.getPainlessLookup().canonicalTypeNameToType(canonicalTypeName); @@ -2805,7 +2805,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor valueType = null; - if (prefixValueType != null && prefixValueType.getValueType().isArray()) { + if (prefixValueType != null && prefixValueType.valueType().isArray()) { if ("length".equals(index)) { if (write) { throw userDotNode.createError( @@ -2823,11 +2823,11 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor prefixValueType = semanticScope.getDecoration(userPrefixNode, ValueType.class).getValueType(); + Class prefixValueType = semanticScope.getDecoration(userPrefixNode, ValueType.class).valueType(); AExpression userIndexNode = userBraceNode.getIndexNode(); Class valueType; @@ -3102,8 +3103,8 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor type = prefixValueType.getValueType(); + Class type = prefixValueType.valueType(); PainlessLookup lookup = semanticScope.getScriptScope().getPainlessLookup(); - if (prefixValueType.getValueType() == def.class) { + if (prefixValueType.valueType() == def.class) { dynamic = true; } else { method = lookup.lookupPainlessMethod(type, false, methodName, userArgumentsSize); @@ -3310,7 +3313,7 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor argumentValueType = semanticScope.getDecoration(userArgumentNode, ValueType.class).getValueType(); + Class argumentValueType = semanticScope.getDecoration(userArgumentNode, ValueType.class).valueType(); if (argumentValueType == void.class) { throw userCallNode.createError( @@ -3350,25 +3353,25 @@ public class DefaultSemanticAnalysisPhase extends UserTreeBaseVisitor targetType = painlessCast.targetType; if (painlessCast.boxTargetType != null) { @@ -558,7 +558,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor iterableValueType = scriptScope.getDecoration(userEachNode.getIterableNode(), ValueType.class).getValueType(); + Class iterableValueType = scriptScope.getDecoration(userEachNode.getIterableNode(), ValueType.class).valueType(); BlockNode irBlockNode = (BlockNode) visit(userEachNode.getBlockNode(), scriptScope); ConditionNode irConditionNode; @@ -742,8 +742,8 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor compoundType = scriptScope.hasDecoration(userAssignmentNode, CompoundType.class) - ? scriptScope.getDecoration(userAssignmentNode, CompoundType.class).getCompoundType() + ? scriptScope.getDecoration(userAssignmentNode, CompoundType.class).compoundType() : null; ExpressionNode irAssignmentNode; @@ -923,7 +923,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor unaryType = scriptScope.hasDecoration(userUnaryNode, UnaryType.class) - ? scriptScope.getDecoration(userUnaryNode, UnaryType.class).getUnaryType() + ? scriptScope.getDecoration(userUnaryNode, UnaryType.class).unaryType() : null; IRNode irNode; @@ -1028,9 +1028,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor valueType = scriptScope.getDecoration(userBinaryNode, ValueType.class).getValueType(); + Class valueType = scriptScope.getDecoration(userBinaryNode, ValueType.class).valueType(); if (operation == Operation.ADD && valueType == String.class) { StringConcatenationNode stringConcatenationNode = new StringConcatenationNode(userBinaryNode.getLocation()); @@ -1062,9 +1060,9 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor binaryType = scriptScope.getDecoration(userBinaryNode, BinaryType.class).getBinaryType(); + Class binaryType = scriptScope.getDecoration(userBinaryNode, BinaryType.class).binaryType(); Class shiftType = scriptScope.hasDecoration(userBinaryNode, ShiftType.class) - ? scriptScope.getDecoration(userBinaryNode, ShiftType.class).getShiftType() + ? scriptScope.getDecoration(userBinaryNode, ShiftType.class).shiftType() : null; BinaryMathNode irBinaryMathNode = new BinaryMathNode(userBinaryNode.getLocation()); @@ -1096,7 +1094,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor valueType = scriptScope.getDecoration(userBooleanCompNode, ValueType.class).getValueType(); + Class valueType = scriptScope.getDecoration(userBooleanCompNode, ValueType.class).valueType(); BooleanNode irBooleanNode = new BooleanNode(userBooleanCompNode.getLocation()); irBooleanNode.attachDecoration(new IRDExpressionType(valueType)); @@ -1110,9 +1108,9 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor valuetype = scriptScope.getDecoration(userInstanceofNode, ValueType.class).getValueType(); - Class instanceType = scriptScope.getDecoration(userInstanceofNode, InstanceType.class).getInstanceType(); + Class valuetype = scriptScope.getDecoration(userInstanceofNode, ValueType.class).valueType(); + Class instanceType = scriptScope.getDecoration(userInstanceofNode, InstanceType.class).instanceType(); InstanceofNode irInstanceofNode = new InstanceofNode(userInstanceofNode.getLocation()); irInstanceofNode.attachDecoration(new IRDExpressionType(valuetype)); @@ -1143,7 +1141,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor valueType = scriptScope.getDecoration(userNewObjectNode, ValueType.class).getValueType(); + Class valueType = scriptScope.getDecoration(userNewObjectNode, ValueType.class).valueType(); PainlessConstructor painlessConstructor = scriptScope.getDecoration(userNewObjectNode, StandardPainlessConstructor.class) - .getStandardPainlessConstructor(); + .standardPainlessConstructor(); NewObjectNode irNewObjectNode = new NewObjectNode(userNewObjectNode.getLocation()); irNewObjectNode.attachDecoration(new IRDExpressionType(valueType)); @@ -1254,29 +1248,28 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor valueType = scriptScope.getDecoration(callLocalNode, ValueType.class).getValueType(); + Class valueType = scriptScope.getDecoration(callLocalNode, ValueType.class).valueType(); irInvokeCallMemberNode.attachDecoration(new IRDExpressionType(valueType)); scriptScope.putDecoration(callLocalNode, new IRNodeDecoration(irInvokeCallMemberNode)); @@ -1314,8 +1307,8 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor valueType = scriptScope.getDecoration(userBooleanConstantNode, ValueType.class).getValueType(); - Object constant = scriptScope.getDecoration(userBooleanConstantNode, StandardConstant.class).getStandardConstant(); + Class valueType = scriptScope.getDecoration(userBooleanConstantNode, ValueType.class).valueType(); + Object constant = scriptScope.getDecoration(userBooleanConstantNode, StandardConstant.class).standardConstant(); ConstantNode irConstantNode = new ConstantNode(userBooleanConstantNode.getLocation()); irConstantNode.attachDecoration(new IRDExpressionType(valueType)); @@ -1326,8 +1319,8 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor valueType = scriptScope.getDecoration(userNumericNode, ValueType.class).getValueType(); - Object constant = scriptScope.getDecoration(userNumericNode, StandardConstant.class).getStandardConstant(); + Class valueType = scriptScope.getDecoration(userNumericNode, ValueType.class).valueType(); + Object constant = scriptScope.getDecoration(userNumericNode, StandardConstant.class).standardConstant(); ConstantNode irConstantNode = new ConstantNode(userNumericNode.getLocation()); irConstantNode.attachDecoration(new IRDExpressionType(valueType)); @@ -1338,8 +1331,8 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor valueType = scriptScope.getDecoration(userDecimalNode, ValueType.class).getValueType(); - Object constant = scriptScope.getDecoration(userDecimalNode, StandardConstant.class).getStandardConstant(); + Class valueType = scriptScope.getDecoration(userDecimalNode, ValueType.class).valueType(); + Object constant = scriptScope.getDecoration(userDecimalNode, StandardConstant.class).standardConstant(); ConstantNode irConstantNode = new ConstantNode(userDecimalNode.getLocation()); irConstantNode.attachDecoration(new IRDExpressionType(valueType)); @@ -1350,8 +1343,8 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor valueType = scriptScope.getDecoration(userStringNode, ValueType.class).getValueType(); - Object constant = scriptScope.getDecoration(userStringNode, StandardConstant.class).getStandardConstant(); + Class valueType = scriptScope.getDecoration(userStringNode, ValueType.class).valueType(); + Object constant = scriptScope.getDecoration(userStringNode, StandardConstant.class).standardConstant(); ConstantNode irConstantNode = new ConstantNode(userStringNode.getLocation()); irConstantNode.attachDecoration(new IRDExpressionType(valueType)); @@ -1363,7 +1356,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor(scriptScope.getDecoration(userLambdaNode, TypeParameters.class).getTypeParameters())) + new IRDTypeParameters(new ArrayList<>(scriptScope.getDecoration(userLambdaNode, TypeParameters.class).typeParameters())) ); irFunctionNode.attachDecoration( - new IRDParameterNames(new ArrayList<>(scriptScope.getDecoration(userLambdaNode, ParameterNames.class).getParameterNames())) + new IRDParameterNames(new ArrayList<>(scriptScope.getDecoration(userLambdaNode, ParameterNames.class).parameterNames())) ); if (scriptScope.getCondition(userLambdaNode, InstanceCapturingLambda.class)) { irFunctionNode.attachCondition(IRCInstanceCapture.class); @@ -1414,15 +1407,15 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor captures = scriptScope.getDecoration(userLambdaNode, CapturesDecoration.class).getCaptures(); + List captures = scriptScope.getDecoration(userLambdaNode, CapturesDecoration.class).captures(); if (captures.isEmpty() == false) { List captureNames = new ArrayList<>(); for (Variable capture : captures) { - captureNames.add(capture.getName()); + captureNames.add(capture.name()); } irExpressionNode.attachDecoration(new IRDCaptureNames(captureNames)); @@ -1439,19 +1432,19 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor returnType = scriptScope.getDecoration(userNewArrayFunctionRefNode, ReturnType.class).getReturnType(); + Class returnType = scriptScope.getDecoration(userNewArrayFunctionRefNode, ReturnType.class).returnType(); LoadVariableNode irLoadVariableNode = new LoadVariableNode(userNewArrayFunctionRefNode.getLocation()); irLoadVariableNode.attachDecoration(new IRDExpressionType(int.class)); @@ -1514,7 +1505,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor staticType = scriptScope.getDecoration(userSymbolNode, StaticType.class).getStaticType(); + Class staticType = scriptScope.getDecoration(userSymbolNode, StaticType.class).staticType(); StaticNode staticNode = new StaticNode(userSymbolNode.getLocation()); staticNode.attachDecoration(new IRDExpressionType(staticType)); irExpressionNode = staticNode; @@ -1552,7 +1543,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor valueType = scriptScope.getDecoration(userSymbolNode, ValueType.class).getValueType(); + Class valueType = scriptScope.getDecoration(userSymbolNode, ValueType.class).valueType(); UnaryNode irStoreNode = null; ExpressionNode irLoadNode = null; @@ -1590,7 +1581,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor staticType = scriptScope.getDecoration(userDotNode, StaticType.class).getStaticType(); + Class staticType = scriptScope.getDecoration(userDotNode, StaticType.class).staticType(); StaticNode staticNode = new StaticNode(userDotNode.getLocation()); staticNode.attachDecoration(new IRDExpressionType(staticType)); irExpressionNode = staticNode; @@ -1600,7 +1591,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor valueType = scriptScope.getDecoration(userDotNode, ValueType.class).getValueType(); + Class valueType = scriptScope.getDecoration(userDotNode, ValueType.class).valueType(); ValueType prefixValueType = scriptScope.getDecoration(userDotNode.getPrefixNode(), ValueType.class); ExpressionNode irPrefixNode = (ExpressionNode) visit(userDotNode.getPrefixNode(), scriptScope); @@ -1609,13 +1600,13 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor valueType = scriptScope.getDecoration(userBraceNode, ValueType.class).getValueType(); - Class prefixValueType = scriptScope.getDecoration(userBraceNode.getPrefixNode(), ValueType.class).getValueType(); + Class valueType = scriptScope.getDecoration(userBraceNode, ValueType.class).valueType(); + Class prefixValueType = scriptScope.getDecoration(userBraceNode.getPrefixNode(), ValueType.class).valueType(); ExpressionNode irPrefixNode = (ExpressionNode) visit(userBraceNode.getPrefixNode(), scriptScope); ExpressionNode irIndexNode = injectCast(userBraceNode.getIndexNode(), scriptScope); @@ -1783,7 +1773,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor indexType = scriptScope.getDecoration(userBraceNode.getIndexNode(), ValueType.class).getValueType(); + Class indexType = scriptScope.getDecoration(userBraceNode.getIndexNode(), ValueType.class).valueType(); FlipDefIndexNode irFlipDefIndexNode = new FlipDefIndexNode(userBraceNode.getIndexNode().getLocation()); irFlipDefIndexNode.attachDecoration(new IRDExpressionType(indexType)); irFlipDefIndexNode.setChildNode(irIndexNode); @@ -1805,7 +1795,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor valueType = scriptScope.getDecoration(userCallNode, ValueType.class).getValueType(); + Class valueType = scriptScope.getDecoration(userCallNode, ValueType.class).valueType(); if (scriptScope.getCondition(userCallNode, DynamicInvocation.class)) { InvokeCallDefNode irCallSubDefNode = new InvokeCallDefNode(userCallNode.getLocation()); @@ -1875,16 +1865,16 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor boxType; if (prefixValueType != null) { - boxType = prefixValueType.getValueType(); + boxType = prefixValueType.valueType(); } else { - boxType = scriptScope.getDecoration(userCallNode.getPrefixNode(), StaticType.class).getStaticType(); + boxType = scriptScope.getDecoration(userCallNode.getPrefixNode(), StaticType.class).staticType(); } InvokeCallNode irInvokeCallNode = new InvokeCallNode(userCallNode.getLocation()); - PainlessMethod method = scriptScope.getDecoration(userCallNode, StandardPainlessMethod.class).getStandardPainlessMethod(); + PainlessMethod method = scriptScope.getDecoration(userCallNode, StandardPainlessMethod.class).standardPainlessMethod(); Object[] injections = PainlessLookupUtility.buildInjections(method, scriptScope.getCompilerSettings().asMap()); - Class[] parameterTypes = method.javaMethod.getParameterTypes(); - int augmentedOffset = method.javaMethod.getDeclaringClass() == method.targetClass ? 0 : 1; + Class[] parameterTypes = method.javaMethod().getParameterTypes(); + int augmentedOffset = method.javaMethod().getDeclaringClass() == method.targetClass() ? 0 : 1; for (int i = 0; i < injections.length; i++) { Object injection = injections[i]; @@ -1905,7 +1895,7 @@ public class DefaultUserTreeToIRTreePhase implements UserTreeVisitor expressionValueType = semanticScope.getDecoration(userStatementNode, Decorations.ValueType.class).getValueType(); + Class expressionValueType = semanticScope.getDecoration(userStatementNode, Decorations.ValueType.class).valueType(); boolean rtn = lastSource && isVoid == false && expressionValueType != void.class; if (rtn) { @@ -203,8 +203,8 @@ public class PainlessSemanticAnalysisPhase extends DefaultSemanticAnalysisPhase ScriptClassInfo scriptClassInfo ) { Location location = userExpressionNode.getLocation(); - Class valueType = semanticScope.getDecoration(userExpressionNode, Decorations.ValueType.class).getValueType(); - Class targetType = semanticScope.getDecoration(userExpressionNode, TargetType.class).getTargetType(); + Class valueType = semanticScope.getDecoration(userExpressionNode, Decorations.ValueType.class).valueType(); + Class targetType = semanticScope.getDecoration(userExpressionNode, TargetType.class).targetType(); PainlessCast painlessCast; if (valueType == def.class) { diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/phase/PainlessUserTreeToIRTreePhase.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/phase/PainlessUserTreeToIRTreePhase.java index b34272d62b55..755a91fd8a49 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/phase/PainlessUserTreeToIRTreePhase.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/phase/PainlessUserTreeToIRTreePhase.java @@ -530,7 +530,7 @@ public class PainlessUserTreeToIRTreePhase extends DefaultUserTreeToIRTreePhase } IRNodeDecoration irNodeDecoration = scriptScope.getDecoration(userStatementNode, IRNodeDecoration.class); - IRNode irNode = irNodeDecoration.getIRNode(); + IRNode irNode = irNodeDecoration.irNode(); if ((irNode instanceof ReturnNode) == false) { // Shouldn't have a Converter decoration if StatementExpressionNode, should be ReturnNode if explicit return @@ -541,7 +541,7 @@ public class PainlessUserTreeToIRTreePhase extends DefaultUserTreeToIRTreePhase // inject converter InvokeCallMemberNode irInvokeCallMemberNode = new InvokeCallMemberNode(userStatementNode.getLocation()); - irInvokeCallMemberNode.attachDecoration(new IRDFunction(converter.getConverter())); + irInvokeCallMemberNode.attachDecoration(new IRDFunction(converter.converter())); ExpressionNode returnExpression = returnNode.getExpressionNode(); returnNode.setExpressionNode(irInvokeCallMemberNode); irInvokeCallMemberNode.addArgumentNode(returnExpression); @@ -550,7 +550,7 @@ public class PainlessUserTreeToIRTreePhase extends DefaultUserTreeToIRTreePhase @Override public void visitCallLocal(ECallLocal userCallLocalNode, ScriptScope scriptScope) { if ("$".equals(userCallLocalNode.getMethodName())) { - PainlessMethod thisMethod = scriptScope.getDecoration(userCallLocalNode, ThisPainlessMethod.class).getThisPainlessMethod(); + PainlessMethod thisMethod = scriptScope.getDecoration(userCallLocalNode, ThisPainlessMethod.class).thisPainlessMethod(); InvokeCallMemberNode irInvokeCallMemberNode = new InvokeCallMemberNode(userCallLocalNode.getLocation()); irInvokeCallMemberNode.attachDecoration(new IRDThisMethod(thisMethod)); diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/symbol/Decorations.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/symbol/Decorations.java index 320da296bdae..a7989972264b 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/symbol/Decorations.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/symbol/Decorations.java @@ -80,17 +80,7 @@ public class Decorations { } - public static class TargetType implements Decoration { - - private final Class targetType; - - public TargetType(Class targetType) { - this.targetType = Objects.requireNonNull(targetType); - } - - public Class getTargetType() { - return targetType; - } + public record TargetType(Class targetType) implements Decoration { public String getTargetCanonicalTypeName() { return PainlessLookupUtility.typeToCanonicalTypeName(targetType); @@ -107,51 +97,22 @@ public class Decorations { // standard output for user expression node during semantic phase - public static class ValueType implements Decoration { - - private final Class valueType; - - public ValueType(Class valueType) { - this.valueType = Objects.requireNonNull(valueType); - } - - public Class getValueType() { - return valueType; - } + public record ValueType(Class valueType) implements Decoration { public String getValueCanonicalTypeName() { return PainlessLookupUtility.typeToCanonicalTypeName(valueType); } } - public static class StaticType implements Decoration { - - private final Class staticType; - - public StaticType(Class staticType) { - this.staticType = Objects.requireNonNull(staticType); - } - - public Class getStaticType() { - return staticType; - } + public record StaticType(Class staticType) implements Decoration { public String getStaticCanonicalTypeName() { return PainlessLookupUtility.typeToCanonicalTypeName(staticType); } } - public static class PartialCanonicalTypeName implements Decoration { + public record PartialCanonicalTypeName(String partialCanonicalTypeName) implements Decoration { - private final String partialCanonicalTypeName; - - public PartialCanonicalTypeName(String partialCanonicalTypeName) { - this.partialCanonicalTypeName = Objects.requireNonNull(partialCanonicalTypeName); - } - - public String getPartialCanonicalTypeName() { - return partialCanonicalTypeName; - } } public interface DefOptimized extends Condition { @@ -176,381 +137,121 @@ public class Decorations { } - public static class ExpressionPainlessCast implements Decoration { + public record ExpressionPainlessCast(PainlessCast expressionPainlessCast) implements Decoration {} - private final PainlessCast expressionPainlessCast; + public record SemanticVariable(Variable semanticVariable) implements Decoration {} - public ExpressionPainlessCast(PainlessCast expressionPainlessCast) { - this.expressionPainlessCast = Objects.requireNonNull(expressionPainlessCast); - } + public record IterablePainlessMethod(PainlessMethod iterablePainlessMethod) implements Decoration {} - public PainlessCast getExpressionPainlessCast() { - return expressionPainlessCast; - } - } - - public static class SemanticVariable implements Decoration { - - private final Variable semanticVariable; - - public SemanticVariable(Variable semanticVariable) { - this.semanticVariable = semanticVariable; - } - - public Variable getSemanticVariable() { - return semanticVariable; - } - } - - public static class IterablePainlessMethod implements Decoration { - - private final PainlessMethod iterablePainlessMethod; - - public IterablePainlessMethod(PainlessMethod iterablePainlessMethod) { - this.iterablePainlessMethod = Objects.requireNonNull(iterablePainlessMethod); - } - - public PainlessMethod getIterablePainlessMethod() { - return iterablePainlessMethod; - } - } - - public static class UnaryType implements Decoration { - - private final Class unaryType; - - public UnaryType(Class unaryType) { - this.unaryType = Objects.requireNonNull(unaryType); - } - - public Class getUnaryType() { - return unaryType; - } + public record UnaryType(Class unaryType) implements Decoration { public String getUnaryCanonicalTypeName() { return PainlessLookupUtility.typeToCanonicalTypeName(unaryType); } } - public static class BinaryType implements Decoration { - - private final Class binaryType; - - public BinaryType(Class binaryType) { - this.binaryType = Objects.requireNonNull(binaryType); - } - - public Class getBinaryType() { - return binaryType; - } + public record BinaryType(Class binaryType) implements Decoration { public String getBinaryCanonicalTypeName() { return PainlessLookupUtility.typeToCanonicalTypeName(binaryType); } } - public static class ShiftType implements Decoration { - - private final Class shiftType; - - public ShiftType(Class shiftType) { - this.shiftType = Objects.requireNonNull(shiftType); - } - - public Class getShiftType() { - return shiftType; - } + public record ShiftType(Class shiftType) implements Decoration { public String getShiftCanonicalTypeName() { return PainlessLookupUtility.typeToCanonicalTypeName(shiftType); } } - public static class ComparisonType implements Decoration { - - private final Class comparisonType; - - public ComparisonType(Class comparisonType) { - this.comparisonType = Objects.requireNonNull(comparisonType); - } - - public Class getComparisonType() { - return comparisonType; - } + public record ComparisonType(Class comparisonType) implements Decoration { public String getComparisonCanonicalTypeName() { return PainlessLookupUtility.typeToCanonicalTypeName(comparisonType); } } - public static class CompoundType implements Decoration { - - private final Class compoundType; - - public CompoundType(Class compoundType) { - this.compoundType = Objects.requireNonNull(compoundType); - } - - public Class getCompoundType() { - return compoundType; - } + public record CompoundType(Class compoundType) implements Decoration { public String getCompoundCanonicalTypeName() { return PainlessLookupUtility.typeToCanonicalTypeName(compoundType); } } - public static class UpcastPainlessCast implements Decoration { + public record UpcastPainlessCast(PainlessCast upcastPainlessCast) implements Decoration {} - private final PainlessCast upcastPainlessCast; - - public UpcastPainlessCast(PainlessCast upcastPainlessCast) { - this.upcastPainlessCast = Objects.requireNonNull(upcastPainlessCast); - } - - public PainlessCast getUpcastPainlessCast() { - return upcastPainlessCast; - } - } - - public static class DowncastPainlessCast implements Decoration { - - private final PainlessCast downcastPainlessCast; + public record DowncastPainlessCast(PainlessCast downcastPainlessCast) implements Decoration { public DowncastPainlessCast(PainlessCast downcastPainlessCast) { this.downcastPainlessCast = Objects.requireNonNull(downcastPainlessCast); } - - public PainlessCast getDowncastPainlessCast() { - return downcastPainlessCast; - } } - public static class StandardPainlessField implements Decoration { + public record StandardPainlessField(PainlessField standardPainlessField) implements Decoration {} - private final PainlessField standardPainlessField; + public record StandardPainlessConstructor(PainlessConstructor standardPainlessConstructor) implements Decoration {} - public StandardPainlessField(PainlessField standardPainlessField) { - this.standardPainlessField = Objects.requireNonNull(standardPainlessField); - } + public record StandardPainlessMethod(PainlessMethod standardPainlessMethod) implements Decoration {} - public PainlessField getStandardPainlessField() { - return standardPainlessField; - } - } + public interface DynamicInvocation extends Condition {} - public static class StandardPainlessConstructor implements Decoration { + public record GetterPainlessMethod(PainlessMethod getterPainlessMethod) implements Decoration {} - private final PainlessConstructor standardPainlessConstructor; + public record SetterPainlessMethod(PainlessMethod setterPainlessMethod) implements Decoration {} - public StandardPainlessConstructor(PainlessConstructor standardPainlessConstructor) { - this.standardPainlessConstructor = Objects.requireNonNull(standardPainlessConstructor); - } + public record StandardConstant(Object standardConstant) implements Decoration {} - public PainlessConstructor getStandardPainlessConstructor() { - return standardPainlessConstructor; - } - } + public record StandardLocalFunction(LocalFunction localFunction) implements Decoration {} - public static class StandardPainlessMethod implements Decoration { + public record ThisPainlessMethod(PainlessMethod thisPainlessMethod) implements Decoration {} - private final PainlessMethod standardPainlessMethod; + public record StandardPainlessClassBinding(PainlessClassBinding painlessClassBinding) implements Decoration {} - public StandardPainlessMethod(PainlessMethod standardPainlessMethod) { - this.standardPainlessMethod = Objects.requireNonNull(standardPainlessMethod); - } - - public PainlessMethod getStandardPainlessMethod() { - return standardPainlessMethod; - } - } - - public interface DynamicInvocation extends Condition { + public record StandardPainlessInstanceBinding(PainlessInstanceBinding painlessInstanceBinding) implements Decoration { } - public static class GetterPainlessMethod implements Decoration { + public record MethodNameDecoration(String methodName) implements Decoration { - private final PainlessMethod getterPainlessMethod; - - public GetterPainlessMethod(PainlessMethod getterPainlessMethod) { - this.getterPainlessMethod = Objects.requireNonNull(getterPainlessMethod); - } - - public PainlessMethod getGetterPainlessMethod() { - return getterPainlessMethod; - } } - public static class SetterPainlessMethod implements Decoration { - - private final PainlessMethod setterPainlessMethod; - - public SetterPainlessMethod(PainlessMethod setterPainlessMethod) { - this.setterPainlessMethod = Objects.requireNonNull(setterPainlessMethod); - } - - public PainlessMethod getSetterPainlessMethod() { - return setterPainlessMethod; - } - } - - public static class StandardConstant implements Decoration { - - private final Object standardConstant; - - public StandardConstant(Object standardConstant) { - this.standardConstant = Objects.requireNonNull(standardConstant); - } - - public Object getStandardConstant() { - return standardConstant; - } - } - - public static class StandardLocalFunction implements Decoration { - - private final LocalFunction localFunction; - - public StandardLocalFunction(LocalFunction localFunction) { - this.localFunction = Objects.requireNonNull(localFunction); - } - - public LocalFunction getLocalFunction() { - return localFunction; - } - } - - public static class ThisPainlessMethod implements Decoration { - - private final PainlessMethod thisPainlessMethod; - - public ThisPainlessMethod(PainlessMethod thisPainlessMethod) { - this.thisPainlessMethod = Objects.requireNonNull(thisPainlessMethod); - } - - public PainlessMethod getThisPainlessMethod() { - return thisPainlessMethod; - } - } - - public static class StandardPainlessClassBinding implements Decoration { - - private final PainlessClassBinding painlessClassBinding; - - public StandardPainlessClassBinding(PainlessClassBinding painlessClassBinding) { - this.painlessClassBinding = Objects.requireNonNull(painlessClassBinding); - } - - public PainlessClassBinding getPainlessClassBinding() { - return painlessClassBinding; - } - } - - public static class StandardPainlessInstanceBinding implements Decoration { - - private final PainlessInstanceBinding painlessInstanceBinding; - - public StandardPainlessInstanceBinding(PainlessInstanceBinding painlessInstanceBinding) { - this.painlessInstanceBinding = Objects.requireNonNull(painlessInstanceBinding); - } - - public PainlessInstanceBinding getPainlessInstanceBinding() { - return painlessInstanceBinding; - } - } - - public static class MethodNameDecoration implements Decoration { - - private final String methodName; - - public MethodNameDecoration(String methodName) { - this.methodName = Objects.requireNonNull(methodName); - } - - public String getMethodName() { - return methodName; - } - } - - public static class ReturnType implements Decoration { - - private final Class returnType; - - public ReturnType(Class returnType) { - this.returnType = Objects.requireNonNull(returnType); - } - - public Class getReturnType() { - return returnType; - } + public record ReturnType(Class returnType) implements Decoration { public String getReturnCanonicalTypeName() { return PainlessLookupUtility.typeToCanonicalTypeName(returnType); } } - public static class TypeParameters implements Decoration { - - private final List> typeParameters; + public record TypeParameters(List> typeParameters) implements Decoration { public TypeParameters(List> typeParameters) { this.typeParameters = Collections.unmodifiableList(new ArrayList<>(Objects.requireNonNull(typeParameters))); } - - public List> getTypeParameters() { - return typeParameters; - } } - public static class ParameterNames implements Decoration { - - private final List parameterNames; + public record ParameterNames(List parameterNames) implements Decoration { public ParameterNames(List parameterNames) { this.parameterNames = Collections.unmodifiableList(new ArrayList<>(Objects.requireNonNull(parameterNames))); } + } - public List getParameterNames() { - return parameterNames; + public record ReferenceDecoration(FunctionRef reference) implements Decoration {} + + public record EncodingDecoration(Def.Encoding encoding) implements Decoration { + + public static EncodingDecoration of(boolean isStatic, boolean needsInstance, String symbol, String methodName, int captures) { + return new EncodingDecoration(new Def.Encoding(isStatic, needsInstance, symbol, methodName, captures)); } } - public static class ReferenceDecoration implements Decoration { - - private final FunctionRef reference; - - public ReferenceDecoration(FunctionRef reference) { - this.reference = Objects.requireNonNull(reference); - } - - public FunctionRef getReference() { - return reference; - } - } - - public static class EncodingDecoration implements Decoration { - - private final Def.Encoding encoding; - - public EncodingDecoration(boolean isStatic, boolean needsInstance, String symbol, String methodName, int captures) { - this.encoding = new Def.Encoding(isStatic, needsInstance, symbol, methodName, captures); - } - - public Def.Encoding getEncoding() { - return encoding; - } - } - - public static class CapturesDecoration implements Decoration { - - private final List captures; + public record CapturesDecoration(List captures) implements Decoration { public CapturesDecoration(List captures) { this.captures = Collections.unmodifiableList(new ArrayList<>(Objects.requireNonNull(captures))); } - public List getCaptures() { + public List captures() { return captures; } } @@ -559,17 +260,7 @@ public class Decorations { } - public static class InstanceType implements Decoration { - - private final Class instanceType; - - public InstanceType(Class instanceType) { - this.instanceType = Objects.requireNonNull(instanceType); - } - - public Class getInstanceType() { - return instanceType; - } + public record InstanceType(Class instanceType) implements Decoration { public String getInstanceCanonicalTypeName() { return PainlessLookupUtility.typeToCanonicalTypeName(instanceType); @@ -584,45 +275,13 @@ public class Decorations { } - public static class AccessDepth implements Decoration { - - private final int accessDepth; - - public AccessDepth(int accessDepth) { - this.accessDepth = accessDepth; - } - - public int getAccessDepth() { - return accessDepth; - } - } + public record AccessDepth(int accessDepth) implements Decoration {} // standard output for user tree to ir tree phase - public static class IRNodeDecoration implements Decoration { + public record IRNodeDecoration(IRNode irNode) implements Decoration {} - private final IRNode irNode; - - public IRNodeDecoration(IRNode irNode) { - this.irNode = Objects.requireNonNull(irNode); - } - - public IRNode getIRNode() { - return irNode; - } - } - - public static class Converter implements Decoration { - private final LocalFunction converter; - - public Converter(LocalFunction converter) { - this.converter = converter; - } - - public LocalFunction getConverter() { - return converter; - } - } + public record Converter(LocalFunction converter) implements Decoration {} // collect additional information about where doc is used diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/symbol/IRDecorations.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/symbol/IRDecorations.java index f9e76e5317b1..ecb1990fc3bf 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/symbol/IRDecorations.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/symbol/IRDecorations.java @@ -286,7 +286,7 @@ public class IRDecorations { @Override public String toString() { - return PainlessLookupUtility.buildPainlessMethodKey(getValue().javaMethod.getName(), getValue().typeParameters.size()); + return PainlessLookupUtility.buildPainlessMethodKey(getValue().javaMethod().getName(), getValue().typeParameters().size()); } } @@ -379,7 +379,7 @@ public class IRDecorations { @Override public String toString() { - return PainlessLookupUtility.buildPainlessMethodKey(getValue().javaMethod.getName(), getValue().typeParameters.size()); + return PainlessLookupUtility.buildPainlessMethodKey(getValue().javaMethod().getName(), getValue().typeParameters().size()); } } diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/symbol/SemanticScope.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/symbol/SemanticScope.java index 3e3c4b9e8ad4..2d5dd2668e34 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/symbol/SemanticScope.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/symbol/SemanticScope.java @@ -38,20 +38,11 @@ public abstract class SemanticScope { * variables. Each {@link SemanticScope} tracks its own set of defined * variables available for use. */ - public static class Variable { + public record Variable(Class type, String name, boolean isFinal) { - protected final Class type; - protected final String name; - protected final boolean isFinal; - - public Variable(Class type, String name, boolean isFinal) { - this.type = Objects.requireNonNull(type); - this.name = Objects.requireNonNull(name); - this.isFinal = isFinal; - } - - public Class getType() { - return type; + public Variable { + Objects.requireNonNull(type); + Objects.requireNonNull(name); } /** @@ -61,14 +52,6 @@ public abstract class SemanticScope { public String getCanonicalTypeName() { return PainlessLookupUtility.typeToCanonicalTypeName(type); } - - public String getName() { - return name; - } - - public boolean isFinal() { - return isFinal; - } } /** @@ -169,7 +152,7 @@ public abstract class SemanticScope { if (variable == null) { variable = parent.getVariable(location, name); - variable = new Variable(variable.getType(), variable.getName(), true); + variable = new Variable(variable.type(), variable.name(), true); captures.add(variable); } else { usedVariables.add(name); diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/toxcontent/DecorationToXContent.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/toxcontent/DecorationToXContent.java index 643818c75020..a9e3474e80cf 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/toxcontent/DecorationToXContent.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/toxcontent/DecorationToXContent.java @@ -83,133 +83,133 @@ public class DecorationToXContent { public static void ToXContent(TargetType targetType, XContentBuilderWrapper builder) { start(targetType, builder); - builder.field(Fields.TYPE, targetType.getTargetType().getSimpleName()); + builder.field(Fields.TYPE, targetType.targetType().getSimpleName()); builder.endObject(); } public static void ToXContent(ValueType valueType, XContentBuilderWrapper builder) { start(valueType, builder); - builder.field(Fields.TYPE, valueType.getValueType().getSimpleName()); + builder.field(Fields.TYPE, valueType.valueType().getSimpleName()); builder.endObject(); } public static void ToXContent(StaticType staticType, XContentBuilderWrapper builder) { start(staticType, builder); - builder.field(Fields.TYPE, staticType.getStaticType().getSimpleName()); + builder.field(Fields.TYPE, staticType.staticType().getSimpleName()); builder.endObject(); } public static void ToXContent(PartialCanonicalTypeName partialCanonicalTypeName, XContentBuilderWrapper builder) { start(partialCanonicalTypeName, builder); - builder.field(Fields.TYPE, partialCanonicalTypeName.getPartialCanonicalTypeName()); + builder.field(Fields.TYPE, partialCanonicalTypeName.partialCanonicalTypeName()); builder.endObject(); } public static void ToXContent(ExpressionPainlessCast expressionPainlessCast, XContentBuilderWrapper builder) { start(expressionPainlessCast, builder); builder.field(Fields.CAST); - ToXContent(expressionPainlessCast.getExpressionPainlessCast(), builder); + ToXContent(expressionPainlessCast.expressionPainlessCast(), builder); builder.endObject(); } public static void ToXContent(SemanticVariable semanticVariable, XContentBuilderWrapper builder) { start(semanticVariable, builder); builder.field("variable"); - ToXContent(semanticVariable.getSemanticVariable(), builder); + ToXContent(semanticVariable.semanticVariable(), builder); builder.endObject(); } public static void ToXContent(IterablePainlessMethod iterablePainlessMethod, XContentBuilderWrapper builder) { start(iterablePainlessMethod, builder); builder.field(Fields.METHOD); - ToXContent(iterablePainlessMethod.getIterablePainlessMethod(), builder); + ToXContent(iterablePainlessMethod.iterablePainlessMethod(), builder); builder.endObject(); } public static void ToXContent(UnaryType unaryType, XContentBuilderWrapper builder) { start(unaryType, builder); - builder.field(Fields.TYPE, unaryType.getUnaryType().getSimpleName()); + builder.field(Fields.TYPE, unaryType.unaryType().getSimpleName()); builder.endObject(); } public static void ToXContent(BinaryType binaryType, XContentBuilderWrapper builder) { start(binaryType, builder); - builder.field(Fields.TYPE, binaryType.getBinaryType().getSimpleName()); + builder.field(Fields.TYPE, binaryType.binaryType().getSimpleName()); builder.endObject(); } public static void ToXContent(ShiftType shiftType, XContentBuilderWrapper builder) { start(shiftType, builder); - builder.field(Fields.TYPE, shiftType.getShiftType().getSimpleName()); + builder.field(Fields.TYPE, shiftType.shiftType().getSimpleName()); builder.endObject(); } public static void ToXContent(ComparisonType comparisonType, XContentBuilderWrapper builder) { start(comparisonType, builder); - builder.field(Fields.TYPE, comparisonType.getComparisonType().getSimpleName()); + builder.field(Fields.TYPE, comparisonType.comparisonType().getSimpleName()); builder.endObject(); } public static void ToXContent(CompoundType compoundType, XContentBuilderWrapper builder) { start(compoundType, builder); - builder.field(Fields.TYPE, compoundType.getCompoundType().getSimpleName()); + builder.field(Fields.TYPE, compoundType.compoundType().getSimpleName()); builder.endObject(); } public static void ToXContent(UpcastPainlessCast upcastPainlessCast, XContentBuilderWrapper builder) { start(upcastPainlessCast, builder); builder.field(Fields.CAST); - ToXContent(upcastPainlessCast.getUpcastPainlessCast(), builder); + ToXContent(upcastPainlessCast.upcastPainlessCast(), builder); builder.endObject(); } public static void ToXContent(DowncastPainlessCast downcastPainlessCast, XContentBuilderWrapper builder) { start(downcastPainlessCast, builder); builder.field(Fields.CAST); - ToXContent(downcastPainlessCast.getDowncastPainlessCast(), builder); + ToXContent(downcastPainlessCast.downcastPainlessCast(), builder); builder.endObject(); } public static void ToXContent(StandardPainlessField standardPainlessField, XContentBuilderWrapper builder) { start(standardPainlessField, builder); builder.field("field"); - ToXContent(standardPainlessField.getStandardPainlessField(), builder); + ToXContent(standardPainlessField.standardPainlessField(), builder); builder.endObject(); } public static void ToXContent(StandardPainlessConstructor standardPainlessConstructor, XContentBuilderWrapper builder) { start(standardPainlessConstructor, builder); builder.field("constructor"); - ToXContent(standardPainlessConstructor.getStandardPainlessConstructor(), builder); + ToXContent(standardPainlessConstructor.standardPainlessConstructor(), builder); builder.endObject(); } public static void ToXContent(StandardPainlessMethod standardPainlessMethod, XContentBuilderWrapper builder) { start(standardPainlessMethod, builder); builder.field(Fields.METHOD); - ToXContent(standardPainlessMethod.getStandardPainlessMethod(), builder); + ToXContent(standardPainlessMethod.standardPainlessMethod(), builder); builder.endObject(); } public static void ToXContent(GetterPainlessMethod getterPainlessMethod, XContentBuilderWrapper builder) { start(getterPainlessMethod, builder); builder.field(Fields.METHOD); - ToXContent(getterPainlessMethod.getGetterPainlessMethod(), builder); + ToXContent(getterPainlessMethod.getterPainlessMethod(), builder); builder.endObject(); } public static void ToXContent(SetterPainlessMethod setterPainlessMethod, XContentBuilderWrapper builder) { start(setterPainlessMethod, builder); builder.field(Fields.METHOD); - ToXContent(setterPainlessMethod.getSetterPainlessMethod(), builder); + ToXContent(setterPainlessMethod.setterPainlessMethod(), builder); builder.endObject(); } public static void ToXContent(StandardConstant standardConstant, XContentBuilderWrapper builder) { start(standardConstant, builder); builder.startObject("constant"); - builder.field(Fields.TYPE, standardConstant.getStandardConstant().getClass().getSimpleName()); - builder.field("value", standardConstant.getStandardConstant()); + builder.field(Fields.TYPE, standardConstant.standardConstant().getClass().getSimpleName()); + builder.field("value", standardConstant.standardConstant()); builder.endObject(); builder.endObject(); } @@ -217,55 +217,55 @@ public class DecorationToXContent { public static void ToXContent(StandardLocalFunction standardLocalFunction, XContentBuilderWrapper builder) { start(standardLocalFunction, builder); builder.field("function"); - ToXContent(standardLocalFunction.getLocalFunction(), builder); + ToXContent(standardLocalFunction.localFunction(), builder); builder.endObject(); } public static void ToXContent(StandardPainlessClassBinding standardPainlessClassBinding, XContentBuilderWrapper builder) { start(standardPainlessClassBinding, builder); builder.field("PainlessClassBinding"); - ToXContent(standardPainlessClassBinding.getPainlessClassBinding(), builder); + ToXContent(standardPainlessClassBinding.painlessClassBinding(), builder); builder.endObject(); } public static void ToXContent(StandardPainlessInstanceBinding standardPainlessInstanceBinding, XContentBuilderWrapper builder) { start(standardPainlessInstanceBinding, builder); builder.field("PainlessInstanceBinding"); - ToXContent(standardPainlessInstanceBinding.getPainlessInstanceBinding(), builder); + ToXContent(standardPainlessInstanceBinding.painlessInstanceBinding(), builder); builder.endObject(); } public static void ToXContent(MethodNameDecoration methodNameDecoration, XContentBuilderWrapper builder) { start(methodNameDecoration, builder); - builder.field("methodName", methodNameDecoration.getMethodName()); + builder.field("methodName", methodNameDecoration.methodName()); builder.endObject(); } public static void ToXContent(ReturnType returnType, XContentBuilderWrapper builder) { start(returnType, builder); - builder.field("returnType", returnType.getReturnType().getSimpleName()); + builder.field("returnType", returnType.returnType().getSimpleName()); builder.endObject(); } public static void ToXContent(TypeParameters typeParameters, XContentBuilderWrapper builder) { start(typeParameters, builder); - if (typeParameters.getTypeParameters().isEmpty() == false) { - builder.field("typeParameters", classNames(typeParameters.getTypeParameters())); + if (typeParameters.typeParameters().isEmpty() == false) { + builder.field("typeParameters", classNames(typeParameters.typeParameters())); } builder.endObject(); } public static void ToXContent(ParameterNames parameterNames, XContentBuilderWrapper builder) { start(parameterNames, builder); - if (parameterNames.getParameterNames().isEmpty() == false) { - builder.field("parameterNames", parameterNames.getParameterNames()); + if (parameterNames.parameterNames().isEmpty() == false) { + builder.field("parameterNames", parameterNames.parameterNames()); } builder.endObject(); } public static void ToXContent(ReferenceDecoration referenceDecoration, XContentBuilderWrapper builder) { start(referenceDecoration, builder); - FunctionRef ref = referenceDecoration.getReference(); + FunctionRef ref = referenceDecoration.reference(); builder.field("interfaceMethodName", ref.interfaceMethodName); builder.field("interfaceMethodType"); @@ -298,15 +298,15 @@ public class DecorationToXContent { public static void ToXContent(EncodingDecoration encodingDecoration, XContentBuilderWrapper builder) { start(encodingDecoration, builder); - builder.field("encoding", encodingDecoration.getEncoding()); + builder.field("encoding", encodingDecoration.encoding()); builder.endObject(); } public static void ToXContent(CapturesDecoration capturesDecoration, XContentBuilderWrapper builder) { start(capturesDecoration, builder); - if (capturesDecoration.getCaptures().isEmpty() == false) { + if (capturesDecoration.captures().isEmpty() == false) { builder.startArray("captures"); - for (SemanticScope.Variable capture : capturesDecoration.getCaptures()) { + for (SemanticScope.Variable capture : capturesDecoration.captures()) { ToXContent(capture, builder); } builder.endArray(); @@ -316,27 +316,27 @@ public class DecorationToXContent { public static void ToXContent(InstanceType instanceType, XContentBuilderWrapper builder) { start(instanceType, builder); - builder.field("instanceType", instanceType.getInstanceType().getSimpleName()); + builder.field("instanceType", instanceType.instanceType().getSimpleName()); builder.endObject(); } public static void ToXContent(AccessDepth accessDepth, XContentBuilderWrapper builder) { start(accessDepth, builder); - builder.field("depth", accessDepth.getAccessDepth()); + builder.field("depth", accessDepth.accessDepth()); builder.endObject(); } public static void ToXContent(IRNodeDecoration irNodeDecoration, XContentBuilderWrapper builder) { start(irNodeDecoration, builder); // TODO(stu): expand this - builder.field("irNode", irNodeDecoration.getIRNode().toString()); + builder.field("irNode", irNodeDecoration.irNode().toString()); builder.endObject(); } public static void ToXContent(Converter converter, XContentBuilderWrapper builder) { start(converter, builder); builder.field("converter"); - ToXContent(converter.getConverter(), builder); + ToXContent(converter.converter(), builder); builder.endObject(); } @@ -442,25 +442,25 @@ public class DecorationToXContent { public static void ToXContent(PainlessMethod method, XContentBuilderWrapper builder) { builder.startObject(); - if (method.javaMethod != null) { + if (method.javaMethod() != null) { builder.field("javaMethod"); - ToXContent(method.methodType, builder); + ToXContent(method.methodType(), builder); } - if (method.targetClass != null) { - builder.field("targetClass", method.targetClass.getSimpleName()); + if (method.targetClass() != null) { + builder.field("targetClass", method.targetClass().getSimpleName()); } - if (method.returnType != null) { - builder.field("returnType", method.returnType.getSimpleName()); + if (method.returnType() != null) { + builder.field("returnType", method.returnType().getSimpleName()); } - if (method.typeParameters != null && method.typeParameters.isEmpty() == false) { - builder.field("typeParameters", classNames(method.typeParameters)); + if (method.typeParameters() != null && method.typeParameters().isEmpty() == false) { + builder.field("typeParameters", classNames(method.typeParameters())); } - if (method.methodHandle != null) { + if (method.methodHandle() != null) { builder.field("methodHandle"); - ToXContent(method.methodHandle.type(), builder); + ToXContent(method.methodHandle().type(), builder); } // ignoring methodType as that's handled under methodHandle - AnnotationsToXContent(method.annotations, builder); + AnnotationsToXContent(method.annotations(), builder); builder.endObject(); } @@ -481,42 +481,42 @@ public class DecorationToXContent { public static void ToXContent(PainlessClassBinding binding, XContentBuilderWrapper builder) { builder.startObject(); builder.field("javaConstructor"); - ToXContent(binding.javaConstructor, builder); + ToXContent(binding.javaConstructor(), builder); builder.field("javaMethod"); - ToXContent(binding.javaMethod, builder); - builder.field("returnType", binding.returnType.getSimpleName()); - if (binding.typeParameters.isEmpty() == false) { - builder.field("typeParameters", classNames(binding.typeParameters)); + ToXContent(binding.javaMethod(), builder); + builder.field("returnType", binding.returnType().getSimpleName()); + if (binding.typeParameters().isEmpty() == false) { + builder.field("typeParameters", classNames(binding.typeParameters())); } - AnnotationsToXContent(binding.annotations, builder); + AnnotationsToXContent(binding.annotations(), builder); builder.endObject(); } public static void ToXContent(PainlessInstanceBinding binding, XContentBuilderWrapper builder) { builder.startObject(); - builder.field("targetInstance", binding.targetInstance.getClass().getSimpleName()); + builder.field("targetInstance", binding.targetInstance().getClass().getSimpleName()); builder.field("javaMethod"); - ToXContent(binding.javaMethod, builder); - builder.field("returnType", binding.returnType.getSimpleName()); - if (binding.typeParameters.isEmpty() == false) { - builder.field("typeParameters", classNames(binding.typeParameters)); + ToXContent(binding.javaMethod(), builder); + builder.field("returnType", binding.returnType().getSimpleName()); + if (binding.typeParameters().isEmpty() == false) { + builder.field("typeParameters", classNames(binding.typeParameters())); } - AnnotationsToXContent(binding.annotations, builder); + AnnotationsToXContent(binding.annotations(), builder); builder.endObject(); } public static void ToXContent(PainlessField field, XContentBuilderWrapper builder) { builder.startObject(); builder.field("javaField"); - ToXContent(field.javaField, builder); - builder.field("typeParameter", field.typeParameter.getSimpleName()); + ToXContent(field.javaField(), builder); + builder.field("typeParameter", field.typeParameter().getSimpleName()); builder.field("getterMethodHandle"); - ToXContent(field.getterMethodHandle.type(), builder); + ToXContent(field.getterMethodHandle().type(), builder); builder.field("setterMethodHandle"); - if (field.setterMethodHandle != null) { - ToXContent(field.setterMethodHandle.type(), builder); + if (field.setterMethodHandle() != null) { + ToXContent(field.setterMethodHandle().type(), builder); } builder.endObject(); } @@ -524,20 +524,20 @@ public class DecorationToXContent { public static void ToXContent(PainlessConstructor constructor, XContentBuilderWrapper builder) { builder.startObject(); builder.field("javaConstructor"); - ToXContent(constructor.javaConstructor, builder); - if (constructor.typeParameters.isEmpty() == false) { - builder.field("typeParameters", classNames(constructor.typeParameters)); + ToXContent(constructor.javaConstructor(), builder); + if (constructor.typeParameters().isEmpty() == false) { + builder.field("typeParameters", classNames(constructor.typeParameters())); } builder.field("methodHandle"); - ToXContent(constructor.methodHandle.type(), builder); + ToXContent(constructor.methodHandle().type(), builder); builder.endObject(); } // symbol public static void ToXContent(SemanticScope.Variable variable, XContentBuilderWrapper builder) { builder.startObject(); - builder.field(Fields.TYPE, variable.getType()); - builder.field("name", variable.getName()); + builder.field(Fields.TYPE, variable.type()); + builder.field("name", variable.name()); builder.field("isFinal", variable.isFinal()); builder.endObject(); } @@ -560,12 +560,12 @@ public class DecorationToXContent { } else if (annotation instanceof DeprecatedAnnotation) { builder.startObject(); builder.field("name", DeprecatedAnnotation.NAME); - builder.field("message", ((DeprecatedAnnotation) annotation).getMessage()); + builder.field("message", ((DeprecatedAnnotation) annotation).message()); builder.endObject(); } else if (annotation instanceof InjectConstantAnnotation) { builder.startObject(); builder.field("name", InjectConstantAnnotation.NAME); - builder.field("message", ((InjectConstantAnnotation) annotation).injects); + builder.field("message", ((InjectConstantAnnotation) annotation).injects()); builder.endObject(); } else if (annotation instanceof NoImportAnnotation) { builder.value(NoImportAnnotation.NAME); diff --git a/modules/parent-join/src/main/java/org/elasticsearch/join/mapper/Joiner.java b/modules/parent-join/src/main/java/org/elasticsearch/join/mapper/Joiner.java index 59e12ce329f0..9a4911fb8c4d 100644 --- a/modules/parent-join/src/main/java/org/elasticsearch/join/mapper/Joiner.java +++ b/modules/parent-join/src/main/java/org/elasticsearch/join/mapper/Joiner.java @@ -66,12 +66,12 @@ public final class Joiner { Joiner(String joinField, List relations) { this.joinField = joinField; for (Relations r : relations) { - for (String child : r.children) { - parentsToChildren.put(r.parent, r.children); + for (String child : r.children()) { + parentsToChildren.put(r.parent(), r.children()); if (childrenToParents.containsKey(child)) { throw new IllegalArgumentException("[" + child + "] cannot have multiple parents"); } - childrenToParents.put(child, r.parent); + childrenToParents.put(child, r.parent()); } } } diff --git a/modules/parent-join/src/main/java/org/elasticsearch/join/mapper/ParentJoinFieldMapper.java b/modules/parent-join/src/main/java/org/elasticsearch/join/mapper/ParentJoinFieldMapper.java index a608bcfef900..3a3f3e1b5aeb 100644 --- a/modules/parent-join/src/main/java/org/elasticsearch/join/mapper/ParentJoinFieldMapper.java +++ b/modules/parent-join/src/main/java/org/elasticsearch/join/mapper/ParentJoinFieldMapper.java @@ -125,7 +125,7 @@ public final class ParentJoinFieldMapper extends FieldMapper { final Map parentIdFields = new HashMap<>(); relations.get() .stream() - .map(relation -> new ParentIdFieldMapper(name + "#" + relation.parent, eagerGlobalOrdinals.get())) + .map(relation -> new ParentIdFieldMapper(name + "#" + relation.parent(), eagerGlobalOrdinals.get())) .forEach(mapper -> parentIdFields.put(mapper.name(), mapper)); Joiner joiner = new Joiner(name(), relations.get()); return new ParentJoinFieldMapper( @@ -306,10 +306,10 @@ public final class ParentJoinFieldMapper extends FieldMapper { builder.field("eager_global_ordinals", eagerGlobalOrdinals); builder.startObject("relations"); for (Relations relation : relations) { - if (relation.children.size() == 1) { - builder.field(relation.parent, relation.children.iterator().next()); + if (relation.children().size() == 1) { + builder.field(relation.parent(), relation.children().iterator().next()); } else { - builder.field(relation.parent, relation.children); + builder.field(relation.parent(), relation.children()); } } builder.endObject(); diff --git a/modules/parent-join/src/main/java/org/elasticsearch/join/mapper/Relations.java b/modules/parent-join/src/main/java/org/elasticsearch/join/mapper/Relations.java index f77393603bd4..c9189433baf0 100644 --- a/modules/parent-join/src/main/java/org/elasticsearch/join/mapper/Relations.java +++ b/modules/parent-join/src/main/java/org/elasticsearch/join/mapper/Relations.java @@ -16,39 +16,12 @@ import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Objects; import java.util.Set; /** * Defines a relationship between a parent type and a set of child types */ -class Relations { - - final String parent; - final Set children; - - Relations(String parent, Set children) { - this.parent = parent; - this.children = children; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - Relations relation = (Relations) o; - return Objects.equals(parent, relation.parent) && Objects.equals(children, relation.children); - } - - @Override - public int hashCode() { - return Objects.hash(parent, children); - } - - @Override - public String toString() { - return parent + "->" + children; - } +record Relations(String parent, Set children) { static List parse(Object fieldNode) { List parsed = new ArrayList<>(); diff --git a/modules/rank-eval/src/main/java/org/elasticsearch/index/rankeval/EvalQueryQuality.java b/modules/rank-eval/src/main/java/org/elasticsearch/index/rankeval/EvalQueryQuality.java index a7b9832fd81c..5436aa41c285 100644 --- a/modules/rank-eval/src/main/java/org/elasticsearch/index/rankeval/EvalQueryQuality.java +++ b/modules/rank-eval/src/main/java/org/elasticsearch/index/rankeval/EvalQueryQuality.java @@ -94,8 +94,8 @@ public class EvalQueryQuality implements ToXContentFragment, Writeable { builder.startArray(UNRATED_DOCS_FIELD.getPreferredName()); for (DocumentKey key : EvaluationMetric.filterUnratedDocuments(ratedHits)) { builder.startObject(); - builder.field(RatedDocument.INDEX_FIELD.getPreferredName(), key.getIndex()); - builder.field(RatedDocument.DOC_ID_FIELD.getPreferredName(), key.getDocId()); + builder.field(RatedDocument.INDEX_FIELD.getPreferredName(), key.index()); + builder.field(RatedDocument.DOC_ID_FIELD.getPreferredName(), key.docId()); builder.endObject(); } builder.endArray(); diff --git a/modules/rank-eval/src/main/java/org/elasticsearch/index/rankeval/RatedDocument.java b/modules/rank-eval/src/main/java/org/elasticsearch/index/rankeval/RatedDocument.java index f4e0ca946c16..cf4ac5ca7014 100644 --- a/modules/rank-eval/src/main/java/org/elasticsearch/index/rankeval/RatedDocument.java +++ b/modules/rank-eval/src/main/java/org/elasticsearch/index/rankeval/RatedDocument.java @@ -70,11 +70,11 @@ public class RatedDocument implements Writeable, ToXContentObject { } public String getIndex() { - return key.getIndex(); + return key.index(); } public String getDocID() { - return key.getDocId(); + return key.docId(); } public int getRating() { @@ -83,8 +83,8 @@ public class RatedDocument implements Writeable, ToXContentObject { @Override public void writeTo(StreamOutput out) throws IOException { - out.writeString(key.getIndex()); - out.writeString(key.getDocId()); + out.writeString(key.index()); + out.writeString(key.docId()); out.writeVInt(rating); } @@ -95,8 +95,8 @@ public class RatedDocument implements Writeable, ToXContentObject { @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); - builder.field(INDEX_FIELD.getPreferredName(), key.getIndex()); - builder.field(DOC_ID_FIELD.getPreferredName(), key.getDocId()); + builder.field(INDEX_FIELD.getPreferredName(), key.index()); + builder.field(DOC_ID_FIELD.getPreferredName(), key.docId()); builder.field(RATING_FIELD.getPreferredName(), rating); builder.endObject(); return builder; @@ -127,46 +127,15 @@ public class RatedDocument implements Writeable, ToXContentObject { /** * a joint document key consisting of the documents index and id */ - static class DocumentKey { + record DocumentKey(String index, String docId) { - private final String docId; - private final String index; - - DocumentKey(String index, String docId) { + DocumentKey { if (Strings.isNullOrEmpty(index)) { throw new IllegalArgumentException("Index must be set for each rated document"); } if (Strings.isNullOrEmpty(docId)) { throw new IllegalArgumentException("DocId must be set for each rated document"); } - - this.index = index; - this.docId = docId; - } - - String getIndex() { - return index; - } - - String getDocId() { - return docId; - } - - @Override - public final boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null || getClass() != obj.getClass()) { - return false; - } - DocumentKey other = (DocumentKey) obj; - return Objects.equals(index, other.index) && Objects.equals(docId, other.docId); - } - - @Override - public final int hashCode() { - return Objects.hash(index, docId); } @Override diff --git a/modules/reindex/src/main/java/org/elasticsearch/reindex/ReindexSslConfig.java b/modules/reindex/src/main/java/org/elasticsearch/reindex/ReindexSslConfig.java index 50448f82d975..c712bd7ace49 100644 --- a/modules/reindex/src/main/java/org/elasticsearch/reindex/ReindexSslConfig.java +++ b/modules/reindex/src/main/java/org/elasticsearch/reindex/ReindexSslConfig.java @@ -147,10 +147,10 @@ public class ReindexSslConfig { * configurations if the underlying key/certificate files are modified. */ SSLIOSessionStrategy getStrategy() { - final HostnameVerifier hostnameVerifier = configuration.getVerificationMode().isHostnameVerificationEnabled() + final HostnameVerifier hostnameVerifier = configuration.verificationMode().isHostnameVerificationEnabled() ? new DefaultHostnameVerifier() : new NoopHostnameVerifier(); - final String[] protocols = configuration.getSupportedProtocols().toArray(Strings.EMPTY_ARRAY); + final String[] protocols = configuration.supportedProtocols().toArray(Strings.EMPTY_ARRAY); final String[] cipherSuites = configuration.getCipherSuites().toArray(Strings.EMPTY_ARRAY); return new SSLIOSessionStrategy(context, protocols, cipherSuites, hostnameVerifier); } diff --git a/plugins/mapper-annotated-text/src/main/java/org/elasticsearch/index/mapper/annotatedtext/AnnotatedPassageFormatter.java b/plugins/mapper-annotated-text/src/main/java/org/elasticsearch/index/mapper/annotatedtext/AnnotatedPassageFormatter.java index 04cd5aec16a1..d9d75e85842a 100644 --- a/plugins/mapper-annotated-text/src/main/java/org/elasticsearch/index/mapper/annotatedtext/AnnotatedPassageFormatter.java +++ b/plugins/mapper-annotated-text/src/main/java/org/elasticsearch/index/mapper/annotatedtext/AnnotatedPassageFormatter.java @@ -137,10 +137,10 @@ public class AnnotatedPassageFormatter extends PassageFormatter { // Now add original text's annotations - ignoring any that might conflict with the search hits markup. for (AnnotationToken token : annotations) { - int start = token.offset; - int end = token.endOffset; + int start = token.offset(); + int end = token.endOffset(); if (start >= passage.getStartOffset() && end <= passage.getEndOffset()) { - String escapedValue = URLEncoder.encode(token.value, StandardCharsets.UTF_8.name()); + String escapedValue = URLEncoder.encode(token.value(), StandardCharsets.UTF_8.name()); Markup markup = new Markup(start, end, escapedValue); markupPassage.addUnlessOverlapping(markup); } @@ -207,12 +207,12 @@ public class AnnotatedPassageFormatter extends PassageFormatter { AnnotationToken token = fieldValueAnnotations.getAnnotation(i); if (token.intersects(start - fieldValueOffset, end - fieldValueOffset)) { intersectingAnnotations.add( - new AnnotationToken(token.offset + fieldValueOffset, token.endOffset + fieldValueOffset, token.value) + new AnnotationToken(token.offset() + fieldValueOffset, token.endOffset() + fieldValueOffset, token.value()) ); } } // add 1 for the fieldvalue separator character - fieldValueOffset += fieldValueAnnotations.textMinusMarkup.length() + 1; + fieldValueOffset += fieldValueAnnotations.textMinusMarkup().length() + 1; } return intersectingAnnotations.toArray(new AnnotationToken[intersectingAnnotations.size()]); } diff --git a/plugins/mapper-annotated-text/src/main/java/org/elasticsearch/index/mapper/annotatedtext/AnnotatedTextFieldMapper.java b/plugins/mapper-annotated-text/src/main/java/org/elasticsearch/index/mapper/annotatedtext/AnnotatedTextFieldMapper.java index e77362a43bee..e2eea9d32009 100644 --- a/plugins/mapper-annotated-text/src/main/java/org/elasticsearch/index/mapper/annotatedtext/AnnotatedTextFieldMapper.java +++ b/plugins/mapper-annotated-text/src/main/java/org/elasticsearch/index/mapper/annotatedtext/AnnotatedTextFieldMapper.java @@ -42,7 +42,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; -import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -152,10 +151,7 @@ public class AnnotatedTextFieldMapper extends FieldMapper { * Parses markdown-like syntax into plain text and AnnotationTokens with offsets for * annotations found in texts */ - public static final class AnnotatedText { - public final String textPlusMarkup; - public final String textMinusMarkup; - List annotations; + public record AnnotatedText(String textMinusMarkup, String textPlusMarkup, List annotations) { // Format is markdown-like syntax for URLs eg: // "New mayor is [John Smith](type=person&value=John%20Smith) " @@ -201,23 +197,7 @@ public class AnnotatedTextFieldMapper extends FieldMapper { return new AnnotatedText(sb.toString(), textPlusMarkup, annotations); } - protected AnnotatedText(String textMinusMarkup, String textPlusMarkup, List annotations) { - this.textMinusMarkup = textMinusMarkup; - this.textPlusMarkup = textPlusMarkup; - this.annotations = annotations; - } - - public static final class AnnotationToken { - public final int offset; - public final int endOffset; - - public final String value; - - public AnnotationToken(int offset, int endOffset, String value) { - this.offset = offset; - this.endOffset = endOffset; - this.value = value; - } + public record AnnotationToken(int offset, int endOffset, String value) { @Override public String toString() { @@ -229,28 +209,6 @@ public class AnnotatedTextFieldMapper extends FieldMapper { || (start <= endOffset && end >= endOffset) || (start >= offset && end <= endOffset); } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + endOffset; - result = prime * result + offset; - result = prime * result + Objects.hashCode(value); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; - AnnotationToken other = (AnnotationToken) obj; - return Objects.equals(endOffset, other.endOffset) - && Objects.equals(offset, other.offset) - && Objects.equals(value, other.value); - } - } @Override diff --git a/plugins/mapper-annotated-text/src/main/java/org/elasticsearch/index/mapper/annotatedtext/AnnotatedTextHighlighter.java b/plugins/mapper-annotated-text/src/main/java/org/elasticsearch/index/mapper/annotatedtext/AnnotatedTextHighlighter.java index f0f3042f1e12..090df4212670 100644 --- a/plugins/mapper-annotated-text/src/main/java/org/elasticsearch/index/mapper/annotatedtext/AnnotatedTextHighlighter.java +++ b/plugins/mapper-annotated-text/src/main/java/org/elasticsearch/index/mapper/annotatedtext/AnnotatedTextHighlighter.java @@ -43,7 +43,7 @@ public class AnnotatedTextHighlighter extends UnifiedHighlighter { AnnotatedText[] annotations = new AnnotatedText[fieldValues.size()]; for (int i = 0; i < fieldValues.size(); i++) { annotations[i] = AnnotatedText.parse(fieldValues.get(i).toString()); - strings.add(annotations[i].textMinusMarkup); + strings.add(annotations[i].textMinusMarkup()); } // Store the annotations in the formatter and analyzer ((AnnotatedPassageFormatter) highlighter.getFormatter()).setAnnotations(annotations); 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 478ae9251b50..f2a1584e43bf 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 @@ -123,7 +123,7 @@ public class AnnotatedTextHighlighterTests extends ESTestCase { ArrayList plainTextForHighlighter = new ArrayList<>(annotations.length); for (int i = 0; i < annotations.length; i++) { - plainTextForHighlighter.add(annotations[i].textMinusMarkup); + plainTextForHighlighter.add(annotations[i].textMinusMarkup()); } TopDocs topDocs = searcher.search(new MatchAllDocsQuery(), 1, Sort.INDEXORDER); diff --git a/plugins/mapper-annotated-text/src/test/java/org/elasticsearch/index/mapper/annotatedtext/AnnotatedTextParsingTests.java b/plugins/mapper-annotated-text/src/test/java/org/elasticsearch/index/mapper/annotatedtext/AnnotatedTextParsingTests.java index c1a9aa950421..4b27a148acf2 100644 --- a/plugins/mapper-annotated-text/src/test/java/org/elasticsearch/index/mapper/annotatedtext/AnnotatedTextParsingTests.java +++ b/plugins/mapper-annotated-text/src/test/java/org/elasticsearch/index/mapper/annotatedtext/AnnotatedTextParsingTests.java @@ -21,8 +21,8 @@ public class AnnotatedTextParsingTests extends ESTestCase { private void checkParsing(String markup, String expectedPlainText, AnnotationToken... expectedTokens) { AnnotatedText at = AnnotatedText.parse(markup); - assertEquals(expectedPlainText, at.textMinusMarkup); - List actualAnnotations = at.annotations; + assertEquals(expectedPlainText, at.textMinusMarkup()); + List actualAnnotations = at.annotations(); assertEquals(expectedTokens.length, actualAnnotations.size()); for (int i = 0; i < expectedTokens.length; i++) { assertEquals(expectedTokens[i], actualAnnotations.get(i)); diff --git a/qa/ccs-rolling-upgrade-remote-cluster/src/test/java/org/elasticsearch/upgrades/SearchStatesIT.java b/qa/ccs-rolling-upgrade-remote-cluster/src/test/java/org/elasticsearch/upgrades/SearchStatesIT.java index c0fd43a2b539..c1db9d77f61d 100644 --- a/qa/ccs-rolling-upgrade-remote-cluster/src/test/java/org/elasticsearch/upgrades/SearchStatesIT.java +++ b/qa/ccs-rolling-upgrade-remote-cluster/src/test/java/org/elasticsearch/upgrades/SearchStatesIT.java @@ -75,45 +75,7 @@ public class SearchStatesIT extends ESRestTestCase { private static final Version UPGRADE_FROM_VERSION = Version.fromString(System.getProperty("tests.upgrade_from_version")); private static final String CLUSTER_ALIAS = "remote_cluster"; - static class Node { - final String id; - final String name; - final Version version; - final String transportAddress; - final String httpAddress; - final Map attributes; - - Node(String id, String name, Version version, String transportAddress, String httpAddress, Map attributes) { - this.id = id; - this.name = name; - this.version = version; - this.transportAddress = transportAddress; - this.httpAddress = httpAddress; - this.attributes = attributes; - } - - @Override - public String toString() { - return "Node{" - + "id='" - + id - + '\'' - + ", name='" - + name - + '\'' - + ", version=" - + version - + ", transportAddress='" - + transportAddress - + '\'' - + ", httpAddress='" - + httpAddress - + '\'' - + ", attributes=" - + attributes - + '}'; - } - } + record Node(String id, String name, Version version, String transportAddress, String httpAddress, Map attributes) {} static List getNodes(RestClient restClient) throws IOException { Response response = restClient.performRequest(new Request("GET", "_nodes")); diff --git a/qa/mixed-cluster/src/test/java/org/elasticsearch/backwards/HotThreadsIT.java b/qa/mixed-cluster/src/test/java/org/elasticsearch/backwards/HotThreadsIT.java index b2db1953240e..9c931e15eeee 100644 --- a/qa/mixed-cluster/src/test/java/org/elasticsearch/backwards/HotThreadsIT.java +++ b/qa/mixed-cluster/src/test/java/org/elasticsearch/backwards/HotThreadsIT.java @@ -23,7 +23,7 @@ public class HotThreadsIT extends ESRestTestCase { assumeFalse("no bwc node found", nodes.getBWCNodes().isEmpty()); assumeTrue( "new nodes are higher version than BWC nodes", - nodes.getNewNodes().get(0).getVersion().compareTo(nodes.getBWCNodes().get(0).getVersion()) > 0 + nodes.getNewNodes().get(0).version().compareTo(nodes.getBWCNodes().get(0).version()) > 0 ); final Request request = new Request("GET", "/_nodes/hot_threads"); final Response response = client().performRequest(request); diff --git a/qa/mixed-cluster/src/test/java/org/elasticsearch/backwards/IndexingIT.java b/qa/mixed-cluster/src/test/java/org/elasticsearch/backwards/IndexingIT.java index 0314b65773ef..9793809e1b6f 100644 --- a/qa/mixed-cluster/src/test/java/org/elasticsearch/backwards/IndexingIT.java +++ b/qa/mixed-cluster/src/test/java/org/elasticsearch/backwards/IndexingIT.java @@ -79,7 +79,7 @@ public class IndexingIT extends ESRestTestCase { Nodes nodes = buildNodeAndVersions(); assumeFalse("new nodes is empty", nodes.getNewNodes().isEmpty()); logger.info("cluster discovered: {}", nodes.toString()); - final List bwcNamesList = nodes.getBWCNodes().stream().map(Node::getNodeName).collect(Collectors.toList()); + final List bwcNamesList = nodes.getBWCNodes().stream().map(Node::nodeName).collect(Collectors.toList()); final String bwcNames = bwcNamesList.stream().collect(Collectors.joining(",")); Settings.Builder settings = Settings.builder() .put(IndexMetadata.INDEX_NUMBER_OF_SHARDS_SETTING.getKey(), 1) @@ -92,7 +92,7 @@ public class IndexingIT extends ESRestTestCase { try ( RestClient newNodeClient = buildClient( restClientSettings(), - nodes.getNewNodes().stream().map(Node::getPublishAddress).toArray(HttpHost[]::new) + nodes.getNewNodes().stream().map(Node::publishAddress).toArray(HttpHost[]::new) ) ) { @@ -104,11 +104,11 @@ public class IndexingIT extends ESRestTestCase { ensureGreen(index); assertOK(client().performRequest(new Request("POST", index + "/_refresh"))); List shards = buildShards(index, nodes, newNodeClient); - Shard primary = buildShards(index, nodes, newNodeClient).stream().filter(Shard::isPrimary).findFirst().get(); - logger.info("primary resolved to: " + primary.getNode().getNodeName()); + Shard primary = buildShards(index, nodes, newNodeClient).stream().filter(Shard::primary).findFirst().get(); + logger.info("primary resolved to: " + primary.node().nodeName()); for (Shard shard : shards) { - assertVersion(index, 1, "_only_nodes:" + shard.getNode().getNodeName(), finalVersionForDoc1); - assertCount(index, "_only_nodes:" + shard.getNode().getNodeName(), 1); + assertVersion(index, 1, "_only_nodes:" + shard.node().nodeName(), finalVersionForDoc1); + assertCount(index, "_only_nodes:" + shard.node().nodeName(), 1); } nUpdates = randomIntBetween(minUpdates, maxUpdates); @@ -116,16 +116,16 @@ public class IndexingIT extends ESRestTestCase { final int finalVersionForDoc2 = indexDocWithConcurrentUpdates(index, 2, nUpdates); assertOK(client().performRequest(new Request("POST", index + "/_refresh"))); shards = buildShards(index, nodes, newNodeClient); - primary = shards.stream().filter(Shard::isPrimary).findFirst().get(); - logger.info("primary resolved to: " + primary.getNode().getNodeName()); + primary = shards.stream().filter(Shard::primary).findFirst().get(); + logger.info("primary resolved to: " + primary.node().nodeName()); for (Shard shard : shards) { - assertVersion(index, 2, "_only_nodes:" + shard.getNode().getNodeName(), finalVersionForDoc2); - assertCount(index, "_only_nodes:" + shard.getNode().getNodeName(), 2); + assertVersion(index, 2, "_only_nodes:" + shard.node().nodeName(), finalVersionForDoc2); + assertCount(index, "_only_nodes:" + shard.node().nodeName(), 2); } - primary = shards.stream().filter(Shard::isPrimary).findFirst().get(); - logger.info("moving primary to new node by excluding {}", primary.getNode().getNodeName()); - updateIndexSettings(index, Settings.builder().put("index.routing.allocation.exclude._name", primary.getNode().getNodeName())); + primary = shards.stream().filter(Shard::primary).findFirst().get(); + logger.info("moving primary to new node by excluding {}", primary.node().nodeName()); + updateIndexSettings(index, Settings.builder().put("index.routing.allocation.exclude._name", primary.node().nodeName())); ensureGreen(index); nUpdates = randomIntBetween(minUpdates, maxUpdates); logger.info("indexing docs with [{}] concurrent updates after moving primary", nUpdates); @@ -133,8 +133,8 @@ public class IndexingIT extends ESRestTestCase { assertOK(client().performRequest(new Request("POST", index + "/_refresh"))); shards = buildShards(index, nodes, newNodeClient); for (Shard shard : shards) { - assertVersion(index, 3, "_only_nodes:" + shard.getNode().getNodeName(), finalVersionForDoc3); - assertCount(index, "_only_nodes:" + shard.getNode().getNodeName(), 3); + assertVersion(index, 3, "_only_nodes:" + shard.node().nodeName(), finalVersionForDoc3); + assertCount(index, "_only_nodes:" + shard.node().nodeName(), 3); } logger.info("setting number of replicas to 0"); @@ -146,8 +146,8 @@ public class IndexingIT extends ESRestTestCase { assertOK(client().performRequest(new Request("POST", index + "/_refresh"))); shards = buildShards(index, nodes, newNodeClient); for (Shard shard : shards) { - assertVersion(index, 4, "_only_nodes:" + shard.getNode().getNodeName(), finalVersionForDoc4); - assertCount(index, "_only_nodes:" + shard.getNode().getNodeName(), 4); + assertVersion(index, 4, "_only_nodes:" + shard.node().nodeName(), finalVersionForDoc4); + assertCount(index, "_only_nodes:" + shard.node().nodeName(), 4); } logger.info("setting number of replicas to 1"); @@ -159,8 +159,8 @@ public class IndexingIT extends ESRestTestCase { assertOK(client().performRequest(new Request("POST", index + "/_refresh"))); shards = buildShards(index, nodes, newNodeClient); for (Shard shard : shards) { - assertVersion(index, 5, "_only_nodes:" + shard.getNode().getNodeName(), finalVersionForDoc5); - assertCount(index, "_only_nodes:" + shard.getNode().getNodeName(), 5); + assertVersion(index, 5, "_only_nodes:" + shard.node().nodeName(), finalVersionForDoc5); + assertCount(index, "_only_nodes:" + shard.node().nodeName(), 5); } } } @@ -169,7 +169,7 @@ public class IndexingIT extends ESRestTestCase { Nodes nodes = buildNodeAndVersions(); assumeFalse("new nodes is empty", nodes.getNewNodes().isEmpty()); logger.info("cluster discovered: {}", nodes.toString()); - final List bwcNamesList = nodes.getBWCNodes().stream().map(Node::getNodeName).collect(Collectors.toList()); + final List bwcNamesList = nodes.getBWCNodes().stream().map(Node::nodeName).collect(Collectors.toList()); final String bwcNames = bwcNamesList.stream().collect(Collectors.joining(",")); Settings.Builder settings = Settings.builder() .put(IndexMetadata.INDEX_NUMBER_OF_SHARDS_SETTING.getKey(), 1) @@ -181,7 +181,7 @@ public class IndexingIT extends ESRestTestCase { try ( RestClient newNodeClient = buildClient( restClientSettings(), - nodes.getNewNodes().stream().map(Node::getPublishAddress).toArray(HttpHost[]::new) + nodes.getNewNodes().stream().map(Node::publishAddress).toArray(HttpHost[]::new) ) ) { int numDocs = 0; @@ -200,9 +200,9 @@ public class IndexingIT extends ESRestTestCase { logger.info("indexing [{}] docs after allowing shards on all nodes", numberOfDocsAfterAllowingShardsOnAllNodes); numDocs += indexDocs(index, numDocs, numberOfDocsAfterAllowingShardsOnAllNodes); assertSeqNoOnShards(index, nodes, nodes.getBWCVersion().major >= 6 ? numDocs : 0, newNodeClient); - Shard primary = buildShards(index, nodes, newNodeClient).stream().filter(Shard::isPrimary).findFirst().get(); - logger.info("moving primary to new node by excluding {}", primary.getNode().getNodeName()); - updateIndexSettings(index, Settings.builder().put("index.routing.allocation.exclude._name", primary.getNode().getNodeName())); + Shard primary = buildShards(index, nodes, newNodeClient).stream().filter(Shard::primary).findFirst().get(); + logger.info("moving primary to new node by excluding {}", primary.node().nodeName()); + updateIndexSettings(index, Settings.builder().put("index.routing.allocation.exclude._name", primary.node().nodeName())); ensureGreen(index); int numDocsOnNewPrimary = 0; final int numberOfDocsAfterMovingPrimary = 1 + randomInt(5); @@ -254,7 +254,7 @@ public class IndexingIT extends ESRestTestCase { assertOK(client().performRequest(request)); - String bwcNames = nodes.getBWCNodes().stream().map(Node::getNodeName).collect(Collectors.joining(",")); + String bwcNames = nodes.getBWCNodes().stream().map(Node::nodeName).collect(Collectors.joining(",")); // Allocating shards on the BWC nodes to makes sure that taking snapshot happens on those nodes. Settings.Builder settings = Settings.builder() @@ -289,7 +289,7 @@ public class IndexingIT extends ESRestTestCase { assumeFalse("no new node found", nodes.getNewNodes().isEmpty()); assumeFalse("no bwc node found", nodes.getBWCNodes().isEmpty()); // Allocate shards to new nodes then verify synced flush requests processed by old nodes/new nodes - String newNodes = nodes.getNewNodes().stream().map(Node::getNodeName).collect(Collectors.joining(",")); + String newNodes = nodes.getNewNodes().stream().map(Node::nodeName).collect(Collectors.joining(",")); int numShards = randomIntBetween(1, 10); int numOfReplicas = randomIntBetween(0, nodes.getNewNodes().size() - 1); int totalShards = numShards * (numOfReplicas + 1); @@ -307,7 +307,7 @@ public class IndexingIT extends ESRestTestCase { try ( RestClient oldNodeClient = buildClient( restClientSettings(), - nodes.getBWCNodes().stream().map(Node::getPublishAddress).toArray(HttpHost[]::new) + nodes.getBWCNodes().stream().map(Node::publishAddress).toArray(HttpHost[]::new) ) ) { Request request = new Request("POST", index + "/_flush/synced"); @@ -335,7 +335,7 @@ public class IndexingIT extends ESRestTestCase { try ( RestClient newNodeClient = buildClient( restClientSettings(), - nodes.getNewNodes().stream().map(Node::getPublishAddress).toArray(HttpHost[]::new) + nodes.getNewNodes().stream().map(Node::publishAddress).toArray(HttpHost[]::new) ) ) { Request request = new Request("POST", index + "/_flush/synced"); @@ -368,7 +368,7 @@ public class IndexingIT extends ESRestTestCase { assumeFalse("no new node found", nodes.getNewNodes().isEmpty()); assumeFalse("no bwc node found", nodes.getBWCNodes().isEmpty()); // Allocate shards to new nodes then verify flush requests processed by old nodes/new nodes - String newNodes = nodes.getNewNodes().stream().map(Node::getNodeName).collect(Collectors.joining(",")); + String newNodes = nodes.getNewNodes().stream().map(Node::nodeName).collect(Collectors.joining(",")); int numShards = randomIntBetween(1, 10); int numOfReplicas = randomIntBetween(0, nodes.getNewNodes().size() - 1); int totalShards = numShards * (numOfReplicas + 1); @@ -386,7 +386,7 @@ public class IndexingIT extends ESRestTestCase { try ( RestClient oldNodeClient = buildClient( restClientSettings(), - nodes.getBWCNodes().stream().map(Node::getPublishAddress).toArray(HttpHost[]::new) + nodes.getBWCNodes().stream().map(Node::publishAddress).toArray(HttpHost[]::new) ) ) { Request request = new Request("POST", index + "/_flush"); @@ -403,7 +403,7 @@ public class IndexingIT extends ESRestTestCase { try ( RestClient newNodeClient = buildClient( restClientSettings(), - nodes.getNewNodes().stream().map(Node::getPublishAddress).toArray(HttpHost[]::new) + nodes.getNewNodes().stream().map(Node::publishAddress).toArray(HttpHost[]::new) ) ) { Request request = new Request("POST", index + "/_flush"); @@ -441,22 +441,22 @@ public class IndexingIT extends ESRestTestCase { assertBusy(() -> { try { List shards = buildShards(index, nodes, client); - Shard primaryShard = shards.stream().filter(Shard::isPrimary).findFirst().get(); + Shard primaryShard = shards.stream().filter(Shard::primary).findFirst().get(); assertNotNull("failed to find primary shard", primaryShard); final long expectedGlobalCkp = numDocs - 1; final long expectMaxSeqNo = numDocs - 1; - logger.info("primary resolved to node {}", primaryShard.getNode()); + logger.info("primary resolved to node {}", primaryShard.node()); for (Shard shard : shards) { - final SeqNoStats seqNoStats = shard.getSeqNoStats(); - logger.info("stats for {}, primary [{}]: [{}]", shard.getNode(), shard.isPrimary(), seqNoStats); - assertThat("max_seq no on " + shard.getNode() + " is wrong", seqNoStats.getMaxSeqNo(), equalTo(expectMaxSeqNo)); + final SeqNoStats seqNoStats = shard.seqNoStats(); + logger.info("stats for {}, primary [{}]: [{}]", shard.node(), shard.primary(), seqNoStats); + assertThat("max_seq no on " + shard.node() + " is wrong", seqNoStats.getMaxSeqNo(), equalTo(expectMaxSeqNo)); assertThat( - "localCheckpoint no on " + shard.getNode() + " is wrong", + "localCheckpoint no on " + shard.node() + " is wrong", seqNoStats.getLocalCheckpoint(), equalTo(expectMaxSeqNo) ); assertThat( - "globalCheckpoint no on " + shard.getNode() + " is wrong", + "globalCheckpoint no on " + shard.node() + " is wrong", seqNoStats.getGlobalCheckpoint(), equalTo(expectedGlobalCkp) ); @@ -528,24 +528,24 @@ public class IndexingIT extends ESRestTestCase { } public void add(Node node) { - put(node.getId(), node); + put(node.id(), node); } public List getNewNodes() { Version bwcVersion = getBWCVersion(); - return values().stream().filter(n -> n.getVersion().after(bwcVersion)).collect(Collectors.toList()); + return values().stream().filter(n -> n.version().after(bwcVersion)).collect(Collectors.toList()); } public List getBWCNodes() { Version bwcVersion = getBWCVersion(); - return values().stream().filter(n -> n.getVersion().equals(bwcVersion)).collect(Collectors.toList()); + return values().stream().filter(n -> n.version().equals(bwcVersion)).collect(Collectors.toList()); } public Version getBWCVersion() { if (isEmpty()) { throw new IllegalStateException("no nodes available"); } - return Version.fromId(values().stream().map(node -> node.getVersion().id).min(Integer::compareTo).get()); + return Version.fromId(values().stream().map(node -> node.version().id).min(Integer::compareTo).get()); } public Node getSafe(String id) { @@ -567,67 +567,7 @@ public class IndexingIT extends ESRestTestCase { } } - static final class Node { - private final String id; - private final String nodeName; - private final Version version; - private final HttpHost publishAddress; + record Node(String id, String nodeName, Version version, HttpHost publishAddress) {} - Node(String id, String nodeName, Version version, HttpHost publishAddress) { - this.id = id; - this.nodeName = nodeName; - this.version = version; - this.publishAddress = publishAddress; - } - - public String getId() { - return id; - } - - public String getNodeName() { - return nodeName; - } - - public HttpHost getPublishAddress() { - return publishAddress; - } - - public Version getVersion() { - return version; - } - - @Override - public String toString() { - return "Node{" + "id='" + id + '\'' + ", nodeName='" + nodeName + '\'' + ", version=" + version + '}'; - } - } - - final class Shard { - private final Node node; - private final boolean Primary; - private final SeqNoStats seqNoStats; - - Shard(Node node, boolean primary, SeqNoStats seqNoStats) { - this.node = node; - Primary = primary; - this.seqNoStats = seqNoStats; - } - - public Node getNode() { - return node; - } - - public boolean isPrimary() { - return Primary; - } - - public SeqNoStats getSeqNoStats() { - return seqNoStats; - } - - @Override - public String toString() { - return "Shard{" + "node=" + node + ", Primary=" + Primary + ", seqNoStats=" + seqNoStats + '}'; - } - } + record Shard(Node node, boolean primary, SeqNoStats seqNoStats) {} } diff --git a/qa/mixed-cluster/src/test/java/org/elasticsearch/backwards/SearchWithMinCompatibleSearchNodeIT.java b/qa/mixed-cluster/src/test/java/org/elasticsearch/backwards/SearchWithMinCompatibleSearchNodeIT.java index 10e991c37feb..ef2686409f23 100644 --- a/qa/mixed-cluster/src/test/java/org/elasticsearch/backwards/SearchWithMinCompatibleSearchNodeIT.java +++ b/qa/mixed-cluster/src/test/java/org/elasticsearch/backwards/SearchWithMinCompatibleSearchNodeIT.java @@ -50,8 +50,8 @@ public class SearchWithMinCompatibleSearchNodeIT extends ESRestTestCase { allNodes = new ArrayList<>(); allNodes.addAll(nodes.getBWCNodes()); allNodes.addAll(nodes.getNewNodes()); - bwcVersion = nodes.getBWCNodes().get(0).getVersion(); - newVersion = nodes.getNewNodes().get(0).getVersion(); + bwcVersion = nodes.getBWCNodes().get(0).version(); + newVersion = nodes.getNewNodes().get(0).version(); if (client().performRequest(new Request("HEAD", "/" + index)).getStatusLine().getStatusCode() == 404) { createIndex( @@ -71,9 +71,7 @@ public class SearchWithMinCompatibleSearchNodeIT extends ESRestTestCase { } public void testMinVersionAsNewVersion() throws Exception { - try ( - RestClient client = buildClient(restClientSettings(), allNodes.stream().map(Node::getPublishAddress).toArray(HttpHost[]::new)) - ) { + try (RestClient client = buildClient(restClientSettings(), allNodes.stream().map(Node::publishAddress).toArray(HttpHost[]::new))) { Request newVersionRequest = new Request( "POST", index + "/_search?min_compatible_shard_node=" + newVersion + "&ccs_minimize_roundtrips=false" @@ -94,9 +92,7 @@ public class SearchWithMinCompatibleSearchNodeIT extends ESRestTestCase { } public void testMinVersionAsOldVersion() throws Exception { - try ( - RestClient client = buildClient(restClientSettings(), allNodes.stream().map(Node::getPublishAddress).toArray(HttpHost[]::new)) - ) { + try (RestClient client = buildClient(restClientSettings(), allNodes.stream().map(Node::publishAddress).toArray(HttpHost[]::new))) { Request oldVersionRequest = new Request( "POST", index + "/_search?min_compatible_shard_node=" + bwcVersion + "&ccs_minimize_roundtrips=false" @@ -120,9 +116,7 @@ public class SearchWithMinCompatibleSearchNodeIT extends ESRestTestCase { } public void testCcsMinimizeRoundtripsIsFalse() throws Exception { - try ( - RestClient client = buildClient(restClientSettings(), allNodes.stream().map(Node::getPublishAddress).toArray(HttpHost[]::new)) - ) { + try (RestClient client = buildClient(restClientSettings(), allNodes.stream().map(Node::publishAddress).toArray(HttpHost[]::new))) { Version version = randomBoolean() ? newVersion : bwcVersion; Request request = new Request( diff --git a/qa/os/src/test/java/org/elasticsearch/packaging/test/ArchiveGenerateInitialCredentialsTests.java b/qa/os/src/test/java/org/elasticsearch/packaging/test/ArchiveGenerateInitialCredentialsTests.java index c0fb26463471..5713f3670bbe 100644 --- a/qa/os/src/test/java/org/elasticsearch/packaging/test/ArchiveGenerateInitialCredentialsTests.java +++ b/qa/os/src/test/java/org/elasticsearch/packaging/test/ArchiveGenerateInitialCredentialsTests.java @@ -55,9 +55,9 @@ public class ArchiveGenerateInitialCredentialsTests extends PackagingTestCase { assumeTrue("expect command isn't on Windows", distribution.platform != Distribution.Platform.WINDOWS); ServerUtils.disableSecurityAutoConfiguration(installation); Shell.Result result = awaitElasticsearchStartupWithResult(runElasticsearchStartCommand(null, false, true)); - assertThat(parseElasticPassword(result.stdout), nullValue()); - assertThat(parseKibanaToken(result.stdout), nullValue()); - assertThat(parseFingerprint(result.stdout), nullValue()); + assertThat(parseElasticPassword(result.stdout()), nullValue()); + assertThat(parseKibanaToken(result.stdout()), nullValue()); + assertThat(parseFingerprint(result.stdout()), nullValue()); stopElasticsearch(); } @@ -79,10 +79,10 @@ public class ArchiveGenerateInitialCredentialsTests extends PackagingTestCase { stopElasticsearch(); ServerUtils.enableSecurityAutoConfiguration(installation); Shell.Result result = awaitElasticsearchStartupWithResult(runElasticsearchStartCommand(null, false, true)); - assertThat(parseElasticPassword(result.stdout), notNullValue()); - assertThat(parseKibanaToken(result.stdout), notNullValue()); - assertThat(parseFingerprint(result.stdout), notNullValue()); - String response = makeRequestAsElastic("https://localhost:9200", parseElasticPassword(result.stdout)); + assertThat(parseElasticPassword(result.stdout()), notNullValue()); + assertThat(parseKibanaToken(result.stdout()), notNullValue()); + assertThat(parseFingerprint(result.stdout()), notNullValue()); + String response = makeRequestAsElastic("https://localhost:9200", parseElasticPassword(result.stdout())); assertThat(response, containsString("You Know, for Search")); } @@ -92,9 +92,9 @@ public class ArchiveGenerateInitialCredentialsTests extends PackagingTestCase { assumeTrue("expect command isn't on Windows", distribution.platform != Distribution.Platform.WINDOWS); stopElasticsearch(); Shell.Result result = awaitElasticsearchStartupWithResult(runElasticsearchStartCommand(null, false, true)); - assertThat(parseElasticPassword(result.stdout), nullValue()); - assertThat(parseKibanaToken(result.stdout), nullValue()); - assertThat(parseFingerprint(result.stdout), nullValue()); + assertThat(parseElasticPassword(result.stdout()), nullValue()); + assertThat(parseKibanaToken(result.stdout()), nullValue()); + assertThat(parseFingerprint(result.stdout()), nullValue()); } private String parseElasticPassword(String output) { diff --git a/qa/os/src/test/java/org/elasticsearch/packaging/test/ArchiveTests.java b/qa/os/src/test/java/org/elasticsearch/packaging/test/ArchiveTests.java index 096f49edd6f4..2270ceeeb5fb 100644 --- a/qa/os/src/test/java/org/elasticsearch/packaging/test/ArchiveTests.java +++ b/qa/os/src/test/java/org/elasticsearch/packaging/test/ArchiveTests.java @@ -80,7 +80,7 @@ public class ArchiveTests extends PackagingTestCase { final Installation.Executables bin = installation.executables(); final Result r = bin.pluginTool.run("list"); - assertThat(r.stdout, emptyString()); + assertThat(r.stdout(), emptyString()); } public void test30MissingBundledJdk() throws Exception { @@ -95,8 +95,8 @@ public class ArchiveTests extends PackagingTestCase { } // ask for elasticsearch version to quickly exit if java is actually found (ie test failure) final Result runResult = sh.runIgnoreExitCode(bin.elasticsearch.toString() + " -V"); - assertThat(runResult.exitCode, is(1)); - assertThat(runResult.stderr, containsString("could not find java in bundled JDK")); + assertThat(runResult.exitCode(), is(1)); + assertThat(runResult.stderr(), containsString("could not find java in bundled JDK")); } finally { if (distribution().hasJdk) { mv(relocatedJdk, installation.bundledJdk); @@ -110,8 +110,8 @@ public class ArchiveTests extends PackagingTestCase { // ask for elasticsearch version to quickly exit if java is actually found (ie test failure) final Result runResult = sh.runIgnoreExitCode(bin.elasticsearch.toString() + " -V"); - assertThat(runResult.exitCode, is(1)); - assertThat(runResult.stderr, containsString("could not find java in ES_JAVA_HOME")); + assertThat(runResult.exitCode(), is(1)); + assertThat(runResult.stderr(), containsString("could not find java in ES_JAVA_HOME")); } public void test32SpecialCharactersInJdkPath() throws Exception { @@ -125,7 +125,7 @@ public class ArchiveTests extends PackagingTestCase { mv(installation.bundledJdk, relocatedJdk); // ask for elasticsearch version to avoid starting the app final Result runResult = sh.run(bin.elasticsearch.toString() + " -V"); - assertThat(runResult.stdout, startsWith("Version: ")); + assertThat(runResult.stdout(), startsWith("Version: ")); } finally { mv(relocatedJdk, installation.bundledJdk); } @@ -300,11 +300,11 @@ public class ArchiveTests extends PackagingTestCase { public void test61EsJavaHomeOverride() throws Exception { Platforms.onLinux(() -> { - String systemJavaHome1 = sh.run("echo $SYSTEM_JAVA_HOME").stdout.trim(); + String systemJavaHome1 = sh.run("echo $SYSTEM_JAVA_HOME").stdout().trim(); sh.getEnv().put("ES_JAVA_HOME", systemJavaHome1); }); Platforms.onWindows(() -> { - final String systemJavaHome1 = sh.run("$Env:SYSTEM_JAVA_HOME").stdout.trim(); + final String systemJavaHome1 = sh.run("$Env:SYSTEM_JAVA_HOME").stdout().trim(); sh.getEnv().put("ES_JAVA_HOME", systemJavaHome1); }); @@ -319,13 +319,13 @@ public class ArchiveTests extends PackagingTestCase { public void test62JavaHomeIgnored() throws Exception { assumeTrue(distribution().hasJdk); Platforms.onLinux(() -> { - String systemJavaHome1 = sh.run("echo $SYSTEM_JAVA_HOME").stdout.trim(); + String systemJavaHome1 = sh.run("echo $SYSTEM_JAVA_HOME").stdout().trim(); sh.getEnv().put("JAVA_HOME", systemJavaHome1); // ensure that ES_JAVA_HOME is not set for the test sh.getEnv().remove("ES_JAVA_HOME"); }); Platforms.onWindows(() -> { - final String systemJavaHome1 = sh.run("$Env:SYSTEM_JAVA_HOME").stdout.trim(); + final String systemJavaHome1 = sh.run("$Env:SYSTEM_JAVA_HOME").stdout().trim(); sh.getEnv().put("JAVA_HOME", systemJavaHome1); // ensure that ES_JAVA_HOME is not set for the test sh.getEnv().remove("ES_JAVA_HOME"); @@ -333,7 +333,7 @@ public class ArchiveTests extends PackagingTestCase { final Installation.Executables bin = installation.executables(); final Result runResult = sh.run(bin.elasticsearch.toString() + " -V"); - assertThat(runResult.stderr, containsString("warning: ignoring JAVA_HOME=" + systemJavaHome + "; using bundled JDK")); + assertThat(runResult.stderr(), containsString("warning: ignoring JAVA_HOME=" + systemJavaHome + "; using bundled JDK")); startElasticsearch(); runElasticsearchTests(); @@ -351,11 +351,11 @@ public class ArchiveTests extends PackagingTestCase { try { mv(installation.bundledJdk, relocatedJdk); Platforms.onLinux(() -> { - String systemJavaHome1 = sh.run("echo $SYSTEM_JAVA_HOME").stdout.trim(); + String systemJavaHome1 = sh.run("echo $SYSTEM_JAVA_HOME").stdout().trim(); sh.getEnv().put("ES_JAVA_HOME", systemJavaHome1); }); Platforms.onWindows(() -> { - final String systemJavaHome1 = sh.run("$Env:SYSTEM_JAVA_HOME").stdout.trim(); + final String systemJavaHome1 = sh.run("$Env:SYSTEM_JAVA_HOME").stdout().trim(); sh.getEnv().put("ES_JAVA_HOME", systemJavaHome1); }); @@ -386,7 +386,7 @@ public class ArchiveTests extends PackagingTestCase { String pluginListCommand = installation.bin + "/elasticsearch-plugin list"; Result result = sh.run(pluginListCommand); - assertThat(result.exitCode, equalTo(0)); + assertThat(result.exitCode(), equalTo(0)); } finally { // clean up sym link @@ -400,7 +400,7 @@ public class ArchiveTests extends PackagingTestCase { // Create temporary directory with a space and link to real java home String testJavaHome = Paths.get("/tmp", "java home").toString(); try { - final String systemJavaHome = sh.run("echo $SYSTEM_JAVA_HOME").stdout.trim(); + final String systemJavaHome = sh.run("echo $SYSTEM_JAVA_HOME").stdout().trim(); sh.run("ln -s \"" + systemJavaHome + "\" \"" + testJavaHome + "\""); sh.getEnv().put("ES_JAVA_HOME", testJavaHome); @@ -411,7 +411,7 @@ public class ArchiveTests extends PackagingTestCase { String pluginListCommand = installation.bin + "/elasticsearch-plugin list"; Result result = sh.run(pluginListCommand); - assertThat(result.exitCode, equalTo(0)); + assertThat(result.exitCode(), equalTo(0)); } finally { FileUtils.rm(Paths.get(testJavaHome)); } @@ -557,12 +557,12 @@ public class ArchiveTests extends PackagingTestCase { assertThat(installation.lib.resolve("tools").resolve("security-cli"), fileExists()); final Platforms.PlatformAction action = () -> { Result result = sh.run(bin.certutilTool + " --help"); - assertThat(result.stdout, containsString("Simplifies certificate creation for use with the Elastic Stack")); + assertThat(result.stdout(), containsString("Simplifies certificate creation for use with the Elastic Stack")); // Ensure that the exit code from the java command is passed back up through the shell script result = sh.runIgnoreExitCode(bin.certutilTool + " invalid-command"); - assertThat(result.exitCode, is(not(0))); - assertThat(result.stderr, containsString("Unknown command [invalid-command]")); + assertThat(result.exitCode(), is(not(0))); + assertThat(result.stderr(), containsString("Unknown command [invalid-command]")); }; Platforms.onLinux(action); Platforms.onWindows(action); @@ -573,7 +573,7 @@ public class ArchiveTests extends PackagingTestCase { Platforms.PlatformAction action = () -> { final Result result = sh.run(bin.shardTool + " -h"); - assertThat(result.stdout, containsString("A CLI tool to remove corrupted parts of unrecoverable shards")); + assertThat(result.stdout(), containsString("A CLI tool to remove corrupted parts of unrecoverable shards")); }; Platforms.onLinux(action); @@ -585,7 +585,7 @@ public class ArchiveTests extends PackagingTestCase { Platforms.PlatformAction action = () -> { final Result result = sh.run(bin.nodeTool + " -h"); - assertThat(result.stdout, containsString("A CLI tool to do unsafe cluster and index manipulations on current node")); + assertThat(result.stdout(), containsString("A CLI tool to do unsafe cluster and index manipulations on current node")); }; Platforms.onLinux(action); @@ -606,7 +606,7 @@ public class ArchiveTests extends PackagingTestCase { } Result result = sh.run("echo y | " + nodeTool + " unsafe-bootstrap"); - assertThat(result.stdout, containsString("Master node was successfully bootstrapped")); + assertThat(result.stdout(), containsString("Master node was successfully bootstrapped")); } public void test94ElasticsearchNodeExecuteCliNotEsHomeWorkDir() throws Exception { @@ -616,15 +616,15 @@ public class ArchiveTests extends PackagingTestCase { Platforms.PlatformAction action = () -> { Result result = sh.run(bin.certutilTool + " -h"); - assertThat(result.stdout, containsString("Simplifies certificate creation for use with the Elastic Stack")); + assertThat(result.stdout(), containsString("Simplifies certificate creation for use with the Elastic Stack")); result = sh.run(bin.syskeygenTool + " -h"); - assertThat(result.stdout, containsString("system key tool")); + assertThat(result.stdout(), containsString("system key tool")); result = sh.run(bin.setupPasswordsTool + " -h"); - assertThat(result.stdout, containsString("Sets the passwords for reserved users")); + assertThat(result.stdout(), containsString("Sets the passwords for reserved users")); result = sh.run(bin.usersTool + " -h"); - assertThat(result.stdout, containsString("Manages elasticsearch file users")); + assertThat(result.stdout(), containsString("Manages elasticsearch file users")); result = sh.run(bin.serviceTokensTool + " -h"); - assertThat(result.stdout, containsString("Manages elasticsearch service account file-tokens")); + assertThat(result.stdout(), containsString("Manages elasticsearch service account file-tokens")); }; Platforms.onLinux(action); diff --git a/qa/os/src/test/java/org/elasticsearch/packaging/test/CertGenCliTests.java b/qa/os/src/test/java/org/elasticsearch/packaging/test/CertGenCliTests.java index 7281c15f75d0..03b820de5866 100644 --- a/qa/os/src/test/java/org/elasticsearch/packaging/test/CertGenCliTests.java +++ b/qa/os/src/test/java/org/elasticsearch/packaging/test/CertGenCliTests.java @@ -55,7 +55,7 @@ public class CertGenCliTests extends PackagingTestCase { public void test20Help() { Shell.Result result = installation.executables().certgenTool.run("--help"); - assertThat(result.stdout, containsString("Simplifies certificate creation")); + assertThat(result.stdout(), containsString("Simplifies certificate creation")); } public void test30Generate() throws Exception { @@ -134,7 +134,7 @@ public class CertGenCliTests extends PackagingTestCase { private String setElasticPassword() { Shell.Result result = installation.executables().resetPasswordTool.run("--auto --batch --silent --username elastic", null); - return result.stdout; + return result.stdout(); } } diff --git a/qa/os/src/test/java/org/elasticsearch/packaging/test/CronEvalCliTests.java b/qa/os/src/test/java/org/elasticsearch/packaging/test/CronEvalCliTests.java index 38221bc0c1f6..3f5090d42dcb 100644 --- a/qa/os/src/test/java/org/elasticsearch/packaging/test/CronEvalCliTests.java +++ b/qa/os/src/test/java/org/elasticsearch/packaging/test/CronEvalCliTests.java @@ -27,11 +27,11 @@ public class CronEvalCliTests extends PackagingTestCase { public void test20Help() throws Exception { Shell.Result result = installation.executables().cronevalTool.run("--help"); - assertThat(result.stdout, containsString("Validates and evaluates a cron expression")); + assertThat(result.stdout(), containsString("Validates and evaluates a cron expression")); } public void test30Run() throws Exception { Shell.Result result = installation.executables().cronevalTool.run("'0 0 20 ? * MON-THU' -c 2"); - assertThat(result.stdout, containsString("Valid!")); + assertThat(result.stdout(), containsString("Valid!")); } } diff --git a/qa/os/src/test/java/org/elasticsearch/packaging/test/DebMetadataTests.java b/qa/os/src/test/java/org/elasticsearch/packaging/test/DebMetadataTests.java index c4ebeeec2bc9..793bb7ab6802 100644 --- a/qa/os/src/test/java/org/elasticsearch/packaging/test/DebMetadataTests.java +++ b/qa/os/src/test/java/org/elasticsearch/packaging/test/DebMetadataTests.java @@ -29,7 +29,7 @@ public class DebMetadataTests extends PackagingTestCase { public void test05CheckLintian() { String extraArgs = ""; - final String helpText = sh.run("lintian --help").stdout; + final String helpText = sh.run("lintian --help").stdout(); if (helpText.contains("fail-on-warnings")) { extraArgs = "--fail-on-warnings"; } else if (helpText.contains("--fail-on error")) { @@ -44,9 +44,9 @@ public class DebMetadataTests extends PackagingTestCase { final Shell.Result result = sh.run("dpkg -I " + getDistributionFile(distribution())); - TestCase.assertTrue(Pattern.compile("(?m)^ Depends:.*bash.*").matcher(result.stdout).find()); + TestCase.assertTrue(Pattern.compile("(?m)^ Depends:.*bash.*").matcher(result.stdout()).find()); String oppositePackageName = "elasticsearch-oss"; - TestCase.assertTrue(Pattern.compile("(?m)^ Conflicts: " + oppositePackageName + "$").matcher(result.stdout).find()); + TestCase.assertTrue(Pattern.compile("(?m)^ Conflicts: " + oppositePackageName + "$").matcher(result.stdout()).find()); } } diff --git a/qa/os/src/test/java/org/elasticsearch/packaging/test/DebPreservationTests.java b/qa/os/src/test/java/org/elasticsearch/packaging/test/DebPreservationTests.java index f30bcdbe4e86..4f2048aa0043 100644 --- a/qa/os/src/test/java/org/elasticsearch/packaging/test/DebPreservationTests.java +++ b/qa/os/src/test/java/org/elasticsearch/packaging/test/DebPreservationTests.java @@ -82,6 +82,6 @@ public class DebPreservationTests extends PackagingTestCase { assertPathsDoNotExist(installation.config, installation.envFile); - assertThat(packageStatus(distribution()).exitCode, is(1)); + assertThat(packageStatus(distribution()).exitCode(), is(1)); } } diff --git a/qa/os/src/test/java/org/elasticsearch/packaging/test/DockerTests.java b/qa/os/src/test/java/org/elasticsearch/packaging/test/DockerTests.java index 58cbc6be097e..dc92789be15e 100644 --- a/qa/os/src/test/java/org/elasticsearch/packaging/test/DockerTests.java +++ b/qa/os/src/test/java/org/elasticsearch/packaging/test/DockerTests.java @@ -167,7 +167,7 @@ public class DockerTests extends PackagingTestCase { final Installation.Executables bin = installation.executables(); final Result r = sh.run(bin.pluginTool + " list"); - assertThat("Expected no plugins to be listed", r.stdout, emptyString()); + assertThat("Expected no plugins to be listed", r.stdout(), emptyString()); } /** @@ -306,7 +306,7 @@ public class DockerTests extends PackagingTestCase { final List> interactions = mockServer.getInteractions(); - assertThat(result.stderr, containsString("FileNotFoundException: http://example.com/my-plugin.zip")); + assertThat(result.stderr(), containsString("FileNotFoundException: http://example.com/my-plugin.zip")); // Now check that Elasticsearch did use the proxy server assertThat(interactions, hasSize(1)); @@ -369,7 +369,7 @@ public class DockerTests extends PackagingTestCase { * Check that the JDK's `cacerts` file is a symlink to the copy provided by the operating system. */ public void test040JavaUsesTheOsProvidedKeystore() { - final String path = sh.run("realpath jdk/lib/security/cacerts").stdout; + final String path = sh.run("realpath jdk/lib/security/cacerts").stdout(); if (distribution.packaging == Packaging.DOCKER_UBI || distribution.packaging == Packaging.DOCKER_IRON_BANK) { // In these images, the `cacerts` file ought to be a symlink here @@ -384,7 +384,9 @@ public class DockerTests extends PackagingTestCase { * Checks that there are Amazon trusted certificates in the cacaerts keystore. */ public void test041AmazonCaCertsAreInTheKeystore() { - final boolean matches = sh.run("jdk/bin/keytool -cacerts -storepass changeit -list | grep trustedCertEntry").stdout.lines() + final boolean matches = sh.run("jdk/bin/keytool -cacerts -storepass changeit -list | grep trustedCertEntry") + .stdout() + .lines() .anyMatch(line -> line.contains("amazonrootca")); assertTrue("Expected Amazon trusted cert in cacerts", matches); @@ -417,7 +419,7 @@ public class DockerTests extends PackagingTestCase { public void test060JavaUsesCloudflareZlib() { waitForElasticsearch(installation, "elastic", PASSWORD); - final String output = sh.run("bash -c 'pmap -p $(pidof java)'").stdout; + final String output = sh.run("bash -c 'pmap -p $(pidof java)'").stdout(); assertThat("Expected java to be using cloudflare-zlib", output, containsString("cloudflare-zlib")); } @@ -669,7 +671,7 @@ public class DockerTests extends PackagingTestCase { ); assertThat( - dockerLogs.stderr, + dockerLogs.stderr(), containsString("ERROR: Both ELASTIC_PASSWORD_FILE and ELASTIC_PASSWORD are set. These are mutually exclusive.") ); } @@ -693,7 +695,7 @@ public class DockerTests extends PackagingTestCase { ); assertThat( - dockerLogs.stderr, + dockerLogs.stderr(), containsString( "ERROR: File /run/secrets/" + passwordFilename + " from ELASTIC_PASSWORD_FILE must have file permissions 400 or 600" ) @@ -729,7 +731,7 @@ public class DockerTests extends PackagingTestCase { ); assertThat( - dockerLogs.stderr, + dockerLogs.stderr(), containsString( "ERROR: File " + passwordFilename @@ -756,7 +758,7 @@ public class DockerTests extends PackagingTestCase { final Result result = sh.runIgnoreExitCode("bash -c 'echo y | elasticsearch-setup-passwords auto'"); assertFalse("elasticsearch-setup-passwords command should have failed", result.isSuccess()); - assertThat(result.stdout, containsString("java.net.UnknownHostException: this.is.not.valid")); + assertThat(result.stdout(), containsString("java.net.UnknownHostException: this.is.not.valid")); } /** @@ -772,7 +774,9 @@ public class DockerTests extends PackagingTestCase { // Note the double-underscore in the var name here, which retains the underscore in translation installation = runContainer(distribution(), builder().envVar("ES_SETTING_XPACK_SECURITY_FIPS__MODE_ENABLED", "false")); - final Optional commandLine = sh.run("bash -c 'COLUMNS=2000 ps ax'").stdout.lines() + final Optional commandLine = sh.run("bash -c 'COLUMNS=2000 ps ax'") + .stdout() + .lines() .filter(line -> line.contains("org.elasticsearch.bootstrap.Elasticsearch")) .findFirst(); @@ -798,7 +802,9 @@ public class DockerTests extends PackagingTestCase { .envVar("es_setting_xpack_security_fips__mode_enabled", "false") ); - final Optional commandLine = sh.run("bash -c 'COLUMNS=2000 ps ax'").stdout.lines() + final Optional commandLine = sh.run("bash -c 'COLUMNS=2000 ps ax'") + .stdout() + .lines() .filter(line -> line.contains("org.elasticsearch.bootstrap.Elasticsearch")) .findFirst(); @@ -821,7 +827,9 @@ public class DockerTests extends PackagingTestCase { builder().envVar("xpack.security.fips_mode.enabled", "false").envVar("http.cors.allow-methods", "GET") ); - final Optional commandLine = sh.run("bash -c 'COLUMNS=2000 ps ax'").stdout.lines() + final Optional commandLine = sh.run("bash -c 'COLUMNS=2000 ps ax'") + .stdout() + .lines() .filter(line -> line.contains("org.elasticsearch.bootstrap.Elasticsearch")) .findFirst(); @@ -845,12 +853,12 @@ public class DockerTests extends PackagingTestCase { assertTrue(existsInContainer(securityCli)); Result result = sh.run(bin.certutilTool + " --help"); - assertThat(result.stdout, containsString("Simplifies certificate creation for use with the Elastic Stack")); + assertThat(result.stdout(), containsString("Simplifies certificate creation for use with the Elastic Stack")); // Ensure that the exit code from the java command is passed back up through the shell script result = sh.runIgnoreExitCode(bin.certutilTool + " invalid-command"); assertThat(result.isSuccess(), is(false)); - assertThat(result.stdout, containsString("Unknown command [invalid-command]")); + assertThat(result.stdout(), containsString("Unknown command [invalid-command]")); } /** @@ -860,7 +868,7 @@ public class DockerTests extends PackagingTestCase { final Installation.Executables bin = installation.executables(); final Result result = sh.run(bin.shardTool + " -h"); - assertThat(result.stdout, containsString("A CLI tool to remove corrupted parts of unrecoverable shards")); + assertThat(result.stdout(), containsString("A CLI tool to remove corrupted parts of unrecoverable shards")); } /** @@ -872,7 +880,7 @@ public class DockerTests extends PackagingTestCase { final Result result = sh.run(bin.nodeTool + " -h"); assertThat( "Failed to find expected message about the elasticsearch-node CLI tool", - result.stdout, + result.stdout(), containsString("A CLI tool to do unsafe cluster and index manipulations on current node") ); } @@ -897,7 +905,7 @@ public class DockerTests extends PackagingTestCase { final Shell localSh = new Shell(); final String findResults = localSh.run( "docker run --rm --tty " + DockerRun.getImageName(distribution) + " bash -c ' touch data/test && find . \\! -group 0 ' " - ).stdout; + ).stdout(); assertThat("Found some files whose GID != 0", findResults, is(emptyString())); } @@ -978,8 +986,8 @@ public class DockerTests extends PackagingTestCase { waitForElasticsearch(installation, "elastic", PASSWORD); final Result containerLogs = getContainerLogs(); - assertThat("Container logs should contain full class names", containerLogs.stdout, containsString("org.elasticsearch.node.Node")); - assertThat("Container logs don't contain INFO level messages", containerLogs.stdout, containsString("INFO")); + assertThat("Container logs should contain full class names", containerLogs.stdout(), containsString("org.elasticsearch.node.Node")); + assertThat("Container logs don't contain INFO level messages", containerLogs.stdout(), containsString("INFO")); } /** @@ -991,7 +999,7 @@ public class DockerTests extends PackagingTestCase { waitForElasticsearch(installation, "elastic", PASSWORD); final Result containerLogs = getContainerLogs(); - final List stdout = containerLogs.stdout.lines().toList(); + final List stdout = containerLogs.stdout().lines().toList(); // We select to look for a line near the beginning so that we don't stumble upon the stdout printing of auto-configured credentials assertThat("Container logs should be formatted using the stack config", stdout.get(10), matchesPattern("^\\[\\d\\d\\d\\d-.*")); assertThat("[logs/docker-cluster.log] should exist but it doesn't", existsInContainer("logs/docker-cluster.log"), is(true)); @@ -1006,7 +1014,7 @@ public class DockerTests extends PackagingTestCase { waitForElasticsearch(installation, "elastic", PASSWORD); final Result containerLogs = getContainerLogs(); - final List stdout = containerLogs.stdout.lines().toList(); + final List stdout = containerLogs.stdout().lines().toList(); // We select to look for a line near the beginning so that we don't stumble upon the stdout printing of auto-configured credentials assertThat("Container logs should be formatted using the docker config", stdout.get(10), startsWith("{\"")); assertThat("[logs/docker-cluster.log] shouldn't exist but it does", existsInContainer("logs/docker-cluster.log"), is(false)); @@ -1018,7 +1026,7 @@ public class DockerTests extends PackagingTestCase { public void test123CannotUseUnknownLoggingConfig() { final Result result = runContainerExpectingFailure(distribution(), builder().envVar("ES_LOG_STYLE", "unknown")); - assertThat(result.stderr, containsString("ERROR: ES_LOG_STYLE set to [unknown]. Expected [console] or [file]")); + assertThat(result.stderr(), containsString("ERROR: ES_LOG_STYLE set to [unknown]. Expected [console] or [file]")); } /** @@ -1041,11 +1049,11 @@ public class DockerTests extends PackagingTestCase { public void test130JavaHasCorrectOwnership() { final ProcessInfo info = ProcessInfo.getProcessInfo(sh, "java"); - assertThat("Incorrect UID", info.uid, equalTo(1000)); - assertThat("Incorrect username", info.username, equalTo("elasticsearch")); + assertThat("Incorrect UID", info.uid(), equalTo(1000)); + assertThat("Incorrect username", info.username(), equalTo("elasticsearch")); - assertThat("Incorrect GID", info.gid, equalTo(0)); - assertThat("Incorrect group", info.group, equalTo("root")); + assertThat("Incorrect GID", info.gid(), equalTo(0)); + assertThat("Incorrect group", info.group(), equalTo("root")); } /** @@ -1055,13 +1063,13 @@ public class DockerTests extends PackagingTestCase { public void test131InitProcessHasCorrectPID() { final ProcessInfo info = ProcessInfo.getProcessInfo(sh, "tini"); - assertThat("Incorrect PID", info.pid, equalTo(1)); + assertThat("Incorrect PID", info.pid(), equalTo(1)); - assertThat("Incorrect UID", info.uid, equalTo(1000)); - assertThat("Incorrect username", info.username, equalTo("elasticsearch")); + assertThat("Incorrect UID", info.uid(), equalTo(1000)); + assertThat("Incorrect username", info.username(), equalTo("elasticsearch")); - assertThat("Incorrect GID", info.gid, equalTo(0)); - assertThat("Incorrect group", info.group, equalTo("root")); + assertThat("Incorrect GID", info.gid(), equalTo(0)); + assertThat("Incorrect group", info.group(), equalTo("root")); } /** @@ -1131,7 +1139,8 @@ public class DockerTests extends PackagingTestCase { // Grab the container output and find the line where it print the JVM arguments. This will // let us see what the automatic heap sizing calculated. - final Optional jvmArgumentsLine = getContainerLogs().stdout.lines() + final Optional jvmArgumentsLine = getContainerLogs().stdout() + .lines() .filter(line -> line.contains("JVM arguments")) .findFirst(); assertThat("Failed to find jvmArguments in container logs", jvmArgumentsLine.isPresent(), is(true)); @@ -1164,9 +1173,9 @@ public class DockerTests extends PackagingTestCase { public void test170DefaultShellIsBash() { final Result result = DockerShell.executeCommand("/bin/sh", "-c", "echo $SHELL"); if (result.isSuccess()) { - assertThat(result.stdout, equalTo("/bin/bash")); + assertThat(result.stdout(), equalTo("/bin/bash")); } else { - throw new RuntimeException("Command failed: " + result.stderr); + throw new RuntimeException("Command failed: " + result.stderr()); } } @@ -1176,12 +1185,12 @@ public class DockerTests extends PackagingTestCase { public void test200UbiImagesHaveLicenseDirectory() { assumeTrue(distribution.packaging == Packaging.DOCKER_UBI); - final String[] files = sh.run("find /licenses -type f").stdout.split("\n"); + final String[] files = sh.run("find /licenses -type f").stdout().split("\n"); assertThat(files, arrayContaining("/licenses/LICENSE")); // UBI image doesn't contain `diff` - final String ubiLicense = sh.run("cat /licenses/LICENSE").stdout; - final String distroLicense = sh.run("cat /usr/share/elasticsearch/LICENSE.txt").stdout; + final String ubiLicense = sh.run("cat /licenses/LICENSE").stdout(); + final String distroLicense = sh.run("cat /usr/share/elasticsearch/LICENSE.txt").stdout(); assertThat(ubiLicense, equalTo(distroLicense)); } @@ -1216,12 +1225,12 @@ public class DockerTests extends PackagingTestCase { public void test300IronBankImagesHaveLicenseDirectory() { assumeTrue(distribution.packaging == Packaging.DOCKER_IRON_BANK); - final String[] files = sh.run("find /licenses -type f").stdout.split("\n"); + final String[] files = sh.run("find /licenses -type f").stdout().split("\n"); assertThat(files, arrayContaining("/licenses/LICENSE", "/licenses/LICENSE.addendum")); // Image doesn't contain `diff` - final String ubiLicense = sh.run("cat /licenses/LICENSE").stdout; - final String distroLicense = sh.run("cat /usr/share/elasticsearch/LICENSE.txt").stdout; + final String ubiLicense = sh.run("cat /licenses/LICENSE").stdout(); + final String distroLicense = sh.run("cat /usr/share/elasticsearch/LICENSE.txt").stdout(); assertThat(ubiLicense, equalTo(distroLicense)); } @@ -1261,6 +1270,6 @@ public class DockerTests extends PackagingTestCase { private List listPlugins() { final Installation.Executables bin = installation.executables(); - return sh.run(bin.pluginTool + " list").stdout.lines().collect(Collectors.toList()); + return sh.run(bin.pluginTool + " list").stdout().lines().collect(Collectors.toList()); } } diff --git a/qa/os/src/test/java/org/elasticsearch/packaging/test/EnrollNodeToClusterTests.java b/qa/os/src/test/java/org/elasticsearch/packaging/test/EnrollNodeToClusterTests.java index 83592674d5cf..91e5051550e1 100644 --- a/qa/os/src/test/java/org/elasticsearch/packaging/test/EnrollNodeToClusterTests.java +++ b/qa/os/src/test/java/org/elasticsearch/packaging/test/EnrollNodeToClusterTests.java @@ -42,7 +42,7 @@ public class EnrollNodeToClusterTests extends PackagingTestCase { // something in our tests wrap the error code to 1 on windows // TODO investigate this and remove this guard if (distribution.platform != Distribution.Platform.WINDOWS) { - assertThat(result.exitCode, equalTo(ExitCodes.USAGE)); + assertThat(result.exitCode(), equalTo(ExitCodes.USAGE)); } verifySecurityNotAutoConfigured(installation); } @@ -58,7 +58,7 @@ public class EnrollNodeToClusterTests extends PackagingTestCase { // something in our tests wrap the error code to 1 on windows // TODO investigate this and remove this guard if (distribution.platform != Distribution.Platform.WINDOWS) { - assertThat(result.exitCode, equalTo(ExitCodes.DATA_ERROR)); + assertThat(result.exitCode(), equalTo(ExitCodes.DATA_ERROR)); } verifySecurityNotAutoConfigured(installation); } @@ -74,7 +74,7 @@ public class EnrollNodeToClusterTests extends PackagingTestCase { // something in our tests wrap the error code to 1 on windows // TODO investigate this and remove this guard if (distribution.platform != Distribution.Platform.WINDOWS) { - assertThat(result.exitCode, equalTo(ExitCodes.UNAVAILABLE)); + assertThat(result.exitCode(), equalTo(ExitCodes.UNAVAILABLE)); } verifySecurityNotAutoConfigured(installation); } @@ -95,7 +95,7 @@ public class EnrollNodeToClusterTests extends PackagingTestCase { // something in our tests wrap the error code to 1 on windows // TODO investigate this and remove this guard if (distribution.platform != Distribution.Platform.WINDOWS) { - assertThat(result.exitCode, equalTo(ExitCodes.NOOP)); + assertThat(result.exitCode(), equalTo(ExitCodes.NOOP)); } Platforms.onWindows(() -> sh.chown(installation.config)); } @@ -113,7 +113,7 @@ public class EnrollNodeToClusterTests extends PackagingTestCase { // something in our tests wrap the error code to 1 on windows // TODO investigate this and remove this guard if (distribution.platform != Distribution.Platform.WINDOWS) { - assertThat(result.exitCode, equalTo(ExitCodes.NOOP)); + assertThat(result.exitCode(), equalTo(ExitCodes.NOOP)); } } @@ -133,8 +133,8 @@ public class EnrollNodeToClusterTests extends PackagingTestCase { ), false ); - assertThat(result.stderr, containsString("Multiple --enrollment-token parameters are not allowed")); - assertThat(result.exitCode, equalTo(1)); + assertThat(result.stderr(), containsString("Multiple --enrollment-token parameters are not allowed")); + assertThat(result.exitCode(), equalTo(1)); } private String generateMockEnrollmentToken() throws Exception { diff --git a/qa/os/src/test/java/org/elasticsearch/packaging/test/EnrollmentProcessTests.java b/qa/os/src/test/java/org/elasticsearch/packaging/test/EnrollmentProcessTests.java index a4991f529e97..d21f8786e31e 100644 --- a/qa/os/src/test/java/org/elasticsearch/packaging/test/EnrollmentProcessTests.java +++ b/qa/os/src/test/java/org/elasticsearch/packaging/test/EnrollmentProcessTests.java @@ -51,8 +51,8 @@ public class EnrollmentProcessTests extends PackagingTestCase { verifySecurityAutoConfigured(installation); // Generate a node enrollment token to be subsequently used by the second node Shell.Result createTokenResult = installation.executables().createEnrollmentToken.run("-s node"); - assertThat(Strings.isNullOrEmpty(createTokenResult.stdout), is(false)); - final String enrollmentToken = createTokenResult.stdout; + assertThat(Strings.isNullOrEmpty(createTokenResult.stdout()), is(false)); + final String enrollmentToken = createTokenResult.stdout(); // installation now points to the second node installation = installArchive(sh, distribution(), getRootTempDir().resolve("elasticsearch-node2"), getCurrentVersion(), true); @@ -65,7 +65,7 @@ public class EnrollmentProcessTests extends PackagingTestCase { false ); assertThat( - startSecondNodeWithInvalidToken.stdout, + startSecondNodeWithInvalidToken.stdout(), containsString("Failed to parse enrollment token : some-invalid-token-here . Error was: Illegal base64 character 2d") ); verifySecurityNotAutoConfigured(installation); @@ -93,7 +93,9 @@ public class EnrollmentProcessTests extends PackagingTestCase { waitForElasticsearch(installation); final String node1ContainerId = Docker.getContainerId(); - final String enrollmentToken = installation.executables().createEnrollmentToken.run("-s node").stdout.lines() + final String enrollmentToken = installation.executables().createEnrollmentToken.run("-s node") + .stdout() + .lines() .filter(line -> line.startsWith("WARNING:") == false) .findFirst() .orElseThrow(() -> new AssertionError("Failing to find any non-warning output lines")); diff --git a/qa/os/src/test/java/org/elasticsearch/packaging/test/KeystoreManagementTests.java b/qa/os/src/test/java/org/elasticsearch/packaging/test/KeystoreManagementTests.java index fb3586c040b8..9d9bb3f2f368 100644 --- a/qa/os/src/test/java/org/elasticsearch/packaging/test/KeystoreManagementTests.java +++ b/qa/os/src/test/java/org/elasticsearch/packaging/test/KeystoreManagementTests.java @@ -73,7 +73,7 @@ public class KeystoreManagementTests extends PackagingTestCase { final Installation.Executables bin = installation.executables(); Shell.Result r = sh.runIgnoreExitCode(bin.keystoreTool + " has-passwd"); assertFalse("has-passwd should fail", r.isSuccess()); - assertThat("has-passwd should indicate missing keystore", r.stderr, containsString(ERROR_KEYSTORE_NOT_FOUND)); + assertThat("has-passwd should indicate missing keystore", r.stderr(), containsString(ERROR_KEYSTORE_NOT_FOUND)); } /** Test initial package state */ @@ -89,9 +89,9 @@ public class KeystoreManagementTests extends PackagingTestCase { final Installation.Executables bin = installation.executables(); Shell.Result r = sh.runIgnoreExitCode(bin.keystoreTool + " has-passwd"); assertFalse("has-passwd should fail", r.isSuccess()); - assertThat("has-passwd should indicate unprotected keystore", r.stderr, containsString(ERROR_KEYSTORE_NOT_PASSWORD_PROTECTED)); + assertThat("has-passwd should indicate unprotected keystore", r.stderr(), containsString(ERROR_KEYSTORE_NOT_PASSWORD_PROTECTED)); Shell.Result r2 = bin.keystoreTool.run("list"); - assertThat(r2.stdout, containsString("keystore.seed")); + assertThat(r2.stdout(), containsString("keystore.seed")); } /** Test initial Docker state */ @@ -109,9 +109,9 @@ public class KeystoreManagementTests extends PackagingTestCase { final Installation.Executables bin = installation.executables(); Shell.Result r = sh.runIgnoreExitCode(bin.keystoreTool + " has-passwd"); assertFalse("has-passwd should fail", r.isSuccess()); - assertThat("has-passwd should indicate unprotected keystore", r.stdout, containsString(ERROR_KEYSTORE_NOT_PASSWORD_PROTECTED)); + assertThat("has-passwd should indicate unprotected keystore", r.stdout(), containsString(ERROR_KEYSTORE_NOT_PASSWORD_PROTECTED)); Shell.Result r2 = bin.keystoreTool.run("list"); - assertThat(r2.stdout, containsString("keystore.seed")); + assertThat(r2.stdout(), containsString("keystore.seed")); } public void test20KeystorePasswordOnStandardInput() throws Exception { @@ -160,7 +160,7 @@ public class KeystoreManagementTests extends PackagingTestCase { Shell.Result result = runElasticsearchStartCommand("wrong", false, true); // error will be on stdout for "expect" - assertThat(result.stdout, anyOf(containsString(ERROR_INCORRECT_PASSWORD), containsString(ERROR_CORRUPTED_KEYSTORE))); + assertThat(result.stdout(), anyOf(containsString(ERROR_INCORRECT_PASSWORD), containsString(ERROR_CORRUPTED_KEYSTORE))); } /** @@ -172,7 +172,7 @@ public class KeystoreManagementTests extends PackagingTestCase { assertPasswordProtectedKeystore(); Shell.Result r = installation.executables().elasticsearch.run("--help"); - assertThat(r.stdout, startsWith("Starts Elasticsearch")); + assertThat(r.stdout(), startsWith("Starts Elasticsearch")); } public void test30KeystorePasswordFromFile() throws Exception { @@ -293,7 +293,7 @@ public class KeystoreManagementTests extends PackagingTestCase { distribution(), builder().volume(localConfigPath.resolve("config"), installation.config).envVar("KEYSTORE_PASSWORD", "wrong") ); - assertThat(r.stderr, containsString(ERROR_INCORRECT_PASSWORD)); + assertThat(r.stderr(), containsString(ERROR_INCORRECT_PASSWORD)); } public void test50CreateKeystoreManually() throws Exception { @@ -305,7 +305,7 @@ public class KeystoreManagementTests extends PackagingTestCase { verifyKeystorePermissions(); Shell.Result r = bin.keystoreTool.run("list"); - assertThat(r.stdout, containsString("keystore.seed")); + assertThat(r.stdout(), containsString("keystore.seed")); } public void test60AutoCreateKeystore() throws Exception { @@ -325,7 +325,7 @@ public class KeystoreManagementTests extends PackagingTestCase { final Installation.Executables bin = installation.executables(); Shell.Result r = bin.keystoreTool.run("list"); - assertThat(r.stdout, containsString("keystore.seed")); + assertThat(r.stdout(), containsString("keystore.seed")); } /** @@ -427,7 +427,7 @@ public class KeystoreManagementTests extends PackagingTestCase { private void assertPasswordProtectedKeystore() { Shell.Result r = installation.executables().keystoreTool.run("has-passwd"); - assertThat("keystore should be password protected", r.exitCode, is(0)); + assertThat("keystore should be password protected", r.exitCode(), is(0)); } private void verifyKeystorePermissions() { diff --git a/qa/os/src/test/java/org/elasticsearch/packaging/test/PackageTests.java b/qa/os/src/test/java/org/elasticsearch/packaging/test/PackageTests.java index 62541d148c96..5c38fa36a664 100644 --- a/qa/os/src/test/java/org/elasticsearch/packaging/test/PackageTests.java +++ b/qa/os/src/test/java/org/elasticsearch/packaging/test/PackageTests.java @@ -63,19 +63,19 @@ public class PackageTests extends PackagingTestCase { } public void test20PluginsCommandWhenNoPlugins() { - assertThat(sh.run(installation.bin("elasticsearch-plugin") + " list").stdout, is(emptyString())); + assertThat(sh.run(installation.bin("elasticsearch-plugin") + " list").stdout(), is(emptyString())); } public void test30DaemonIsNotEnabledOnRestart() { if (isSystemd()) { sh.run("systemctl daemon-reload"); - String isEnabledOutput = sh.runIgnoreExitCode("systemctl is-enabled elasticsearch.service").stdout.trim(); + String isEnabledOutput = sh.runIgnoreExitCode("systemctl is-enabled elasticsearch.service").stdout().trim(); assertThat(isEnabledOutput, equalTo("disabled")); } } public void test31InstallDoesNotStartServer() { - assertThat(sh.run("ps aux").stdout, not(containsString("org.elasticsearch.bootstrap.Elasticsearch"))); + assertThat(sh.run("ps aux").stdout(), not(containsString("org.elasticsearch.bootstrap.Elasticsearch"))); } private void assertRunsWithJavaHome() throws Exception { @@ -131,12 +131,12 @@ public class PackageTests extends PackagingTestCase { } public void test40StartServer() throws Exception { - String start = sh.runIgnoreExitCode("date ").stdout.trim(); + String start = sh.runIgnoreExitCode("date ").stdout().trim(); startElasticsearch(); String journalEntries = sh.runIgnoreExitCode( "journalctl _SYSTEMD_UNIT=elasticsearch.service " + "--since \"" + start + "\" --output cat | wc -l" - ).stdout.trim(); + ).stdout().trim(); assertThat(journalEntries, equalTo("0")); assertPathsExist(installation.pidDir.resolve("elasticsearch.pid")); @@ -166,7 +166,7 @@ public class PackageTests extends PackagingTestCase { remove(distribution()); // removing must stop the service - assertThat(sh.run("ps aux").stdout, not(containsString("org.elasticsearch.bootstrap.Elasticsearch"))); + assertThat(sh.run("ps aux").stdout(), not(containsString("org.elasticsearch.bootstrap.Elasticsearch"))); if (isSystemd()) { @@ -186,15 +186,15 @@ public class PackageTests extends PackagingTestCase { } else { final Result versionResult = sh.run("systemctl --version"); - final Matcher matcher = Pattern.compile("^systemd (\\d+)").matcher(versionResult.stdout); + final Matcher matcher = Pattern.compile("^systemd (\\d+)").matcher(versionResult.stdout()); matcher.find(); final int version = Integer.parseInt(matcher.group(1)); statusExitCode = version < 231 ? 3 : 4; } - assertThat(sh.runIgnoreExitCode("systemctl status elasticsearch.service").exitCode, is(statusExitCode)); - assertThat(sh.runIgnoreExitCode("systemctl is-enabled elasticsearch.service").exitCode, is(1)); + assertThat(sh.runIgnoreExitCode("systemctl status elasticsearch.service").exitCode(), is(statusExitCode)); + assertThat(sh.runIgnoreExitCode("systemctl is-enabled elasticsearch.service").exitCode(), is(1)); } @@ -258,7 +258,7 @@ public class PackageTests extends PackagingTestCase { assertThat(nodesStatsResponse, containsString("\"adjusted_total_in_bytes\":891289600")); // 40% of 850MB - assertThat(sh.run("ps auwwx").stdout, containsString("-Xms340m -Xmx340m")); + assertThat(sh.run("ps auwwx").stdout(), containsString("-Xms340m -Xmx340m")); stopElasticsearch(); }); @@ -358,16 +358,16 @@ public class PackageTests extends PackagingTestCase { final Path pidFile = installation.pidDir.resolve("elasticsearch.pid"); assertThat(pidFile, fileExists()); String pid = slurp(pidFile).trim(); - String maxFileSize = sh.run("cat /proc/%s/limits | grep \"Max file size\" | awk '{ print $4 }'", pid).stdout.trim(); + String maxFileSize = sh.run("cat /proc/%s/limits | grep \"Max file size\" | awk '{ print $4 }'", pid).stdout().trim(); assertThat(maxFileSize, equalTo("unlimited")); - String maxProcesses = sh.run("cat /proc/%s/limits | grep \"Max processes\" | awk '{ print $3 }'", pid).stdout.trim(); + String maxProcesses = sh.run("cat /proc/%s/limits | grep \"Max processes\" | awk '{ print $3 }'", pid).stdout().trim(); assertThat(maxProcesses, equalTo("4096")); - String maxOpenFiles = sh.run("cat /proc/%s/limits | grep \"Max open files\" | awk '{ print $4 }'", pid).stdout.trim(); + String maxOpenFiles = sh.run("cat /proc/%s/limits | grep \"Max open files\" | awk '{ print $4 }'", pid).stdout().trim(); assertThat(maxOpenFiles, equalTo("65535")); - String maxAddressSpace = sh.run("cat /proc/%s/limits | grep \"Max address space\" | awk '{ print $4 }'", pid).stdout.trim(); + String maxAddressSpace = sh.run("cat /proc/%s/limits | grep \"Max address space\" | awk '{ print $4 }'", pid).stdout().trim(); assertThat(maxAddressSpace, equalTo("unlimited")); stopElasticsearch(); @@ -389,7 +389,7 @@ public class PackageTests extends PackagingTestCase { assertBusy(() -> { final Result logs = journald.getLogs(); - assertThat(logs.stdout, containsString("Failed to load settings from [elasticsearch.yml]")); + assertThat(logs.stdout(), containsString("Failed to load settings from [elasticsearch.yml]")); }); }); } diff --git a/qa/os/src/test/java/org/elasticsearch/packaging/test/PackagesSecurityAutoConfigurationTests.java b/qa/os/src/test/java/org/elasticsearch/packaging/test/PackagesSecurityAutoConfigurationTests.java index 1c5ad6cc9019..2439624f3fc3 100644 --- a/qa/os/src/test/java/org/elasticsearch/packaging/test/PackagesSecurityAutoConfigurationTests.java +++ b/qa/os/src/test/java/org/elasticsearch/packaging/test/PackagesSecurityAutoConfigurationTests.java @@ -110,7 +110,7 @@ public class PackagesSecurityAutoConfigurationTests extends PackagingTestCase { // We cannot run two packaged installations simultaneously here so that we can test that the second node enrolls successfully // We trigger with an invalid enrollment token, to verify that we removed the existing auto-configuration Shell.Result result = installation.executables().nodeReconfigureTool.run("--enrollment-token thisisinvalid", "y", true); - assertThat(result.exitCode, equalTo(ExitCodes.DATA_ERROR)); // invalid enrollment token + assertThat(result.exitCode(), equalTo(ExitCodes.DATA_ERROR)); // invalid enrollment token verifySecurityNotAutoConfigured(installation); } @@ -123,7 +123,7 @@ public class PackagesSecurityAutoConfigurationTests extends PackagingTestCase { verifySecurityAutoConfigured(installation); assertNotNull(installation.getElasticPassword()); Shell.Result result = installation.executables().nodeReconfigureTool.run("", null, true); - assertThat(result.exitCode, equalTo(ExitCodes.USAGE)); // missing enrollment token + assertThat(result.exitCode(), equalTo(ExitCodes.USAGE)); // missing enrollment token // we fail on command invocation so we don't even try to remove autoconfiguration verifySecurityAutoConfigured(installation); } @@ -143,7 +143,7 @@ public class PackagesSecurityAutoConfigurationTests extends PackagingTestCase { // Move instead of delete because Files.deleteIfExists bails on non empty dirs Files.move(installation.config(autoConfigDirName.get()), installation.config("temp-autoconf-dir")); Shell.Result result = installation.executables().nodeReconfigureTool.run("--enrollment-token a-token", "y", true); - assertThat(result.exitCode, equalTo(ExitCodes.USAGE)); // + assertThat(result.exitCode(), equalTo(ExitCodes.USAGE)); // } public void test71ReconfigureFailsWhenKeyStorePasswordWrong() throws Exception { @@ -155,14 +155,14 @@ public class PackagesSecurityAutoConfigurationTests extends PackagingTestCase { verifySecurityAutoConfigured(installation); assertNotNull(installation.getElasticPassword()); Shell.Result changePassword = installation.executables().keystoreTool.run("passwd", "some-password\nsome-password\n"); - assertThat(changePassword.exitCode, equalTo(0)); + assertThat(changePassword.exitCode(), equalTo(0)); Shell.Result result = installation.executables().nodeReconfigureTool.run( "--enrollment-token a-token", "y" + "\n" + "some-wrong-password", true ); - assertThat(result.exitCode, equalTo(ExitCodes.IO_ERROR)); // - assertThat(result.stderr, containsString("Error was: Provided keystore password was incorrect")); + assertThat(result.exitCode(), equalTo(ExitCodes.IO_ERROR)); // + assertThat(result.stderr(), containsString("Error was: Provided keystore password was incorrect")); } public void test71ReconfigureFailsWhenKeyStoreDoesNotContainExpectedSettings() throws Exception { @@ -176,11 +176,11 @@ public class PackagesSecurityAutoConfigurationTests extends PackagingTestCase { Shell.Result removeSetting = installation.executables().keystoreTool.run( "remove xpack.security.transport.ssl.keystore.secure_password" ); - assertThat(removeSetting.exitCode, equalTo(0)); + assertThat(removeSetting.exitCode(), equalTo(0)); Shell.Result result = installation.executables().nodeReconfigureTool.run("--enrollment-token a-token", "y", true); - assertThat(result.exitCode, equalTo(ExitCodes.IO_ERROR)); + assertThat(result.exitCode(), equalTo(ExitCodes.IO_ERROR)); assertThat( - result.stderr, + result.stderr(), containsString( "elasticsearch.keystore did not contain expected setting [xpack.security.transport.ssl.keystore.secure_password]." ) @@ -200,8 +200,8 @@ public class PackagesSecurityAutoConfigurationTests extends PackagingTestCase { Files.write(yml, List.of(), TRUNCATE_EXISTING); Shell.Result result = installation.executables().nodeReconfigureTool.run("--enrollment-token a-token", "y", true); - assertThat(result.exitCode, equalTo(ExitCodes.USAGE)); // - assertThat(result.stderr, containsString("Expected configuration is missing from elasticsearch.yml.")); + assertThat(result.exitCode(), equalTo(ExitCodes.USAGE)); // + assertThat(result.stderr(), containsString("Expected configuration is missing from elasticsearch.yml.")); } public void test72ReconfigureRetainsUserSettings() throws Exception { @@ -226,7 +226,7 @@ public class PackagesSecurityAutoConfigurationTests extends PackagingTestCase { // We cannot run two packaged installations simultaneously here so that we can test that the second node enrolls successfully // We trigger with an invalid enrollment token, to verify that we removed the existing auto-configuration Shell.Result result = installation.executables().nodeReconfigureTool.run("--enrollment-token thisisinvalid", "y", true); - assertThat(result.exitCode, equalTo(ExitCodes.DATA_ERROR)); // invalid enrollment token + assertThat(result.exitCode(), equalTo(ExitCodes.DATA_ERROR)); // invalid enrollment token verifySecurityNotAutoConfigured(installation); // Check that user configuration , both inside and outside the autocofiguration stanza, was retained Path editedYml = installation.config("elasticsearch.yml"); diff --git a/qa/os/src/test/java/org/elasticsearch/packaging/test/PackagingTestCase.java b/qa/os/src/test/java/org/elasticsearch/packaging/test/PackagingTestCase.java index 375b71bbbd96..644219572e4e 100644 --- a/qa/os/src/test/java/org/elasticsearch/packaging/test/PackagingTestCase.java +++ b/qa/os/src/test/java/org/elasticsearch/packaging/test/PackagingTestCase.java @@ -128,10 +128,10 @@ public abstract class PackagingTestCase extends Assert { static { Shell initShell = new Shell(); if (Platforms.WINDOWS) { - systemJavaHome = initShell.run("$Env:SYSTEM_JAVA_HOME").stdout.trim(); + systemJavaHome = initShell.run("$Env:SYSTEM_JAVA_HOME").stdout().trim(); } else { assert Platforms.LINUX || Platforms.DARWIN; - systemJavaHome = initShell.run("echo $SYSTEM_JAVA_HOME").stdout.trim(); + systemJavaHome = initShell.run("echo $SYSTEM_JAVA_HOME").stdout().trim(); } } @@ -355,7 +355,7 @@ public abstract class PackagingTestCase extends Assert { } public void awaitElasticsearchStartup(Shell.Result result) throws Exception { - assertThat("Startup command should succeed. Stderr: [" + result + "]", result.exitCode, equalTo(0)); + assertThat("Startup command should succeed. Stderr: [" + result + "]", result.exitCode(), equalTo(0)); switch (distribution.packaging) { case TAR, ZIP -> Archives.assertElasticsearchStarted(installation); case DEB, RPM -> Packages.assertElasticsearchStarted(sh, installation); @@ -385,7 +385,7 @@ public abstract class PackagingTestCase extends Assert { if (Files.exists(installation.home.resolve("elasticsearch.pid"))) { String pid = FileUtils.slurp(installation.home.resolve("elasticsearch.pid")).trim(); logger.info("elasticsearch process ({}) failed to start", pid); - if (sh.run("jps").stdout.contains(pid)) { + if (sh.run("jps").stdout().contains(pid)) { logger.info("Dumping jstack of elasticsearch process ({}) ", pid); sh.runIgnoreExitCode("jstack " + pid); } @@ -413,15 +413,15 @@ public abstract class PackagingTestCase extends Assert { } else if (distribution().isPackage() && Platforms.isSystemd()) { // For systemd, retrieve the error from journalctl - assertThat(result.stderr, containsString("Job for elasticsearch.service failed")); + assertThat(result.stderr(), containsString("Job for elasticsearch.service failed")); Shell.Result error = journaldWrapper.getLogs(); - assertThat(error.stdout, anyOf(stringMatchers)); + assertThat(error.stdout(), anyOf(stringMatchers)); } else if (Platforms.WINDOWS && Files.exists(Archives.getPowershellErrorPath(installation))) { // In Windows, we have written our stdout and stderr to files in order to run // in the background - String wrapperPid = result.stdout.trim(); + String wrapperPid = result.stdout().trim(); sh.runIgnoreExitCode("Wait-Process -Timeout " + Archives.ES_STARTUP_SLEEP_TIME_SECONDS + " -Id " + wrapperPid); sh.runIgnoreExitCode( "Get-EventSubscriber | " @@ -433,7 +433,7 @@ public abstract class PackagingTestCase extends Assert { } else { // Otherwise, error should be on shell stderr - assertThat(result.stderr, anyOf(stringMatchers)); + assertThat(result.stderr(), anyOf(stringMatchers)); } } @@ -663,7 +663,10 @@ public abstract class PackagingTestCase extends Assert { FileMatcher.file(File, "root", "elasticsearch", p660) ) ); - assertThat(sh.run(es.executables().keystoreTool + " list").stdout, Matchers.containsString("autoconfiguration.password_hash")); + assertThat( + sh.run(es.executables().keystoreTool + " list").stdout(), + Matchers.containsString("autoconfiguration.password_hash") + ); settings = Settings.builder().loadFromPath(es.config("elasticsearch.yml")).build(); } assertThat(settings.get("xpack.security.enabled"), equalTo("true")); @@ -688,7 +691,7 @@ public abstract class PackagingTestCase extends Assert { if (es.distribution.isPackage()) { if (Files.exists(es.config("elasticsearch.keystore"))) { assertThat( - sh.run(es.executables().keystoreTool + " list").stdout, + sh.run(es.executables().keystoreTool + " list").stdout(), not(Matchers.containsString("autoconfiguration.password_hash")) ); } @@ -711,8 +714,8 @@ public abstract class PackagingTestCase extends Assert { } else { lsResult = sh.run("find \"" + es.config + "\" -type d -maxdepth 1"); } - assertNotNull(lsResult.stdout); - return Arrays.stream(lsResult.stdout.split("\n")).filter(f -> f.contains("certs")).findFirst(); + assertNotNull(lsResult.stdout()); + return Arrays.stream(lsResult.stdout().split("\n")).filter(f -> f.contains("certs")).findFirst(); } } diff --git a/qa/os/src/test/java/org/elasticsearch/packaging/test/PasswordToolsTests.java b/qa/os/src/test/java/org/elasticsearch/packaging/test/PasswordToolsTests.java index e52f0146ecc8..623cf34ce8a4 100644 --- a/qa/os/src/test/java/org/elasticsearch/packaging/test/PasswordToolsTests.java +++ b/qa/os/src/test/java/org/elasticsearch/packaging/test/PasswordToolsTests.java @@ -47,7 +47,7 @@ public class PasswordToolsTests extends PackagingTestCase { assertWhileRunning(() -> { ServerUtils.waitForElasticsearch(installation); Shell.Result result = installation.executables().setupPasswordsTool.run("auto --batch", null); - Map userpasses = parseUsersAndPasswords(result.stdout); + Map userpasses = parseUsersAndPasswords(result.stdout()); for (Map.Entry userpass : userpasses.entrySet()) { String response = ServerUtils.makeRequest( Request.Get("http://localhost:9200"), @@ -115,7 +115,7 @@ public class PasswordToolsTests extends PackagingTestCase { assertWhileRunning(() -> { Shell.Result result = installation.executables().setupPasswordsTool.run("auto --batch", null); - Map userpasses = parseUsersAndPasswords(result.stdout); + Map userpasses = parseUsersAndPasswords(result.stdout()); assertThat(userpasses, hasKey("elastic")); for (Map.Entry userpass : userpasses.entrySet()) { String response = ServerUtils.makeRequest( diff --git a/qa/os/src/test/java/org/elasticsearch/packaging/test/PluginCliTests.java b/qa/os/src/test/java/org/elasticsearch/packaging/test/PluginCliTests.java index 552c250d51c5..ff67733a7633 100644 --- a/qa/os/src/test/java/org/elasticsearch/packaging/test/PluginCliTests.java +++ b/qa/os/src/test/java/org/elasticsearch/packaging/test/PluginCliTests.java @@ -112,7 +112,7 @@ public class PluginCliTests extends PackagingTestCase { public void test24JavaOpts() throws Exception { sh.getEnv().put("ES_JAVA_OPTS", "-XX:+PrintFlagsFinal"); - assertWithExamplePlugin(installResult -> assertThat(installResult.stdout, containsString("MaxHeapSize"))); + assertWithExamplePlugin(installResult -> assertThat(installResult.stdout(), containsString("MaxHeapSize"))); } public void test25Umask() throws Exception { @@ -129,7 +129,7 @@ public class PluginCliTests extends PackagingTestCase { Shell.Result result = installation.executables().pluginTool.run("install analysis-icu", null, true); assertThat(result.isSuccess(), is(false)); - assertThat(result.stderr, containsString("Plugins config [" + pluginsConfig + "] exists")); + assertThat(result.stderr(), containsString("Plugins config [" + pluginsConfig + "] exists")); } /** @@ -141,7 +141,7 @@ public class PluginCliTests extends PackagingTestCase { Shell.Result result = installation.executables().pluginTool.run("install analysis-icu", null, true); assertThat(result.isSuccess(), is(false)); - assertThat(result.stderr, containsString("Plugins config [" + pluginsConfig + "] exists")); + assertThat(result.stderr(), containsString("Plugins config [" + pluginsConfig + "] exists")); } /** @@ -168,14 +168,14 @@ public class PluginCliTests extends PackagingTestCase { */ public void test40InstallOfModularizedPluginsSucceedsButDoesNothing() { for (String pluginId : List.of("repository-azure", "repository-gcs", "repository-s3")) { - String stderr = installation.executables().pluginTool.run("install " + pluginId).stderr; + String stderr = installation.executables().pluginTool.run("install " + pluginId).stderr(); assertThat( "Expected plugin installed to warn about migrated plugins", stderr, containsString("[" + pluginId + "] is no longer a plugin") ); - String pluginList = installation.executables().pluginTool.run("list").stdout; + String pluginList = installation.executables().pluginTool.run("list").stdout(); assertThat(pluginId + " should not appear in the plugin list", pluginList, not(containsString(pluginId))); } } @@ -185,11 +185,11 @@ public class PluginCliTests extends PackagingTestCase { * succeeds, but does nothing. */ public void test41RemovalOfModularizedPluginsSucceedsButDoesNothing() { - String pluginList = installation.executables().pluginTool.run("list").stdout; + String pluginList = installation.executables().pluginTool.run("list").stdout(); assertThat("Expected no plugins to be installed", pluginList.trim(), is(emptyString())); for (String pluginId : List.of("repository-azure", "repository-gcs", "repository-s3")) { - String stderr = installation.executables().pluginTool.run("remove " + pluginId).stderr; + String stderr = installation.executables().pluginTool.run("remove " + pluginId).stderr(); assertThat( "Expected plugin installer to warn about migrated plugins", stderr, diff --git a/qa/os/src/test/java/org/elasticsearch/packaging/test/RpmMetadataTests.java b/qa/os/src/test/java/org/elasticsearch/packaging/test/RpmMetadataTests.java index cd46d62f09f8..b09a185e50ce 100644 --- a/qa/os/src/test/java/org/elasticsearch/packaging/test/RpmMetadataTests.java +++ b/qa/os/src/test/java/org/elasticsearch/packaging/test/RpmMetadataTests.java @@ -35,11 +35,11 @@ public class RpmMetadataTests extends PackagingTestCase { final Shell.Result deps = sh.run("rpm -qpR " + getDistributionFile(distribution())); - TestCase.assertTrue(Pattern.compile("(?m)^/bin/bash\\s*$").matcher(deps.stdout).find()); + TestCase.assertTrue(Pattern.compile("(?m)^/bin/bash\\s*$").matcher(deps.stdout()).find()); final Shell.Result conflicts = sh.run("rpm -qp --conflicts " + getDistributionFile(distribution())); String oppositePackageName = "elasticsearch-oss"; - TestCase.assertTrue(Pattern.compile("(?m)^" + oppositePackageName + "\\s*$").matcher(conflicts.stdout).find()); + TestCase.assertTrue(Pattern.compile("(?m)^" + oppositePackageName + "\\s*$").matcher(conflicts.stdout()).find()); } } diff --git a/qa/os/src/test/java/org/elasticsearch/packaging/test/RpmPreservationTests.java b/qa/os/src/test/java/org/elasticsearch/packaging/test/RpmPreservationTests.java index f81a2062b53e..19a9d9b74048 100644 --- a/qa/os/src/test/java/org/elasticsearch/packaging/test/RpmPreservationTests.java +++ b/qa/os/src/test/java/org/elasticsearch/packaging/test/RpmPreservationTests.java @@ -78,7 +78,7 @@ public class RpmPreservationTests extends PackagingTestCase { assertRemoved(distribution()); if (isSystemd()) { - assertThat(sh.runIgnoreExitCode("systemctl is-enabled elasticsearch.service").exitCode, is(1)); + assertThat(sh.runIgnoreExitCode("systemctl is-enabled elasticsearch.service").exitCode(), is(1)); } assertPathsDoNotExist( diff --git a/qa/os/src/test/java/org/elasticsearch/packaging/test/SqlCliTests.java b/qa/os/src/test/java/org/elasticsearch/packaging/test/SqlCliTests.java index 0180d3780305..b01f525a04fb 100644 --- a/qa/os/src/test/java/org/elasticsearch/packaging/test/SqlCliTests.java +++ b/qa/os/src/test/java/org/elasticsearch/packaging/test/SqlCliTests.java @@ -20,6 +20,6 @@ public class SqlCliTests extends PackagingTestCase { public void test020Help() throws Exception { Shell.Result result = installation.executables().sqlCli.run("--help"); - assertThat(result.stdout, containsString("Elasticsearch SQL CLI")); + assertThat(result.stdout(), containsString("Elasticsearch SQL CLI")); } } diff --git a/qa/os/src/test/java/org/elasticsearch/packaging/test/TemporaryDirectoryConfigTests.java b/qa/os/src/test/java/org/elasticsearch/packaging/test/TemporaryDirectoryConfigTests.java index 541458d20100..b6c898320cd0 100644 --- a/qa/os/src/test/java/org/elasticsearch/packaging/test/TemporaryDirectoryConfigTests.java +++ b/qa/os/src/test/java/org/elasticsearch/packaging/test/TemporaryDirectoryConfigTests.java @@ -103,7 +103,7 @@ public class TemporaryDirectoryConfigTests extends PackagingTestCase { distribution(), DockerRun.builder().volume(tmpDir, tmpDir).envVar("LIBFFI_TMPDIR", tmpFile.toString()) ); - assertThat(result.stderr, containsString("LIBFFI_TMPDIR")); + assertThat(result.stderr(), containsString("LIBFFI_TMPDIR")); } private void withLibffiTmpdir(String tmpDir, CheckedConsumer action) throws Exception { diff --git a/qa/os/src/test/java/org/elasticsearch/packaging/test/WindowsServiceTests.java b/qa/os/src/test/java/org/elasticsearch/packaging/test/WindowsServiceTests.java index 4877274222b9..1d61174318a1 100644 --- a/qa/os/src/test/java/org/elasticsearch/packaging/test/WindowsServiceTests.java +++ b/qa/os/src/test/java/org/elasticsearch/packaging/test/WindowsServiceTests.java @@ -50,9 +50,9 @@ public class WindowsServiceTests extends PackagingTestCase { private void assertService(String id, String status, String displayName) { Result result = sh.run("Get-Service " + id + " | Format-List -Property Name, Status, DisplayName"); - assertThat(result.stdout, containsString("Name : " + id)); - assertThat(result.stdout, containsString("Status : " + status)); - assertThat(result.stdout, containsString("DisplayName : " + displayName)); + assertThat(result.stdout(), containsString("Name : " + id)); + assertThat(result.stdout(), containsString("Status : " + status)); + assertThat(result.stdout(), containsString("DisplayName : " + displayName)); } // runs the service command, dumping all log files on failure @@ -69,8 +69,8 @@ public class WindowsServiceTests extends PackagingTestCase { } private void assertExit(Result result, String script, int exitCode) { - if (result.exitCode != exitCode) { - logger.error("---- Unexpected exit code (expected " + exitCode + ", got " + result.exitCode + ") for script: " + script); + if (result.exitCode() != exitCode) { + logger.error("---- Unexpected exit code (expected " + exitCode + ", got " + result.exitCode() + ") for script: " + script); logger.error(result); logger.error("Dumping log files\n"); Result logs = sh.run( @@ -83,10 +83,10 @@ public class WindowsServiceTests extends PackagingTestCase { + " Get-Content \"$file\" " + "}" ); - logger.error(logs.stdout); + logger.error(logs.stdout()); fail(); } else { - logger.info("\nscript: " + script + "\nstdout: " + result.stdout + "\nstderr: " + result.stderr); + logger.info("\nscript: " + script + "\nstdout: " + result.stdout() + "\nstderr: " + result.stderr()); } } @@ -102,8 +102,8 @@ public class WindowsServiceTests extends PackagingTestCase { Path tmpServiceExe = serviceExe.getParent().resolve(serviceExe.getFileName() + ".tmp"); Files.move(serviceExe, tmpServiceExe); Result result = sh.runIgnoreExitCode(serviceScript + " install"); - assertThat(result.exitCode, equalTo(1)); - assertThat(result.stdout, containsString("elasticsearch-service-x64.exe was not found...")); + assertThat(result.exitCode(), equalTo(1)); + assertThat(result.stdout(), containsString("elasticsearch-service-x64.exe was not found...")); Files.move(tmpServiceExe, serviceExe); } @@ -119,8 +119,8 @@ public class WindowsServiceTests extends PackagingTestCase { try { mv(installation.bundledJdk, relocatedJdk); Result result = sh.runIgnoreExitCode(serviceScript + " install"); - assertThat(result.exitCode, equalTo(1)); - assertThat(result.stderr, containsString("could not find java in bundled JDK")); + assertThat(result.exitCode(), equalTo(1)); + assertThat(result.stderr(), containsString("could not find java in bundled JDK")); } finally { mv(relocatedJdk, installation.bundledJdk); } @@ -129,13 +129,13 @@ public class WindowsServiceTests extends PackagingTestCase { public void test14InstallBadJavaHome() throws IOException { sh.getEnv().put("ES_JAVA_HOME", "doesnotexist"); Result result = sh.runIgnoreExitCode(serviceScript + " install"); - assertThat(result.exitCode, equalTo(1)); - assertThat(result.stderr, containsString("could not find java in ES_JAVA_HOME")); + assertThat(result.exitCode(), equalTo(1)); + assertThat(result.stderr(), containsString("could not find java in ES_JAVA_HOME")); } public void test15RemoveNotInstalled() { Result result = assertFailure(serviceScript + " remove", 1); - assertThat(result.stdout, containsString("Failed removing '" + DEFAULT_ID + "' service")); + assertThat(result.stdout(), containsString("Failed removing '" + DEFAULT_ID + "' service")); } public void test16InstallSpecialCharactersInJdkPath() throws IOException { @@ -146,7 +146,7 @@ public class WindowsServiceTests extends PackagingTestCase { try { mv(installation.bundledJdk, relocatedJdk); Result result = sh.run(serviceScript + " install"); - assertThat(result.stdout, containsString("The service 'elasticsearch-service-x64' has been installed.")); + assertThat(result.stdout(), containsString("The service 'elasticsearch-service-x64' has been installed.")); } finally { sh.runIgnoreExitCode(serviceScript + " remove"); mv(relocatedJdk, installation.bundledJdk); @@ -214,14 +214,14 @@ public class WindowsServiceTests extends PackagingTestCase { public void test31StartNotInstalled() throws IOException { Result result = sh.runIgnoreExitCode(serviceScript + " start"); - assertThat(result.stdout, result.exitCode, equalTo(1)); - assertThat(result.stdout, containsString("Failed starting '" + DEFAULT_ID + "' service")); + assertThat(result.stdout(), result.exitCode(), equalTo(1)); + assertThat(result.stdout(), containsString("Failed starting '" + DEFAULT_ID + "' service")); } public void test32StopNotStarted() throws IOException { sh.run(serviceScript + " install"); Result result = sh.run(serviceScript + " stop"); // stop is ok when not started - assertThat(result.stdout, containsString("The service '" + DEFAULT_ID + "' has been stopped")); + assertThat(result.stdout(), containsString("The service '" + DEFAULT_ID + "' has been stopped")); } public void test33JavaChanged() throws Exception { @@ -247,20 +247,20 @@ public class WindowsServiceTests extends PackagingTestCase { Files.write(fakeServiceMgr, Arrays.asList("echo \"Fake Service Manager GUI\"")); Shell sh = new Shell(); Result result = sh.run(serviceScript + " manager"); - assertThat(result.stdout, containsString("Fake Service Manager GUI")); + assertThat(result.stdout(), containsString("Fake Service Manager GUI")); // check failure too Files.write(fakeServiceMgr, Arrays.asList("echo \"Fake Service Manager GUI Failure\"", "exit 1")); result = sh.runIgnoreExitCode(serviceScript + " manager"); - TestCase.assertEquals(1, result.exitCode); - TestCase.assertTrue(result.stdout, result.stdout.contains("Fake Service Manager GUI Failure")); + TestCase.assertEquals(1, result.exitCode()); + TestCase.assertTrue(result.stdout(), result.stdout().contains("Fake Service Manager GUI Failure")); Files.move(tmpServiceMgr, serviceMgr); } public void test70UnknownCommand() { Result result = sh.runIgnoreExitCode(serviceScript + " bogus"); - assertThat(result.exitCode, equalTo(1)); - assertThat(result.stdout, containsString("Unknown option \"bogus\"")); + assertThat(result.exitCode(), equalTo(1)); + assertThat(result.stdout(), containsString("Unknown option \"bogus\"")); } public void test80JavaOptsInEnvVar() throws Exception { diff --git a/qa/os/src/test/java/org/elasticsearch/packaging/util/Packages.java b/qa/os/src/test/java/org/elasticsearch/packaging/util/Packages.java index e9cbf2403430..6d9cba73aa8f 100644 --- a/qa/os/src/test/java/org/elasticsearch/packaging/util/Packages.java +++ b/qa/os/src/test/java/org/elasticsearch/packaging/util/Packages.java @@ -51,23 +51,23 @@ public class Packages { public static void assertInstalled(Distribution distribution) throws Exception { final Result status = packageStatus(distribution); - assertThat(status.exitCode, is(0)); + assertThat(status.exitCode(), is(0)); - Platforms.onDPKG(() -> assertFalse(Pattern.compile("(?m)^Status:.+deinstall ok").matcher(status.stdout).find())); + Platforms.onDPKG(() -> assertFalse(Pattern.compile("(?m)^Status:.+deinstall ok").matcher(status.stdout()).find())); } public static void assertRemoved(Distribution distribution) throws Exception { final Result status = packageStatus(distribution); - Platforms.onRPM(() -> assertThat(status.exitCode, is(1))); + Platforms.onRPM(() -> assertThat(status.exitCode(), is(1))); Platforms.onDPKG(() -> { - assertThat(status.exitCode, anyOf(is(0), is(1))); - if (status.exitCode == 0) { + assertThat(status.exitCode(), anyOf(is(0), is(1))); + if (status.exitCode() == 0) { assertTrue( - "an uninstalled status should be indicated: " + status.stdout, - Pattern.compile("(?m)^Status:.+deinstall ok").matcher(status.stdout).find() - || Pattern.compile("(?m)^Status:.+ok not-installed").matcher(status.stdout).find() + "an uninstalled status should be indicated: " + status.stdout(), + Pattern.compile("(?m)^Status:.+deinstall ok").matcher(status.stdout()).find() + || Pattern.compile("(?m)^Status:.+ok not-installed").matcher(status.stdout()).find() ); } }); @@ -84,16 +84,16 @@ public class Packages { public static Installation installPackage(Shell sh, Distribution distribution, @Nullable Predicate outputPredicate) throws IOException { - String systemJavaHome = sh.run("echo $SYSTEM_JAVA_HOME").stdout.trim(); + String systemJavaHome = sh.run("echo $SYSTEM_JAVA_HOME").stdout().trim(); if (distribution.hasJdk == false) { sh.getEnv().put("ES_JAVA_HOME", systemJavaHome); } final Result result = runPackageManager(distribution, sh, PackageManagerCommand.INSTALL); - if (result.exitCode != 0) { + if (result.exitCode() != 0) { throw new RuntimeException("Installing distribution " + distribution + " failed: " + result); } if (null != outputPredicate) { - assertThat(outputPredicate.test(result.stdout), is(true)); + assertThat(outputPredicate.test(result.stdout()), is(true)); } Installation installation = Installation.ofPackage(sh, distribution); installation.setElasticPassword(captureElasticPasswordFromOutput(result)); @@ -109,7 +109,7 @@ public class Packages { } private static String captureElasticPasswordFromOutput(Result result) { - return Arrays.stream(result.stdout.split(System.lineSeparator())) + return Arrays.stream(result.stdout().split(System.lineSeparator())) .filter(l -> l.contains("The generated password for the elastic built-in superuser is : ")) .map(l -> l.substring(63, 83)) .findFirst() @@ -118,7 +118,7 @@ public class Packages { public static Installation upgradePackage(Shell sh, Distribution distribution) throws IOException { final Result result = runPackageManager(distribution, sh, PackageManagerCommand.UPGRADE); - if (result.exitCode != 0) { + if (result.exitCode() != 0) { throw new RuntimeException("Upgrading distribution " + distribution + " failed: " + result); } @@ -127,7 +127,7 @@ public class Packages { public static Installation forceUpgradePackage(Shell sh, Distribution distribution) throws IOException { final Result result = runPackageManager(distribution, sh, PackageManagerCommand.FORCE_UPGRADE); - if (result.exitCode != 0) { + if (result.exitCode() != 0) { throw new RuntimeException("Force upgrading distribution " + distribution + " failed: " + result); } @@ -145,9 +145,9 @@ public class Packages { } else { String debOptions = DEB_OPTIONS.get(command); Result r = sh.runIgnoreExitCode("dpkg " + debOptions + " " + distributionArg); - if (r.exitCode != 0) { + if (r.exitCode() != 0) { Result lockOF = sh.runIgnoreExitCode("lsof /var/lib/dpkg/lock"); - if (lockOF.exitCode == 0) { + if (lockOF.exitCode() == 0) { throw new RuntimeException("dpkg failed and the lockfile still exists. " + "Failure:\n" + r + "\nLockfile:\n" + lockOF); } } @@ -162,13 +162,13 @@ public class Packages { Platforms.onRPM(() -> { final Result status = packageStatus(distribution); - assertThat(status.exitCode, is(1)); + assertThat(status.exitCode(), is(1)); }); Platforms.onDPKG(() -> { final Result status = packageStatus(distribution); - assertThat(status.exitCode, is(0)); - assertTrue(Pattern.compile("(?m)^Status:.+deinstall ok").matcher(status.stdout).find()); + assertThat(status.exitCode(), is(0)); + assertTrue(Pattern.compile("(?m)^Status:.+deinstall ok").matcher(status.stdout()).find()); }); } @@ -183,7 +183,7 @@ public class Packages { sh.run("getent group elasticsearch"); final Result passwdResult = sh.run("getent passwd elasticsearch"); - final Path homeDir = Paths.get(passwdResult.stdout.trim().split(":")[5]); + final Path homeDir = Paths.get(passwdResult.stdout().trim().split(":")[5]); assertThat("elasticsearch user home directory must not exist", homeDir, fileDoesNotExist()); Stream.of(es.home, es.plugins, es.modules).forEach(dir -> assertThat(dir, file(Directory, "root", "root", p755))); @@ -192,19 +192,19 @@ public class Packages { // we shell out here because java's posix file permission view doesn't support special modes assertThat(es.config, file(Directory, "root", "elasticsearch", p750)); - assertThat(sh.run("find \"" + es.config + "\" -maxdepth 0 -printf \"%m\"").stdout, containsString("2750")); + assertThat(sh.run("find \"" + es.config + "\" -maxdepth 0 -printf \"%m\"").stdout(), containsString("2750")); // We introduced the jvm.options.d folder in 7.7 if (Version.fromString(distribution.baseVersion).onOrAfter(Version.V_7_7_0)) { final Path jvmOptionsDirectory = es.config.resolve("jvm.options.d"); assertThat(jvmOptionsDirectory, file(Directory, "root", "elasticsearch", p750)); - assertThat(sh.run("find \"" + jvmOptionsDirectory + "\" -maxdepth 0 -printf \"%m\"").stdout, containsString("2750")); + assertThat(sh.run("find \"" + jvmOptionsDirectory + "\" -maxdepth 0 -printf \"%m\"").stdout(), containsString("2750")); } Stream.of("elasticsearch.keystore", "elasticsearch.yml", "jvm.options", "log4j2.properties") .forEach(configFile -> assertThat(es.config(configFile), file(File, "root", "elasticsearch", p660))); - assertThat(sh.run("sudo -u elasticsearch " + es.bin("elasticsearch-keystore") + " list").stdout, containsString("keystore.seed")); + assertThat(sh.run("sudo -u elasticsearch " + es.bin("elasticsearch-keystore") + " list").stdout(), containsString("keystore.seed")); Stream.of(es.bin, es.lib).forEach(dir -> assertThat(dir, file(Directory, "root", "root", p755))); @@ -218,7 +218,7 @@ public class Packages { if (distribution.packaging == Distribution.Packaging.RPM) { assertThat(es.home.resolve("LICENSE.txt"), file(File, "root", "root", p644)); } else { - Path copyrightDir = Paths.get(sh.run("readlink -f /usr/share/doc/elasticsearch").stdout.trim()); + Path copyrightDir = Paths.get(sh.run("readlink -f /usr/share/doc/elasticsearch").stdout().trim()); assertThat(copyrightDir, file(Directory, "root", "root", p755)); assertThat(copyrightDir.resolve("copyright"), file(File, "root", "root", p644)); } @@ -231,7 +231,7 @@ public class Packages { ).forEach(confFile -> assertThat(confFile, file(File, "root", "root", p644))); final String sysctlExecutable = (distribution.packaging == Distribution.Packaging.RPM) ? "/usr/sbin/sysctl" : "/sbin/sysctl"; - assertThat(sh.run(sysctlExecutable + " vm.max_map_count").stdout, containsString("vm.max_map_count = 262144")); + assertThat(sh.run(sysctlExecutable + " vm.max_map_count").stdout(), containsString("vm.max_map_count = 262144")); } } @@ -271,8 +271,8 @@ public class Packages { sh.run("systemctl is-enabled elasticsearch.service"); Result exitCode = sh.runIgnoreExitCode("systemctl start elasticsearch.service"); if (exitCode.isSuccess() == false) { - logger.warn(sh.runIgnoreExitCode("systemctl status elasticsearch.service").stdout); - logger.warn(journald.getLogs().stdout); + logger.warn(sh.runIgnoreExitCode("systemctl status elasticsearch.service").stdout()); + logger.warn(journald.getLogs().stdout()); } return exitCode; } @@ -332,7 +332,7 @@ public class Packages { */ public void clear() { final String script = "sudo journalctl --unit=elasticsearch.service --lines=0 --show-cursor -o cat | sed -e 's/-- cursor: //'"; - cursor = sh.run(script).stdout.trim(); + cursor = sh.run(script).stdout().trim(); } /** diff --git a/qa/os/src/test/java/org/elasticsearch/packaging/util/ProcessInfo.java b/qa/os/src/test/java/org/elasticsearch/packaging/util/ProcessInfo.java index 1b928a447e3c..91fd00d86e2b 100644 --- a/qa/os/src/test/java/org/elasticsearch/packaging/util/ProcessInfo.java +++ b/qa/os/src/test/java/org/elasticsearch/packaging/util/ProcessInfo.java @@ -22,27 +22,15 @@ import static org.hamcrest.Matchers.hasSize; * works in Linux containers. At the moment that isn't a problem, because we only publish Docker images * for Linux. */ -public class ProcessInfo { - public final int pid; - public final int uid; - public final int gid; - public final String username; - public final String group; - - public ProcessInfo(int pid, int uid, int gid, String username, String group) { - this.pid = pid; - this.uid = uid; - this.gid = gid; - this.username = username; - this.group = group; - } +public record ProcessInfo(int pid, int uid, int gid, String username, String group) { /** * Fetches process information about command, using sh to execute commands. + * * @return a populated ProcessInfo object */ public static ProcessInfo getProcessInfo(Shell sh, String command) { - final List processes = sh.run("pgrep " + command).stdout.lines().collect(Collectors.toList()); + final List processes = sh.run("pgrep " + command).stdout().lines().collect(Collectors.toList()); assertThat("Expected a single process", processes, hasSize(1)); @@ -52,7 +40,7 @@ public class ProcessInfo { int uid = -1; int gid = -1; - for (String line : sh.run("cat /proc/" + pid + "/status | grep '^[UG]id:'").stdout.split("\\n")) { + for (String line : sh.run("cat /proc/" + pid + "/status | grep '^[UG]id:'").stdout().split("\\n")) { final String[] fields = line.split("\\s+"); if (fields[0].equals("Uid:")) { @@ -62,8 +50,8 @@ public class ProcessInfo { } } - final String username = sh.run("getent passwd " + uid + " | cut -f1 -d:").stdout.trim(); - final String group = sh.run("getent group " + gid + " | cut -f1 -d:").stdout.trim(); + final String username = sh.run("getent passwd " + uid + " | cut -f1 -d:").stdout().trim(); + final String group = sh.run("getent group " + gid + " | cut -f1 -d:").stdout().trim(); return new ProcessInfo(pid, uid, gid, username, group); } diff --git a/qa/os/src/test/java/org/elasticsearch/packaging/util/ServerUtils.java b/qa/os/src/test/java/org/elasticsearch/packaging/util/ServerUtils.java index fc66993cc188..04c0f305ce2e 100644 --- a/qa/os/src/test/java/org/elasticsearch/packaging/util/ServerUtils.java +++ b/qa/os/src/test/java/org/elasticsearch/packaging/util/ServerUtils.java @@ -77,7 +77,9 @@ public class ServerUtils { String configFile = Files.readString(configFilePath, StandardCharsets.UTF_8); securityEnabled = configFile.contains(SECURITY_DISABLED) == false; } else { - final Optional commandLine = dockerShell.run("bash -c 'COLUMNS=2000 ps ax'").stdout.lines() + final Optional commandLine = dockerShell.run("bash -c 'COLUMNS=2000 ps ax'") + .stdout() + .lines() .filter(line -> line.contains("org.elasticsearch.bootstrap.Elasticsearch")) .findFirst(); if (commandLine.isPresent() == false) { diff --git a/qa/os/src/test/java/org/elasticsearch/packaging/util/Shell.java b/qa/os/src/test/java/org/elasticsearch/packaging/util/Shell.java index 86cf22c1df1d..de3cc90ad50c 100644 --- a/qa/os/src/test/java/org/elasticsearch/packaging/util/Shell.java +++ b/qa/os/src/test/java/org/elasticsearch/packaging/util/Shell.java @@ -228,21 +228,13 @@ public class Shell { return String.format(Locale.ROOT, " env = [%s] workingDirectory = [%s]", env, workingDirectory); } - public static class Result { - public final int exitCode; - public final String stdout; - public final String stderr; - - public Result(int exitCode, String stdout, String stderr) { - this.exitCode = exitCode; - this.stdout = stdout; - this.stderr = stderr; - } + public record Result(int exitCode, String stdout, String stderr) { public boolean isSuccess() { return exitCode == 0; } + @Override public String toString() { return String.format(Locale.ROOT, "exitCode = [%d] stdout = [%s] stderr = [%s]", exitCode, stdout.trim(), stderr.trim()); } diff --git a/qa/os/src/test/java/org/elasticsearch/packaging/util/docker/Docker.java b/qa/os/src/test/java/org/elasticsearch/packaging/util/docker/Docker.java index 02fc0e961b89..c6e90859324c 100644 --- a/qa/os/src/test/java/org/elasticsearch/packaging/util/docker/Docker.java +++ b/qa/os/src/test/java/org/elasticsearch/packaging/util/docker/Docker.java @@ -83,7 +83,7 @@ public class Docker { * @param distribution details about the docker image to potentially load. */ public static void ensureImageIsLoaded(Distribution distribution) { - final long count = sh.run("docker image ls --format '{{.Repository}}' " + getImageName(distribution)).stdout.lines().count(); + final long count = sh.run("docker image ls --format '{{.Repository}}' " + getImageName(distribution)).stdout().lines().count(); if (count != 0) { return; @@ -136,7 +136,7 @@ public class Docker { .extraArgs("--publish", transportPort + ":9300", "--publish", restPort + ":9200") .build(); logger.info("Running command: " + command); - containerId = sh.run(command).stdout.trim(); + containerId = sh.run(command).stdout().trim(); waitForElasticsearchToStart(); return Installation.ofContainer(dockerShell, distribution, restPort); } @@ -163,7 +163,7 @@ public class Docker { final String command = builder.distribution(distribution).build(); logger.info("Running command: " + command); - containerId = sh.run(command).stdout.trim(); + containerId = sh.run(command).stdout().trim(); } /** @@ -182,7 +182,7 @@ public class Docker { Thread.sleep(STARTUP_SLEEP_INTERVAL_MILLISECONDS); // Set COLUMNS so that `ps` doesn't truncate its output - psOutput = dockerShell.run("bash -c 'COLUMNS=2000 ps ax'").stdout; + psOutput = dockerShell.run("bash -c 'COLUMNS=2000 ps ax'").stdout(); if (psOutput.contains("org.elasticsearch.bootstrap.Elasticsearch")) { isElasticsearchRunning = true; @@ -201,12 +201,12 @@ public class Docker { ps output: %s - Stdout: + stdout(): %s Stderr: %s\ - """.formatted(psOutput, dockerLogs.stdout, dockerLogs.stderr)); + """.formatted(psOutput, dockerLogs.stdout(), dockerLogs.stderr())); } } @@ -222,7 +222,7 @@ public class Docker { // Give the container a chance to exit out Thread.sleep(2000); - if (sh.run("docker ps --quiet --no-trunc").stdout.contains(containerId) == false) { + if (sh.run("docker ps --quiet --no-trunc").stdout().contains(containerId) == false) { isElasticsearchRunning = false; break; } @@ -236,12 +236,12 @@ public class Docker { fail(""" Elasticsearch container didn't exit. - Stdout: + stdout(): %s Stderr: %s\ - """.formatted(dockerLogs.stdout, dockerLogs.stderr)); + """.formatted(dockerLogs.stdout(), dockerLogs.stderr())); } } @@ -256,8 +256,8 @@ public class Docker { final Shell.Result result = sh.runIgnoreExitCode(command); if (result.isSuccess() == false) { - boolean isErrorAcceptable = result.stderr.contains("removal of container " + containerId + " is already in progress") - || result.stderr.contains("Error: No such container: " + containerId); + boolean isErrorAcceptable = result.stderr().contains("removal of container " + containerId + " is already in progress") + || result.stderr().contains("Error: No such container: " + containerId); // I'm not sure why we're already removing this container, but that's OK. if (isErrorAcceptable == false) { @@ -327,8 +327,8 @@ public class Docker { logger.debug("Trying to look for " + pattern + " ( " + type + ") in " + base + " in the container"); final String script = "docker exec " + containerId + " find " + base + " -type " + type + " -iname " + pattern; final Shell.Result result = sh.run(script); - if (result.isSuccess() && Strings.isNullOrEmpty(result.stdout) == false) { - String path = result.stdout; + if (result.isSuccess() && Strings.isNullOrEmpty(result.stdout()) == false) { + String path = result.stdout(); if (path.split(System.lineSeparator()).length > 1) { path = path.split(System.lineSeparator())[1]; } @@ -454,7 +454,7 @@ public class Docker { dockerShell.run("getent group elasticsearch"); final Shell.Result passwdResult = dockerShell.run("getent passwd elasticsearch"); - final String homeDir = passwdResult.stdout.trim().split(":")[5]; + final String homeDir = passwdResult.stdout().trim().split(":")[5]; assertThat("elasticsearch user's home directory is incorrect", homeDir, equalTo("/usr/share/elasticsearch")); assertThat(es.home, file(Directory, "root", "root", p775)); @@ -467,7 +467,7 @@ public class Docker { Stream.of(es.bin, es.config, es.logs, es.config.resolve("jvm.options.d"), es.data, es.plugins) .forEach(dir -> assertThat(dir, file(Directory, "elasticsearch", "root", p775))); - final String arch = dockerShell.run("arch").stdout.trim(); + final String arch = dockerShell.run("arch").stdout().trim(); Stream.of(es.bin, es.bundledJdk.resolve("bin"), es.modules.resolve("x-pack-ml/platform/linux-" + arch + "/bin")) .forEach( @@ -485,7 +485,7 @@ public class Docker { Stream.of("LICENSE.txt", "NOTICE.txt", "README.asciidoc") .forEach(doc -> assertThat(es.home.resolve(doc), file("root", "root", p444))); - assertThat(dockerShell.run(es.bin("elasticsearch-keystore") + " list").stdout, containsString("keystore.seed")); + assertThat(dockerShell.run(es.bin("elasticsearch-keystore") + " list").stdout(), containsString("keystore.seed")); // nc is useful for checking network issues // zip/unzip are installed to help users who are working with certificates. @@ -570,7 +570,7 @@ public class Docker { r.run(); } catch (Exception e) { final Shell.Result logs = getContainerLogs(); - logger.warn("Elasticsearch container failed to start.\n\nStdout:\n" + logs.stdout + "\n\nStderr:\n" + logs.stderr); + logger.warn("Elasticsearch container failed to start.\n\nStdout:\n" + logs.stdout() + "\n\nStderr:\n" + logs.stderr()); throw e; } } @@ -671,7 +671,7 @@ public class Docker { } private static JsonNode getImageInspectionJson(Distribution distribution) throws Exception { - String labelsJson = sh.run("docker inspect " + getImageName(distribution)).stdout; + String labelsJson = sh.run("docker inspect " + getImageName(distribution)).stdout(); ObjectMapper mapper = new ObjectMapper(); return mapper.readTree(labelsJson).get(0); } @@ -693,7 +693,7 @@ public class Docker { throw new FileNotFoundException(path + " does not exist"); } - final String[] components = result.stdout.split("\\s+"); + final String[] components = result.stdout().split("\\s+"); final String permissions = components[2]; final String fileType = permissions.substring(0, 1); @@ -718,7 +718,7 @@ public class Docker { * @return the listing */ public static List listContents(String path) { - return dockerShell.run("ls -1 --color=never " + path).stdout.lines().collect(Collectors.toList()); + return dockerShell.run("ls -1 --color=never " + path).stdout().lines().collect(Collectors.toList()); } public static List listContents(Path path) { diff --git a/qa/os/src/test/java/org/elasticsearch/packaging/util/docker/DockerShell.java b/qa/os/src/test/java/org/elasticsearch/packaging/util/docker/DockerShell.java index a7b752860d07..0847302f1c40 100644 --- a/qa/os/src/test/java/org/elasticsearch/packaging/util/docker/DockerShell.java +++ b/qa/os/src/test/java/org/elasticsearch/packaging/util/docker/DockerShell.java @@ -53,8 +53,8 @@ public class DockerShell extends Shell { logger.error( "Command [{}] failed.\n\nContainer stdout: [{}]\n\nContainer stderr: [{}]", script, - dockerLogs.stdout, - dockerLogs.stderr + dockerLogs.stdout(), + dockerLogs.stderr() ); } catch (ShellException shellException) { logger.error( diff --git a/qa/os/src/test/java/org/elasticsearch/packaging/util/docker/MockServer.java b/qa/os/src/test/java/org/elasticsearch/packaging/util/docker/MockServer.java index 94d8ee83b790..d2c43e478df8 100644 --- a/qa/os/src/test/java/org/elasticsearch/packaging/util/docker/MockServer.java +++ b/qa/os/src/test/java/org/elasticsearch/packaging/util/docker/MockServer.java @@ -85,7 +85,7 @@ public class MockServer { private void start() throws Exception { final String command = "docker run -t --detach --rm -p " + CONTAINER_PORT + ":" + CONTAINER_PORT + " mockserver/mockserver:latest"; - this.containerId = this.shell.run(command).stdout.trim(); + this.containerId = this.shell.run(command).stdout().trim(); // It's a Java app, so give it a chance to wake up. I'd add a healthcheck to the above command, // but the image doesn't have any CLI utils at all. diff --git a/qa/smoke-test-http/src/test/java/org/elasticsearch/http/DanglingIndicesRestIT.java b/qa/smoke-test-http/src/test/java/org/elasticsearch/http/DanglingIndicesRestIT.java index d4d214726114..6880c558cc4d 100644 --- a/qa/smoke-test-http/src/test/java/org/elasticsearch/http/DanglingIndicesRestIT.java +++ b/qa/smoke-test-http/src/test/java/org/elasticsearch/http/DanglingIndicesRestIT.java @@ -292,13 +292,5 @@ public class DanglingIndicesRestIT extends HttpSmokeTestCase { return new DanglingIndexDetails(stoppedNodeName.get(), indexToUUID); } - private static class DanglingIndexDetails { - private final String stoppedNodeName; - private final Map indexToUUID; - - DanglingIndexDetails(String stoppedNodeName, Map indexToUUID) { - this.stoppedNodeName = stoppedNodeName; - this.indexToUUID = indexToUUID; - } - } + private record DanglingIndexDetails(String stoppedNodeName, Map indexToUUID) {} } diff --git a/server/src/internalClusterTest/java/org/elasticsearch/index/engine/MaxDocsLimitIT.java b/server/src/internalClusterTest/java/org/elasticsearch/index/engine/MaxDocsLimitIT.java index 065754cae124..0f0588d83fe6 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/index/engine/MaxDocsLimitIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/index/engine/MaxDocsLimitIT.java @@ -156,15 +156,7 @@ public class MaxDocsLimitIT extends ESIntegTestCase { assertThat(searchResponse.getHits().getTotalHits().value, equalTo((long) totalSuccess)); } - static final class IndexingResult { - final int numSuccess; - final int numFailures; - - IndexingResult(int numSuccess, int numFailures) { - this.numSuccess = numSuccess; - this.numFailures = numFailures; - } - } + record IndexingResult(int numSuccess, int numFailures) {} static IndexingResult indexDocs(int numRequests, int numThreads) throws Exception { final AtomicInteger completedRequests = new AtomicInteger(); diff --git a/server/src/internalClusterTest/java/org/elasticsearch/versioning/ConcurrentSeqNoVersioningIT.java b/server/src/internalClusterTest/java/org/elasticsearch/versioning/ConcurrentSeqNoVersioningIT.java index 3e3280c9e479..b71500b73edd 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/versioning/ConcurrentSeqNoVersioningIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/versioning/ConcurrentSeqNoVersioningIT.java @@ -493,36 +493,11 @@ public class ConcurrentSeqNoVersioningIT extends AbstractDisruptionTestCase { } } - private static final class State { - private final Version safeVersion; - private final boolean lastFailed; - - private State(Version safeVersion, boolean lastFailed) { - this.safeVersion = safeVersion; - this.lastFailed = lastFailed; - } + private record State(Version safeVersion, boolean lastFailed) { public State failed() { return lastFailed ? this : casFail(safeVersion); } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - State that = (State) o; - return lastFailed == that.lastFailed && safeVersion.equals(that.safeVersion); - } - - @Override - public int hashCode() { - return Objects.hash(safeVersion, lastFailed); - } - - @Override - public String toString() { - return "State{" + "safeVersion=" + safeVersion + ", lastFailed=" + lastFailed + '}'; - } } private static State casFail(Version stateVersion) { @@ -688,9 +663,9 @@ public class ConcurrentSeqNoVersioningIT extends AbstractDisruptionTestCase { } private static void writeEvent(LinearizabilityChecker.Event event, BytesStreamOutput output) throws IOException { - output.writeEnum(event.type); - output.writeNamedWriteable((NamedWriteable) event.value); - output.writeInt(event.id); + output.writeEnum(event.type()); + output.writeNamedWriteable((NamedWriteable) event.value()); + output.writeInt(event.id()); } private static LinearizabilityChecker.Event readEvent(StreamInput input) throws IOException { diff --git a/server/src/main/java/org/elasticsearch/action/support/ActiveShardCount.java b/server/src/main/java/org/elasticsearch/action/support/ActiveShardCount.java index 226515ac944f..e58bec22ee9b 100644 --- a/server/src/main/java/org/elasticsearch/action/support/ActiveShardCount.java +++ b/server/src/main/java/org/elasticsearch/action/support/ActiveShardCount.java @@ -25,7 +25,7 @@ import static org.elasticsearch.cluster.metadata.IndexMetadata.SETTING_WAIT_FOR_ * A class whose instances represent a value for counting the number * of active shard copies for a given shard in an index. */ -public final class ActiveShardCount implements Writeable { +public record ActiveShardCount(int value) implements Writeable { private static final int ACTIVE_SHARD_COUNT_DEFAULT = -2; private static final int ALL_ACTIVE_SHARDS = -1; @@ -35,12 +35,6 @@ public final class ActiveShardCount implements Writeable { public static final ActiveShardCount NONE = new ActiveShardCount(0); public static final ActiveShardCount ONE = new ActiveShardCount(1); - private final int value; - - private ActiveShardCount(final int value) { - this.value = value; - } - /** * Get an ActiveShardCount instance for the given value. The value is first validated to ensure * it is a valid shard count and throws an IllegalArgumentException if validation fails. Valid @@ -187,23 +181,6 @@ public final class ActiveShardCount implements Writeable { } } - @Override - public int hashCode() { - return Integer.hashCode(value); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ActiveShardCount that = (ActiveShardCount) o; - return value == that.value; - } - @Override public String toString() { return switch (value) { diff --git a/server/src/main/java/org/elasticsearch/common/ParsingException.java b/server/src/main/java/org/elasticsearch/common/ParsingException.java index 8d029c873b6e..225600454a80 100644 --- a/server/src/main/java/org/elasticsearch/common/ParsingException.java +++ b/server/src/main/java/org/elasticsearch/common/ParsingException.java @@ -38,8 +38,8 @@ public class ParsingException extends ElasticsearchException { int lineNumber = UNKNOWN_POSITION; int columnNumber = UNKNOWN_POSITION; if (contentLocation != null) { - lineNumber = contentLocation.lineNumber; - columnNumber = contentLocation.columnNumber; + lineNumber = contentLocation.lineNumber(); + columnNumber = contentLocation.columnNumber(); } this.columnNumber = columnNumber; this.lineNumber = lineNumber; diff --git a/server/src/main/java/org/elasticsearch/common/settings/AbstractScopedSettings.java b/server/src/main/java/org/elasticsearch/common/settings/AbstractScopedSettings.java index 74ef42fb5ab6..4e7e13cd38fe 100644 --- a/server/src/main/java/org/elasticsearch/common/settings/AbstractScopedSettings.java +++ b/server/src/main/java/org/elasticsearch/common/settings/AbstractScopedSettings.java @@ -959,15 +959,7 @@ public abstract class AbstractScopedSettings { } } - private static final class Entry implements Map.Entry { - - private final String key; - private final Settings settings; - - private Entry(String key, Settings settings) { - this.key = key; - this.settings = settings; - } + private record Entry(String key, Settings settings) implements Map.Entry { @Override public String getKey() { diff --git a/server/src/main/java/org/elasticsearch/common/settings/Settings.java b/server/src/main/java/org/elasticsearch/common/settings/Settings.java index 604b7f20fa3d..133caa296f07 100644 --- a/server/src/main/java/org/elasticsearch/common/settings/Settings.java +++ b/server/src/main/java/org/elasticsearch/common/settings/Settings.java @@ -653,16 +653,16 @@ public final class Settings implements ToXContentFragment { "malformed, expected end of settings but encountered additional content starting at line number: [{}], " + "column number: [{}]", e, - parser.getTokenLocation().lineNumber, - parser.getTokenLocation().columnNumber + parser.getTokenLocation().lineNumber(), + parser.getTokenLocation().columnNumber() ); } if (lastToken != null) { throw new ElasticsearchParseException( "malformed, expected end of settings but encountered additional content starting at line number: [{}], " + "column number: [{}]", - parser.getTokenLocation().lineNumber, - parser.getTokenLocation().columnNumber + parser.getTokenLocation().lineNumber(), + parser.getTokenLocation().columnNumber() ); } } @@ -720,8 +720,8 @@ public final class Settings implements ToXContentFragment { throw new ElasticsearchParseException( "null-valued setting found for key [{}] found at line number [{}], column number [{}]", key, - parser.getTokenLocation().lineNumber, - parser.getTokenLocation().columnNumber + parser.getTokenLocation().lineNumber(), + parser.getTokenLocation().columnNumber() ); } } diff --git a/server/src/main/java/org/elasticsearch/search/SearchParseException.java b/server/src/main/java/org/elasticsearch/search/SearchParseException.java index e9455aec7792..8f687e238ceb 100644 --- a/server/src/main/java/org/elasticsearch/search/SearchParseException.java +++ b/server/src/main/java/org/elasticsearch/search/SearchParseException.java @@ -33,8 +33,8 @@ public class SearchParseException extends SearchException { int columnNumber = UNKNOWN_POSITION; if (location != null) { if (location != null) { - lineNumber = location.lineNumber; - columnNumber = location.columnNumber; + lineNumber = location.lineNumber(); + columnNumber = location.columnNumber(); } } this.columnNumber = columnNumber; diff --git a/server/src/main/java/org/elasticsearch/search/aggregations/Aggregator.java b/server/src/main/java/org/elasticsearch/search/aggregations/Aggregator.java index ef3baa6be317..47153df47ede 100644 --- a/server/src/main/java/org/elasticsearch/search/aggregations/Aggregator.java +++ b/server/src/main/java/org/elasticsearch/search/aggregations/Aggregator.java @@ -77,7 +77,7 @@ public abstract class Aggregator extends BucketCollector implements Releasable { * aggregation. */ public final Aggregator resolveSortPathOnValidAgg(AggregationPath.PathElement next, Iterator path) { - Aggregator n = subAggregator(next.name); + Aggregator n = subAggregator(next.name()); if (n == null) { throw new IllegalArgumentException( "The provided aggregation [" @@ -89,7 +89,7 @@ public abstract class Aggregator extends BucketCollector implements Releasable { if (false == path.hasNext()) { return n; } - if (next.key != null) { + if (next.key() != null) { throw new IllegalArgumentException("Key only allowed on last aggregation path element but got [" + next + "]"); } return n.resolveSortPath(path.next(), path); diff --git a/server/src/main/java/org/elasticsearch/search/aggregations/AggregatorFactories.java b/server/src/main/java/org/elasticsearch/search/aggregations/AggregatorFactories.java index 1f7ff660310e..404ff44487d8 100644 --- a/server/src/main/java/org/elasticsearch/search/aggregations/AggregatorFactories.java +++ b/server/src/main/java/org/elasticsearch/search/aggregations/AggregatorFactories.java @@ -438,14 +438,14 @@ public class AggregatorFactories { String[] bucketsPaths = builder.getBucketsPaths(); for (String bucketsPath : bucketsPaths) { List bucketsPathElements = AggregationPath.parse(bucketsPath).getPathElements(); - String firstAggName = bucketsPathElements.get(0).name; + String firstAggName = bucketsPathElements.get(0).name(); if (bucketsPath.equals("_count") || bucketsPath.equals("_key")) { continue; } else if (aggBuildersMap.containsKey(firstAggName)) { AggregationBuilder aggBuilder = aggBuildersMap.get(firstAggName); for (int i = 1; i < bucketsPathElements.size(); i++) { PathElement pathElement = bucketsPathElements.get(i); - String aggName = pathElement.name; + String aggName = pathElement.name(); if ((i == bucketsPathElements.size() - 1) && (aggName.equalsIgnoreCase("_key") || aggName.equals("_count"))) { break; } else { diff --git a/server/src/main/java/org/elasticsearch/search/aggregations/InternalAggregations.java b/server/src/main/java/org/elasticsearch/search/aggregations/InternalAggregations.java index 9fecc4f29399..166a4fc8d9e1 100644 --- a/server/src/main/java/org/elasticsearch/search/aggregations/InternalAggregations.java +++ b/server/src/main/java/org/elasticsearch/search/aggregations/InternalAggregations.java @@ -80,14 +80,14 @@ public final class InternalAggregations extends Aggregations implements Writeabl * Get value to use when sorting by a descendant of the aggregation containing this. */ public double sortValue(AggregationPath.PathElement head, Iterator tail) { - InternalAggregation aggregation = get(head.name); + InternalAggregation aggregation = get(head.name()); if (aggregation == null) { - throw new IllegalArgumentException("Cannot find aggregation named [" + head.name + "]"); + throw new IllegalArgumentException("Cannot find aggregation named [" + head.name() + "]"); } if (tail.hasNext()) { return aggregation.sortValue(tail.next(), tail); } - return aggregation.sortValue(head.key); + return aggregation.sortValue(head.key()); } /** diff --git a/server/src/main/java/org/elasticsearch/search/aggregations/support/AggregationPath.java b/server/src/main/java/org/elasticsearch/search/aggregations/support/AggregationPath.java index 6f7da696cf2b..5f8feb785193 100644 --- a/server/src/main/java/org/elasticsearch/search/aggregations/support/AggregationPath.java +++ b/server/src/main/java/org/elasticsearch/search/aggregations/support/AggregationPath.java @@ -103,17 +103,7 @@ public class AggregationPath { return new AggregationPath(tokens); } - public static class PathElement { - - private final String fullName; - public final String name; - public final String key; - - public PathElement(String fullName, String name, String key) { - this.fullName = fullName; - this.name = name; - this.key = key; - } + public record PathElement(String fullName, String name, String key) { @Override public boolean equals(Object o) { @@ -121,7 +111,6 @@ public class AggregationPath { if (o == null || getClass() != o.getClass()) return false; PathElement token = (PathElement) o; - return Objects.equals(key, token.key) && Objects.equals(name, token.name); } diff --git a/server/src/test/java/org/elasticsearch/action/admin/indices/close/TransportVerifyShardBeforeCloseActionTests.java b/server/src/test/java/org/elasticsearch/action/admin/indices/close/TransportVerifyShardBeforeCloseActionTests.java index f16045a47604..51db5b4f7c64 100644 --- a/server/src/test/java/org/elasticsearch/action/admin/indices/close/TransportVerifyShardBeforeCloseActionTests.java +++ b/server/src/test/java/org/elasticsearch/action/admin/indices/close/TransportVerifyShardBeforeCloseActionTests.java @@ -274,22 +274,22 @@ public class TransportVerifyShardBeforeCloseActionTests extends ESTestCase { assertThat(capturedRequests.length, equalTo(nbReplicas)); for (CapturingTransport.CapturedRequest capturedRequest : capturedRequests) { - final String actionName = capturedRequest.action; + final String actionName = capturedRequest.action(); if (actionName.startsWith(ShardStateAction.SHARD_FAILED_ACTION_NAME)) { - assertThat(capturedRequest.request, instanceOf(ShardStateAction.FailedShardEntry.class)); - String allocationId = ((ShardStateAction.FailedShardEntry) capturedRequest.request).getAllocationId(); + assertThat(capturedRequest.request(), instanceOf(ShardStateAction.FailedShardEntry.class)); + String allocationId = ((ShardStateAction.FailedShardEntry) capturedRequest.request()).getAllocationId(); assertTrue(unavailableShards.stream().anyMatch(shardRouting -> shardRouting.allocationId().getId().equals(allocationId))); - transport.handleResponse(capturedRequest.requestId, TransportResponse.Empty.INSTANCE); + transport.handleResponse(capturedRequest.requestId(), TransportResponse.Empty.INSTANCE); } else if (actionName.startsWith(TransportVerifyShardBeforeCloseAction.NAME)) { - assertThat(capturedRequest.request, instanceOf(ConcreteShardRequest.class)); - String allocationId = ((ConcreteShardRequest) capturedRequest.request).getTargetAllocationID(); + assertThat(capturedRequest.request(), instanceOf(ConcreteShardRequest.class)); + String allocationId = ((ConcreteShardRequest) capturedRequest.request()).getTargetAllocationID(); assertFalse(unavailableShards.stream().anyMatch(shardRouting -> shardRouting.allocationId().getId().equals(allocationId))); assertTrue(inSyncAllocationIds.stream().anyMatch(inSyncAllocationId -> inSyncAllocationId.equals(allocationId))); - transport.handleResponse(capturedRequest.requestId, new TransportReplicationAction.ReplicaResponse(0L, 0L)); + transport.handleResponse(capturedRequest.requestId(), new TransportReplicationAction.ReplicaResponse(0L, 0L)); } else { - fail("Test does not support action " + capturedRequest.action); + fail("Test does not support action " + capturedRequest.action()); } } diff --git a/server/src/test/java/org/elasticsearch/action/support/broadcast/node/TransportBroadcastByNodeActionTests.java b/server/src/test/java/org/elasticsearch/action/support/broadcast/node/TransportBroadcastByNodeActionTests.java index 7a5d8ef0b8e7..948288fe0628 100644 --- a/server/src/test/java/org/elasticsearch/action/support/broadcast/node/TransportBroadcastByNodeActionTests.java +++ b/server/src/test/java/org/elasticsearch/action/support/broadcast/node/TransportBroadcastByNodeActionTests.java @@ -498,7 +498,7 @@ public class TransportBroadcastByNodeActionTests extends ESTestCase { int totalFailedShards = 0; for (Map.Entry> entry : capturedRequests.entrySet()) { List exceptions = new ArrayList<>(); - long requestId = entry.getValue().get(0).requestId; + long requestId = entry.getValue().get(0).requestId(); if (rarely()) { // simulate node failure totalShards += map.get(entry.getKey()).size(); @@ -541,7 +541,7 @@ public class TransportBroadcastByNodeActionTests extends ESTestCase { Map> capturedRequests = transport.getCapturedRequestsByTargetNodeAndClear(); for (Map.Entry> entry : capturedRequests.entrySet()) { - transport.handleRemoteError(entry.getValue().get(0).requestId, new ElasticsearchException("simulated")); + transport.handleRemoteError(entry.getValue().get(0).requestId(), new ElasticsearchException("simulated")); } assertTrue(listener.isDone()); diff --git a/server/src/test/java/org/elasticsearch/action/support/master/TransportMasterNodeActionTests.java b/server/src/test/java/org/elasticsearch/action/support/master/TransportMasterNodeActionTests.java index d37a4adf3f0c..02a505e6c05f 100644 --- a/server/src/test/java/org/elasticsearch/action/support/master/TransportMasterNodeActionTests.java +++ b/server/src/test/java/org/elasticsearch/action/support/master/TransportMasterNodeActionTests.java @@ -420,12 +420,12 @@ public class TransportMasterNodeActionTests extends ESTestCase { assertThat(transport.capturedRequests().length, equalTo(1)); CapturingTransport.CapturedRequest capturedRequest = transport.capturedRequests()[0]; - assertTrue(capturedRequest.node.isMasterNode()); - assertThat(capturedRequest.request, equalTo(request)); - assertThat(capturedRequest.action, equalTo("internal:testAction")); + assertTrue(capturedRequest.node().isMasterNode()); + assertThat(capturedRequest.request(), equalTo(request)); + assertThat(capturedRequest.action(), equalTo("internal:testAction")); Response response = new Response(); - transport.handleResponse(capturedRequest.requestId, response); + transport.handleResponse(capturedRequest.requestId(), response); assertTrue(listener.isDone()); assertThat(listener.get(), equalTo(response)); } @@ -447,13 +447,13 @@ public class TransportMasterNodeActionTests extends ESTestCase { CapturingTransport.CapturedRequest[] capturedRequests = transport.getCapturedRequestsAndClear(); assertThat(capturedRequests.length, equalTo(1)); CapturingTransport.CapturedRequest capturedRequest = capturedRequests[0]; - assertTrue(capturedRequest.node.isMasterNode()); - assertThat(capturedRequest.request, equalTo(request)); - assertThat(capturedRequest.action, equalTo("internal:testAction")); + assertTrue(capturedRequest.node().isMasterNode()); + assertThat(capturedRequest.request(), equalTo(request)); + assertThat(capturedRequest.action(), equalTo("internal:testAction")); if (rejoinSameMaster) { transport.handleRemoteError( - capturedRequest.requestId, + capturedRequest.requestId(), randomBoolean() ? new ConnectTransportException(masterNode, "Fake error") : new NodeClosedException(masterNode) ); assertFalse(listener.isDone()); @@ -483,11 +483,11 @@ public class TransportMasterNodeActionTests extends ESTestCase { capturedRequests = transport.getCapturedRequestsAndClear(); assertThat(capturedRequests.length, equalTo(1)); capturedRequest = capturedRequests[0]; - assertTrue(capturedRequest.node.isMasterNode()); - assertThat(capturedRequest.request, equalTo(request)); - assertThat(capturedRequest.action, equalTo("internal:testAction")); + assertTrue(capturedRequest.node().isMasterNode()); + assertThat(capturedRequest.request(), equalTo(request)); + assertThat(capturedRequest.action(), equalTo("internal:testAction")); } else if (failsWithConnectTransportException) { - transport.handleRemoteError(capturedRequest.requestId, new ConnectTransportException(masterNode, "Fake error")); + transport.handleRemoteError(capturedRequest.requestId(), new ConnectTransportException(masterNode, "Fake error")); assertFalse(listener.isDone()); setState(clusterService, ClusterStateCreationUtils.state(localNode, localNode, allNodes)); assertTrue(listener.isDone()); @@ -495,7 +495,7 @@ public class TransportMasterNodeActionTests extends ESTestCase { } else { ElasticsearchException t = new ElasticsearchException("test"); t.addHeader("header", "is here"); - transport.handleRemoteError(capturedRequest.requestId, t); + transport.handleRemoteError(capturedRequest.requestId(), t); assertTrue(listener.isDone()); try { listener.get(); @@ -533,11 +533,11 @@ public class TransportMasterNodeActionTests extends ESTestCase { assertThat(transport.capturedRequests().length, equalTo(1)); CapturingTransport.CapturedRequest capturedRequest = transport.capturedRequests()[0]; - assertTrue(capturedRequest.node.isMasterNode()); - assertThat(capturedRequest.request, equalTo(request)); - assertThat(capturedRequest.action, equalTo("internal:testAction")); + assertTrue(capturedRequest.node().isMasterNode()); + assertThat(capturedRequest.request(), equalTo(request)); + assertThat(capturedRequest.action(), equalTo("internal:testAction")); - transport.handleResponse(capturedRequest.requestId, response); + transport.handleResponse(capturedRequest.requestId(), response); assertTrue(listener.isDone()); assertThat(listener.get(), equalTo(response)); } diff --git a/server/src/test/java/org/elasticsearch/action/support/nodes/TransportNodesActionTests.java b/server/src/test/java/org/elasticsearch/action/support/nodes/TransportNodesActionTests.java index bef435c20834..ee43aaa5b5e9 100644 --- a/server/src/test/java/org/elasticsearch/action/support/nodes/TransportNodesActionTests.java +++ b/server/src/test/java/org/elasticsearch/action/support/nodes/TransportNodesActionTests.java @@ -162,9 +162,9 @@ public class TransportNodesActionTests extends ESTestCase { for (List requests : capturedRequests.values()) { for (CapturingTransport.CapturedRequest capturedRequest : requests) { if (randomBoolean()) { - transport.handleResponse(capturedRequest.requestId, new TestNodeResponse(capturedRequest.node)); + transport.handleResponse(capturedRequest.requestId(), new TestNodeResponse(capturedRequest.node())); } else { - transport.handleRemoteError(capturedRequest.requestId, new TaskCancelledException("simulated")); + transport.handleRemoteError(capturedRequest.requestId(), new TaskCancelledException("simulated")); } } } diff --git a/server/src/test/java/org/elasticsearch/action/support/replication/TransportReplicationActionTests.java b/server/src/test/java/org/elasticsearch/action/support/replication/TransportReplicationActionTests.java index ba767287f964..83bb27b76053 100644 --- a/server/src/test/java/org/elasticsearch/action/support/replication/TransportReplicationActionTests.java +++ b/server/src/test/java/org/elasticsearch/action/support/replication/TransportReplicationActionTests.java @@ -449,7 +449,7 @@ public class TransportReplicationActionTests extends ESTestCase { .get(primaryNodeId); assertThat(capturedRequests, notNullValue()); assertThat(capturedRequests.size(), equalTo(1)); - assertThat(capturedRequests.get(0).action, equalTo("internal:testAction[p]")); + assertThat(capturedRequests.get(0).action(), equalTo("internal:testAction[p]")); assertIndexShardCounter(0); } @@ -544,7 +544,7 @@ public class TransportReplicationActionTests extends ESTestCase { .get(primaryNodeId); assertThat(capturedRequests, notNullValue()); assertThat(capturedRequests.size(), equalTo(1)); - assertThat(capturedRequests.get(0).action, equalTo("internal:testAction[p]")); + assertThat(capturedRequests.get(0).action(), equalTo("internal:testAction[p]")); assertIndexShardCounter(0); } @@ -638,19 +638,19 @@ public class TransportReplicationActionTests extends ESTestCase { reroutePhase.run(); CapturingTransport.CapturedRequest[] capturedRequests = transport.getCapturedRequestsAndClear(); assertThat(capturedRequests, arrayWithSize(1)); - assertThat(capturedRequests[0].action, equalTo("internal:testAction[p]")); + assertThat(capturedRequests[0].action(), equalTo("internal:testAction[p]")); assertPhase(task, "waiting_on_primary"); assertFalse(request.isRetrySet.get()); - transport.handleRemoteError(capturedRequests[0].requestId, randomRetryPrimaryException(shardId)); + transport.handleRemoteError(capturedRequests[0].requestId(), randomRetryPrimaryException(shardId)); if (timeout) { // we always try at least one more time on timeout assertThat(listener.isDone(), equalTo(false)); capturedRequests = transport.getCapturedRequestsAndClear(); assertThat(capturedRequests, arrayWithSize(1)); - assertThat(capturedRequests[0].action, equalTo("internal:testAction[p]")); + assertThat(capturedRequests[0].action(), equalTo("internal:testAction[p]")); assertPhase(task, "waiting_on_primary"); - transport.handleRemoteError(capturedRequests[0].requestId, randomRetryPrimaryException(shardId)); + transport.handleRemoteError(capturedRequests[0].requestId(), randomRetryPrimaryException(shardId)); assertListenerThrows("must throw index not found exception", listener, ElasticsearchException.class); assertPhase(task, "failed"); } else { @@ -659,7 +659,7 @@ public class TransportReplicationActionTests extends ESTestCase { setState(clusterService, clusterService.state()); capturedRequests = transport.getCapturedRequestsAndClear(); assertThat(capturedRequests, arrayWithSize(1)); - assertThat(capturedRequests[0].action, equalTo("internal:testAction[p]")); + assertThat(capturedRequests[0].action(), equalTo("internal:testAction[p]")); } } @@ -695,10 +695,10 @@ public class TransportReplicationActionTests extends ESTestCase { assertThat(capturedRequests, notNullValue()); assertThat(capturedRequests.size(), equalTo(1)); if (clusterService.state().nodes().getLocalNodeId().equals(primaryNodeId)) { - assertThat(capturedRequests.get(0).action, equalTo("internal:testAction[p]")); + assertThat(capturedRequests.get(0).action(), equalTo("internal:testAction[p]")); assertPhase(task, "waiting_on_primary"); } else { - assertThat(capturedRequests.get(0).action, equalTo("internal:testAction")); + assertThat(capturedRequests.get(0).action(), equalTo("internal:testAction")); assertPhase(task, "rerouted"); } assertFalse(request.isRetrySet.get()); @@ -754,15 +754,15 @@ public class TransportReplicationActionTests extends ESTestCase { assertThat(requests.size(), equalTo(1)); assertThat( "primary request was not delegated to relocation target", - requests.get(0).action, + requests.get(0).action(), equalTo("internal:testAction2[p]") ); @SuppressWarnings("unchecked") final TransportReplicationAction.ConcreteShardRequest concreteShardRequest = - (TransportReplicationAction.ConcreteShardRequest) requests.get(0).request; + (TransportReplicationAction.ConcreteShardRequest) requests.get(0).request(); assertThat("primary term not properly set on primary delegation", concreteShardRequest.getPrimaryTerm(), equalTo(primaryTerm)); assertPhase(task, "primary_delegation"); - transport.handleResponse(requests.get(0).requestId, new TestResponse()); + transport.handleResponse(requests.get(0).requestId(), new TestResponse()); assertTrue(listener.isDone()); listener.get(); assertPhase(task, "finished"); @@ -877,15 +877,15 @@ public class TransportReplicationActionTests extends ESTestCase { randomLong(), randomLong() ); - transport.handleResponse(captures[0].requestId, response); + transport.handleResponse(captures[0].requestId(), response); assertTrue(listener.isDone()); assertThat(listener.get(), equalTo(response)); } else if (randomBoolean()) { - transport.handleRemoteError(captures[0].requestId, new ElasticsearchException("simulated")); + transport.handleRemoteError(captures[0].requestId(), new ElasticsearchException("simulated")); assertTrue(listener.isDone()); assertListenerThrows("listener should reflect remote error", listener, ElasticsearchException.class); } else { - transport.handleError(captures[0].requestId, new TransportException("simulated")); + transport.handleError(captures[0].requestId(), new TransportException("simulated")); assertTrue(listener.isDone()); assertListenerThrows("listener should reflect remote error", listener, TransportException.class); } @@ -963,7 +963,7 @@ public class TransportReplicationActionTests extends ESTestCase { assertThat(requestsToReplicas, arrayWithSize(1)); @SuppressWarnings("unchecked") TransportReplicationAction.ConcreteShardRequest shardRequest = (TransportReplicationAction.ConcreteShardRequest< - Request>) requestsToReplicas[0].request; + Request>) requestsToReplicas[0].request(); assertThat(shardRequest.getPrimaryTerm(), equalTo(primaryTerm)); } @@ -1254,17 +1254,17 @@ public class TransportReplicationActionTests extends ESTestCase { assertThat(capturedRequests, notNullValue()); assertThat(capturedRequests.size(), equalTo(1)); final CapturingTransport.CapturedRequest capturedRequest = capturedRequests.get(0); - assertThat(capturedRequest.action, equalTo("internal:testActionWithExceptions[r]")); - assertThat(capturedRequest.request, instanceOf(TransportReplicationAction.ConcreteReplicaRequest.class)); + assertThat(capturedRequest.action(), equalTo("internal:testActionWithExceptions[r]")); + assertThat(capturedRequest.request(), instanceOf(TransportReplicationAction.ConcreteReplicaRequest.class)); assertThat( - ((TransportReplicationAction.ConcreteReplicaRequest) capturedRequest.request).getGlobalCheckpoint(), + ((TransportReplicationAction.ConcreteReplicaRequest) capturedRequest.request()).getGlobalCheckpoint(), equalTo(checkpoint) ); assertThat( - ((TransportReplicationAction.ConcreteReplicaRequest) capturedRequest.request).getMaxSeqNoOfUpdatesOrDeletes(), + ((TransportReplicationAction.ConcreteReplicaRequest) capturedRequest.request()).getMaxSeqNoOfUpdatesOrDeletes(), equalTo(maxSeqNoOfUpdatesOrDeletes) ); - assertConcreteShardRequest(capturedRequest.request, request, replica.allocationId()); + assertConcreteShardRequest(capturedRequest.request(), request, replica.allocationId()); } public void testRetryOnReplicaWithRealTransport() throws Exception { diff --git a/server/src/test/java/org/elasticsearch/action/support/replication/TransportWriteActionTests.java b/server/src/test/java/org/elasticsearch/action/support/replication/TransportWriteActionTests.java index 234d4bcbf17f..43e4464ddb91 100644 --- a/server/src/test/java/org/elasticsearch/action/support/replication/TransportWriteActionTests.java +++ b/server/src/test/java/org/elasticsearch/action/support/replication/TransportWriteActionTests.java @@ -320,15 +320,15 @@ public class TransportWriteActionTests extends ESTestCase { randomLong(), randomLong() ); - transport.handleResponse(captures[0].requestId, response); + transport.handleResponse(captures[0].requestId(), response); assertTrue(listener.isDone()); assertThat(listener.get(), equalTo(response)); } else if (randomBoolean()) { - transport.handleRemoteError(captures[0].requestId, new ElasticsearchException("simulated")); + transport.handleRemoteError(captures[0].requestId(), new ElasticsearchException("simulated")); assertTrue(listener.isDone()); assertListenerThrows("listener should reflect remote error", listener, ElasticsearchException.class); } else { - transport.handleError(captures[0].requestId, new TransportException("simulated")); + transport.handleError(captures[0].requestId(), new TransportException("simulated")); assertTrue(listener.isDone()); assertListenerThrows("listener should reflect remote error", listener, TransportException.class); } @@ -346,26 +346,26 @@ public class TransportWriteActionTests extends ESTestCase { // A write replication action proxy should fail the shard assertEquals(1, shardFailedRequests.length); CapturingTransport.CapturedRequest shardFailedRequest = shardFailedRequests[0]; - ShardStateAction.FailedShardEntry shardEntry = (ShardStateAction.FailedShardEntry) shardFailedRequest.request; + ShardStateAction.FailedShardEntry shardEntry = (ShardStateAction.FailedShardEntry) shardFailedRequest.request(); // the shard the request was sent to and the shard to be failed should be the same assertEquals(shardEntry.getShardId(), replica.shardId()); assertEquals(shardEntry.getAllocationId(), replica.allocationId().getId()); if (randomBoolean()) { // simulate success - transport.handleResponse(shardFailedRequest.requestId, TransportResponse.Empty.INSTANCE); + transport.handleResponse(shardFailedRequest.requestId(), TransportResponse.Empty.INSTANCE); assertTrue(success.get()); assertNull(failure.get()); } else if (randomBoolean()) { // simulate the primary has been demoted transport.handleRemoteError( - shardFailedRequest.requestId, + shardFailedRequest.requestId(), new ShardStateAction.NoLongerPrimaryShardException(replica.shardId(), "shard-failed-test") ); assertFalse(success.get()); assertNotNull(failure.get()); } else { // simulated a node closing exception - transport.handleRemoteError(shardFailedRequest.requestId, new NodeClosedException(state.nodes().getLocalNode())); + transport.handleRemoteError(shardFailedRequest.requestId(), new NodeClosedException(state.nodes().getLocalNode())); assertFalse(success.get()); assertNotNull(failure.get()); } diff --git a/server/src/test/java/org/elasticsearch/action/support/single/instance/TransportInstanceSingleOperationActionTests.java b/server/src/test/java/org/elasticsearch/action/support/single/instance/TransportInstanceSingleOperationActionTests.java index 8030ec5c5587..4c29b10575fa 100644 --- a/server/src/test/java/org/elasticsearch/action/support/single/instance/TransportInstanceSingleOperationActionTests.java +++ b/server/src/test/java/org/elasticsearch/action/support/single/instance/TransportInstanceSingleOperationActionTests.java @@ -218,7 +218,7 @@ public class TransportInstanceSingleOperationActionTests extends ESTestCase { setState(clusterService, ClusterStateCreationUtils.state("test", randomBoolean(), ShardRoutingState.STARTED)); action.new AsyncSingleAction(request, listener).start(); assertThat(transport.capturedRequests().length, equalTo(1)); - transport.handleResponse(transport.capturedRequests()[0].requestId, new Response()); + transport.handleResponse(transport.capturedRequests()[0].requestId(), new Response()); listener.get(); } @@ -230,7 +230,7 @@ public class TransportInstanceSingleOperationActionTests extends ESTestCase { action.new AsyncSingleAction(request, listener).start(); assertThat(transport.capturedRequests().length, equalTo(1)); - long requestId = transport.capturedRequests()[0].requestId; + long requestId = transport.capturedRequests()[0].requestId(); transport.clear(); // this should not trigger retry or anything and the listener should report exception immediately transport.handleRemoteError( @@ -263,7 +263,7 @@ public class TransportInstanceSingleOperationActionTests extends ESTestCase { setState(clusterService, ClusterStateCreationUtils.state("test", local, ShardRoutingState.STARTED)); // this time it should work assertThat(transport.capturedRequests().length, equalTo(1)); - transport.handleResponse(transport.capturedRequests()[0].requestId, new Response()); + transport.handleResponse(transport.capturedRequests()[0].requestId(), new Response()); listener.get(); } @@ -275,14 +275,14 @@ public class TransportInstanceSingleOperationActionTests extends ESTestCase { setState(clusterService, ClusterStateCreationUtils.state("test", local, ShardRoutingState.STARTED)); action.new AsyncSingleAction(request, listener).start(); assertThat(transport.capturedRequests().length, equalTo(1)); - long requestId = transport.capturedRequests()[0].requestId; + long requestId = transport.capturedRequests()[0].requestId(); transport.clear(); DiscoveryNode node = clusterService.state().getNodes().getLocalNode(); transport.handleLocalError(requestId, new ConnectTransportException(node, "test exception")); // trigger cluster state observer setState(clusterService, ClusterStateCreationUtils.state("test", local, ShardRoutingState.STARTED)); assertThat(transport.capturedRequests().length, equalTo(1)); - transport.handleResponse(transport.capturedRequests()[0].requestId, new Response()); + transport.handleResponse(transport.capturedRequests()[0].requestId(), new Response()); listener.get(); } @@ -293,7 +293,7 @@ public class TransportInstanceSingleOperationActionTests extends ESTestCase { setState(clusterService, ClusterStateCreationUtils.state("test", randomBoolean(), ShardRoutingState.STARTED)); action.new AsyncSingleAction(request, listener).start(); assertThat(transport.capturedRequests().length, equalTo(1)); - long requestId = transport.capturedRequests()[0].requestId; + long requestId = transport.capturedRequests()[0].requestId(); transport.clear(); DiscoveryNode node = clusterService.state().getNodes().getLocalNode(); transport.handleLocalError(requestId, new ConnectTransportException(node, "test exception")); @@ -302,7 +302,7 @@ public class TransportInstanceSingleOperationActionTests extends ESTestCase { assertBusy(() -> assertThat(transport.capturedRequests().length, equalTo(1))); // let it fail the second time too - requestId = transport.capturedRequests()[0].requestId; + requestId = transport.capturedRequests()[0].requestId(); transport.handleLocalError(requestId, new ConnectTransportException(node, "test exception")); try { // result should return immediately diff --git a/server/src/test/java/org/elasticsearch/action/termvectors/AbstractTermVectorsTestCase.java b/server/src/test/java/org/elasticsearch/action/termvectors/AbstractTermVectorsTestCase.java index 1a94d8468171..8bca25c0457b 100644 --- a/server/src/test/java/org/elasticsearch/action/termvectors/AbstractTermVectorsTestCase.java +++ b/server/src/test/java/org/elasticsearch/action/termvectors/AbstractTermVectorsTestCase.java @@ -54,18 +54,7 @@ import static org.elasticsearch.xcontent.XContentFactory.jsonBuilder; import static org.hamcrest.Matchers.equalTo; public abstract class AbstractTermVectorsTestCase extends ESIntegTestCase { - protected static class TestFieldSetting { - public final String name; - public final boolean storedOffset; - public final boolean storedPayloads; - public final boolean storedPositions; - - public TestFieldSetting(String name, boolean storedOffset, boolean storedPayloads, boolean storedPositions) { - this.name = name; - this.storedOffset = storedOffset; - this.storedPayloads = storedPayloads; - this.storedPositions = storedPositions; - } + protected record TestFieldSetting(String name, boolean storedOffset, boolean storedPayloads, boolean storedPositions) { public void addToMappings(XContentBuilder mappingsBuilder) throws IOException { mappingsBuilder.startObject(name); @@ -93,21 +82,6 @@ public abstract class AbstractTermVectorsTestCase extends ESIntegTestCase { mappingsBuilder.endObject(); } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("name: ").append(name).append(" tv_with:"); - if (storedPayloads) { - sb.append("payloads,"); - } - if (storedOffset) { - sb.append("offsets,"); - } - if (storedPositions) { - sb.append("positions,"); - } - return sb.toString(); - } } protected static class TestDoc { diff --git a/server/src/test/java/org/elasticsearch/cluster/action/shard/ShardStateActionTests.java b/server/src/test/java/org/elasticsearch/cluster/action/shard/ShardStateActionTests.java index 2d987bef32f1..76ca08965926 100644 --- a/server/src/test/java/org/elasticsearch/cluster/action/shard/ShardStateActionTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/action/shard/ShardStateActionTests.java @@ -170,15 +170,15 @@ public class ShardStateActionTests extends ESTestCase { CapturingTransport.CapturedRequest[] capturedRequests = transport.getCapturedRequestsAndClear(); assertEquals(1, capturedRequests.length); // the request is a shard failed request - assertThat(capturedRequests[0].request, is(instanceOf(ShardStateAction.FailedShardEntry.class))); - ShardStateAction.FailedShardEntry shardEntry = (ShardStateAction.FailedShardEntry) capturedRequests[0].request; + assertThat(capturedRequests[0].request(), is(instanceOf(ShardStateAction.FailedShardEntry.class))); + ShardStateAction.FailedShardEntry shardEntry = (ShardStateAction.FailedShardEntry) capturedRequests[0].request(); // for the right shard assertEquals(shardEntry.shardId, shardRouting.shardId()); assertEquals(shardEntry.allocationId, shardRouting.allocationId().getId()); // sent to the master - assertEquals(clusterService.state().nodes().getMasterNode().getId(), capturedRequests[0].node.getId()); + assertEquals(clusterService.state().nodes().getMasterNode().getId(), capturedRequests[0].node().getId()); - transport.handleResponse(capturedRequests[0].requestId, TransportResponse.Empty.INSTANCE); + transport.handleResponse(capturedRequests[0].requestId(), TransportResponse.Empty.INSTANCE); listener.await(); assertNull(listener.failure.get()); @@ -270,7 +270,7 @@ public class ShardStateActionTests extends ESTestCase { assertThat(capturedRequests.length, equalTo(1)); assertFalse(success.get()); assertThat(retries.get(), equalTo(0)); - retryLoop.accept(capturedRequests[0].requestId); + retryLoop.accept(capturedRequests[0].requestId()); latch.await(); assertNull(throwable.get()); @@ -289,7 +289,7 @@ public class ShardStateActionTests extends ESTestCase { final CapturingTransport.CapturedRequest[] capturedRequests = transport.getCapturedRequestsAndClear(); assertThat(capturedRequests.length, equalTo(1)); - transport.handleRemoteError(capturedRequests[0].requestId, new TransportException("simulated")); + transport.handleRemoteError(capturedRequests[0].requestId(), new TransportException("simulated")); assertNotNull(listener.failure.get()); } @@ -305,7 +305,7 @@ public class ShardStateActionTests extends ESTestCase { shardStateAction.localShardFailed(failedShard, "test", getSimulatedFailure(), listener); CapturingTransport.CapturedRequest[] capturedRequests = transport.getCapturedRequestsAndClear(); - transport.handleResponse(capturedRequests[0].requestId, TransportResponse.Empty.INSTANCE); + transport.handleResponse(capturedRequests[0].requestId(), TransportResponse.Empty.INSTANCE); listener.await(); assertNull(listener.failure.get()); @@ -336,7 +336,7 @@ public class ShardStateActionTests extends ESTestCase { "dummy failure" ); CapturingTransport.CapturedRequest[] capturedRequests = transport.getCapturedRequestsAndClear(); - transport.handleRemoteError(capturedRequests[0].requestId, catastrophicError); + transport.handleRemoteError(capturedRequests[0].requestId(), catastrophicError); listener.await(); @@ -377,7 +377,7 @@ public class ShardStateActionTests extends ESTestCase { } CapturingTransport.CapturedRequest[] capturedRequests = transport.getCapturedRequestsAndClear(); assertThat(capturedRequests, arrayWithSize(1)); - transport.handleResponse(capturedRequests[0].requestId, TransportResponse.Empty.INSTANCE); + transport.handleResponse(capturedRequests[0].requestId(), TransportResponse.Empty.INSTANCE); latch.await(); assertThat(transport.capturedRequests(), arrayWithSize(0)); } @@ -410,7 +410,7 @@ public class ShardStateActionTests extends ESTestCase { CapturingTransport.CapturedRequest[] capturedRequests = transport.getCapturedRequestsAndClear(); assertThat(capturedRequests, arrayWithSize(expectedRequests)); for (int i = 0; i < expectedRequests; i++) { - transport.handleResponse(capturedRequests[i].requestId, TransportResponse.Empty.INSTANCE); + transport.handleResponse(capturedRequests[i].requestId(), TransportResponse.Empty.INSTANCE); } latch.await(); assertThat(transport.capturedRequests(), arrayWithSize(0)); @@ -432,9 +432,9 @@ public class ShardStateActionTests extends ESTestCase { while (shutdown.get() == false) { for (CapturingTransport.CapturedRequest request : transport.getCapturedRequestsAndClear()) { if (randomBoolean()) { - transport.handleResponse(request.requestId, TransportResponse.Empty.INSTANCE); + transport.handleResponse(request.requestId(), TransportResponse.Empty.INSTANCE); } else { - transport.handleRemoteError(request.requestId, randomFrom(getSimulatedFailure())); + transport.handleRemoteError(request.requestId(), randomFrom(getSimulatedFailure())); } } } @@ -489,15 +489,15 @@ public class ShardStateActionTests extends ESTestCase { shardStateAction.shardStarted(shardRouting, primaryTerm, "testShardStarted", ShardLongFieldRange.UNKNOWN, listener); final CapturingTransport.CapturedRequest[] capturedRequests = transport.getCapturedRequestsAndClear(); - assertThat(capturedRequests[0].request, instanceOf(ShardStateAction.StartedShardEntry.class)); + assertThat(capturedRequests[0].request(), instanceOf(ShardStateAction.StartedShardEntry.class)); - ShardStateAction.StartedShardEntry entry = (ShardStateAction.StartedShardEntry) capturedRequests[0].request; + ShardStateAction.StartedShardEntry entry = (ShardStateAction.StartedShardEntry) capturedRequests[0].request(); assertThat(entry.shardId, equalTo(shardRouting.shardId())); assertThat(entry.allocationId, equalTo(shardRouting.allocationId().getId())); assertThat(entry.primaryTerm, equalTo(primaryTerm)); assertThat(entry.timestampRange, sameInstance(ShardLongFieldRange.UNKNOWN)); - transport.handleResponse(capturedRequests[0].requestId, TransportResponse.Empty.INSTANCE); + transport.handleResponse(capturedRequests[0].requestId(), TransportResponse.Empty.INSTANCE); listener.await(); assertNull(listener.failure.get()); } @@ -527,9 +527,9 @@ public class ShardStateActionTests extends ESTestCase { retries.incrementAndGet(); if (retries.get() == numberOfRetries) { // finish the request - transport.handleResponse(capturedRequests[0].requestId, TransportResponse.Empty.INSTANCE); + transport.handleResponse(capturedRequests[0].requestId(), TransportResponse.Empty.INSTANCE); } else { - retryLoop.accept(capturedRequests[0].requestId); + retryLoop.accept(capturedRequests[0].requestId()); } } else { // there failed to be a retry request diff --git a/server/src/test/java/org/elasticsearch/cluster/coordination/FollowersCheckerTests.java b/server/src/test/java/org/elasticsearch/cluster/coordination/FollowersCheckerTests.java index aa3f71fcf111..56712498429b 100644 --- a/server/src/test/java/org/elasticsearch/cluster/coordination/FollowersCheckerTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/coordination/FollowersCheckerTests.java @@ -727,7 +727,7 @@ public class FollowersCheckerTests extends ESTestCase { ); followersChecker.setCurrentNodes(discoveryNodes); List followerTargets = Stream.of(capturingTransport.getCapturedRequestsAndClear()) - .map(cr -> cr.node) + .map(cr -> cr.node()) .collect(Collectors.toList()); List sortedFollowerTargets = new ArrayList<>(followerTargets); Collections.sort(sortedFollowerTargets, Comparator.comparing(n -> n.isMasterNode() == false)); diff --git a/server/src/test/java/org/elasticsearch/cluster/coordination/JoinHelperTests.java b/server/src/test/java/org/elasticsearch/cluster/coordination/JoinHelperTests.java index 5b1b8da8cce5..ca30d4bfb4c3 100644 --- a/server/src/test/java/org/elasticsearch/cluster/coordination/JoinHelperTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/coordination/JoinHelperTests.java @@ -106,7 +106,7 @@ public class JoinHelperTests extends ESTestCase { CapturedRequest[] capturedRequests1 = capturingTransport.getCapturedRequestsAndClear(); assertThat(capturedRequests1.length, equalTo(1)); CapturedRequest capturedRequest1 = capturedRequests1[0]; - assertEquals(node1, capturedRequest1.node); + assertEquals(node1, capturedRequest1.node()); assertTrue(joinHelper.isJoinPending()); @@ -118,7 +118,7 @@ public class JoinHelperTests extends ESTestCase { CapturedRequest[] capturedRequests2 = capturingTransport.getCapturedRequestsAndClear(); assertThat(capturedRequests2.length, equalTo(1)); CapturedRequest capturedRequest2 = capturedRequests2[0]; - assertEquals(node2, capturedRequest2.node); + assertEquals(node2, capturedRequest2.node()); // check that sending another join to node1 is a noop as the previous join is still in progress joinHelper.sendJoinRequest(node1, 0L, optionalJoin1); @@ -132,7 +132,7 @@ public class JoinHelperTests extends ESTestCase { CapturedRequest[] capturedRequests1a = capturingTransport.getCapturedRequestsAndClear(); assertThat(capturedRequests1a.length, equalTo(1)); CapturedRequest capturedRequest1a = capturedRequests1a[0]; - assertEquals(node1, capturedRequest1a.node); + assertEquals(node1, capturedRequest1a.node()); // check that sending another join to node2 works if the optionalJoin is different Optional optionalJoin2a = optionalJoin2.isPresent() && randomBoolean() @@ -142,7 +142,7 @@ public class JoinHelperTests extends ESTestCase { CapturedRequest[] capturedRequests2a = capturingTransport.getCapturedRequestsAndClear(); assertThat(capturedRequests2a.length, equalTo(1)); CapturedRequest capturedRequest2a = capturedRequests2a[0]; - assertEquals(node2, capturedRequest2a.node); + assertEquals(node2, capturedRequest2a.node()); // complete all the joins and check that isJoinPending is updated assertTrue(joinHelper.isJoinPending()); @@ -164,9 +164,9 @@ public class JoinHelperTests extends ESTestCase { private void completeJoinRequest(CapturingTransport capturingTransport, CapturedRequest request, boolean mightSucceed) { if (mightSucceed && randomBoolean()) { - capturingTransport.handleResponse(request.requestId, TransportResponse.Empty.INSTANCE); + capturingTransport.handleResponse(request.requestId(), TransportResponse.Empty.INSTANCE); } else { - capturingTransport.handleRemoteError(request.requestId, new CoordinationStateRejectedException("dummy")); + capturingTransport.handleRemoteError(request.requestId(), new CoordinationStateRejectedException("dummy")); } } @@ -332,7 +332,7 @@ public class JoinHelperTests extends ESTestCase { CapturedRequest[] capturedRequests1a = capturingTransport.getCapturedRequestsAndClear(); assertThat(capturedRequests1a.length, equalTo(1)); CapturedRequest capturedRequest1a = capturedRequests1a[0]; - assertEquals(node1, capturedRequest1a.node); + assertEquals(node1, capturedRequest1a.node()); } public void testJoinValidationFailsOnUnreadableClusterState() throws Exception { diff --git a/server/src/test/java/org/elasticsearch/discovery/PeerFinderTests.java b/server/src/test/java/org/elasticsearch/discovery/PeerFinderTests.java index 593d6d7a7baf..2dc24cf73d3b 100644 --- a/server/src/test/java/org/elasticsearch/discovery/PeerFinderTests.java +++ b/server/src/test/java/org/elasticsearch/discovery/PeerFinderTests.java @@ -548,7 +548,7 @@ public class PeerFinderTests extends ESTestCase { final CapturedRequest[] capturedRequests = capturingTransport.getCapturedRequestsAndClear(); assertThat(capturedRequests.length, is(1)); - final PeersRequest peersRequest = (PeersRequest) capturedRequests[0].request; + final PeersRequest peersRequest = (PeersRequest) capturedRequests[0].request(); assertThat(peersRequest.getKnownPeers(), contains(otherNode)); } @@ -892,11 +892,11 @@ public class PeerFinderTests extends ESTestCase { private void respondToRequests(Function responseFactory) { final CapturedRequest[] capturedRequests = capturingTransport.getCapturedRequestsAndClear(); for (final CapturedRequest capturedRequest : capturedRequests) { - assertThat(capturedRequest.action, is(REQUEST_PEERS_ACTION_NAME)); - assertThat(capturedRequest.request, instanceOf(PeersRequest.class)); - final PeersRequest peersRequest = (PeersRequest) capturedRequest.request; + assertThat(capturedRequest.action(), is(REQUEST_PEERS_ACTION_NAME)); + assertThat(capturedRequest.request(), instanceOf(PeersRequest.class)); + final PeersRequest peersRequest = (PeersRequest) capturedRequest.request(); assertThat(peersRequest.getSourceNode(), is(localNode)); - capturingTransport.handleResponse(capturedRequests[0].requestId, responseFactory.apply(capturedRequest.node)); + capturingTransport.handleResponse(capturedRequests[0].requestId(), responseFactory.apply(capturedRequest.node())); } } diff --git a/server/src/test/java/org/elasticsearch/index/engine/InternalEngineTests.java b/server/src/test/java/org/elasticsearch/index/engine/InternalEngineTests.java index 8d3d4e90c2f6..55c02a1ea7a5 100644 --- a/server/src/test/java/org/elasticsearch/index/engine/InternalEngineTests.java +++ b/server/src/test/java/org/elasticsearch/index/engine/InternalEngineTests.java @@ -4682,10 +4682,7 @@ public class InternalEngineTests extends EngineTestCase { .stream() .filter(e -> e.getValue().operationType() == Engine.Operation.TYPE.INDEX) .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().seqNo())); - assertThat( - getDocIds(engine, true).stream().collect(Collectors.toMap(e -> e.getId(), e -> e.getSeqNo())), - equalTo(liveOps) - ); + assertThat(getDocIds(engine, true).stream().collect(Collectors.toMap(e -> e.id(), e -> e.seqNo())), equalTo(liveOps)); for (String id : latestOps.keySet()) { String msg = "latestOps=" + latestOps + " op=" + id; DocIdAndSeqNo docIdAndSeqNo = VersionsAndSeqNoResolver.loadDocIdAndSeqNo(searcher.getIndexReader(), newUid(id)); diff --git a/server/src/test/java/org/elasticsearch/index/engine/LuceneChangesSnapshotTests.java b/server/src/test/java/org/elasticsearch/index/engine/LuceneChangesSnapshotTests.java index f77f9095b693..e48a7e4dddd5 100644 --- a/server/src/test/java/org/elasticsearch/index/engine/LuceneChangesSnapshotTests.java +++ b/server/src/test/java/org/elasticsearch/index/engine/LuceneChangesSnapshotTests.java @@ -423,10 +423,10 @@ public class LuceneChangesSnapshotTests extends EngineTestCase { assertConsistentHistoryBetweenTranslogAndLuceneIndex(engine); // have to verify without source since we are randomly testing without _source List docsWithoutSourceOnFollower = getDocIds(engine, true).stream() - .map(d -> new DocIdSeqNoAndSource(d.getId(), null, d.getSeqNo(), d.getPrimaryTerm(), d.getVersion())) + .map(d -> new DocIdSeqNoAndSource(d.id(), null, d.seqNo(), d.primaryTerm(), d.version())) .collect(Collectors.toList()); List docsWithoutSourceOnLeader = getDocIds(leader, true).stream() - .map(d -> new DocIdSeqNoAndSource(d.getId(), null, d.getSeqNo(), d.getPrimaryTerm(), d.getVersion())) + .map(d -> new DocIdSeqNoAndSource(d.id(), null, d.seqNo(), d.primaryTerm(), d.version())) .collect(Collectors.toList()); assertThat(docsWithoutSourceOnFollower, equalTo(docsWithoutSourceOnLeader)); } catch (Exception ex) { diff --git a/server/src/test/java/org/elasticsearch/index/replication/RecoveryDuringReplicationTests.java b/server/src/test/java/org/elasticsearch/index/replication/RecoveryDuringReplicationTests.java index 5124de5fcccf..88655e947c60 100644 --- a/server/src/test/java/org/elasticsearch/index/replication/RecoveryDuringReplicationTests.java +++ b/server/src/test/java/org/elasticsearch/index/replication/RecoveryDuringReplicationTests.java @@ -729,7 +729,7 @@ public class RecoveryDuringReplicationTests extends ESIndexLevelReplicationTestC shards.refresh("test"); List docsBelowGlobalCheckpoint = EngineTestCase.getDocIds(getEngine(newPrimary), randomBoolean()) .stream() - .filter(doc -> doc.getSeqNo() <= newPrimary.getLastKnownGlobalCheckpoint()) + .filter(doc -> doc.seqNo() <= newPrimary.getLastKnownGlobalCheckpoint()) .collect(Collectors.toList()); CountDownLatch latch = new CountDownLatch(1); final AtomicBoolean done = new AtomicBoolean(); diff --git a/server/src/test/java/org/elasticsearch/index/shard/IndexShardTests.java b/server/src/test/java/org/elasticsearch/index/shard/IndexShardTests.java index d39884cb0500..7835f7014818 100644 --- a/server/src/test/java/org/elasticsearch/index/shard/IndexShardTests.java +++ b/server/src/test/java/org/elasticsearch/index/shard/IndexShardTests.java @@ -3982,7 +3982,7 @@ public class IndexShardTests extends IndexShardTestCase { try { List exposedDocIds = EngineTestCase.getDocIds(getEngine(shard), rarely()) .stream() - .map(DocIdSeqNoAndSource::getId) + .map(DocIdSeqNoAndSource::id) .collect(Collectors.toList()); assertThat( "every operations before the global checkpoint must be reserved", diff --git a/test/framework/src/main/java/org/elasticsearch/cluster/coordination/CoordinationStateTestCluster.java b/test/framework/src/main/java/org/elasticsearch/cluster/coordination/CoordinationStateTestCluster.java index a260b4b97c46..0b848a551d8e 100644 --- a/test/framework/src/main/java/org/elasticsearch/cluster/coordination/CoordinationStateTestCluster.java +++ b/test/framework/src/main/java/org/elasticsearch/cluster/coordination/CoordinationStateTestCluster.java @@ -193,17 +193,7 @@ public class CoordinationStateTestCluster { initialValue = randomLong(); } - static class Message { - final DiscoveryNode sourceNode; - final DiscoveryNode targetNode; - final Object payload; - - Message(DiscoveryNode sourceNode, DiscoveryNode targetNode, Object payload) { - this.sourceNode = sourceNode; - this.targetNode = targetNode; - this.payload = payload; - } - } + record Message(DiscoveryNode sourceNode, DiscoveryNode targetNode, Object payload) {} void reply(Message m, Object payload) { messages.add(new Message(m.targetNode, m.sourceNode, payload)); diff --git a/test/framework/src/main/java/org/elasticsearch/cluster/coordination/LinearizabilityChecker.java b/test/framework/src/main/java/org/elasticsearch/cluster/coordination/LinearizabilityChecker.java index 4eb0902d47e3..11d9a54930f4 100644 --- a/test/framework/src/main/java/org/elasticsearch/cluster/coordination/LinearizabilityChecker.java +++ b/test/framework/src/main/java/org/elasticsearch/cluster/coordination/LinearizabilityChecker.java @@ -401,22 +401,7 @@ public class LinearizabilityChecker { RESPONSE } - public static class Event { - public final EventType type; - public final Object value; - public final int id; - - public Event(EventType type, Object value, int id) { - this.type = type; - this.value = value; - this.id = id; - } - - @Override - public String toString() { - return "Event{" + "type=" + type + ", value=" + value + ", id=" + id + '}'; - } - } + public record Event(EventType type, Object value, int id) {} static class Entry { final Event event; diff --git a/test/framework/src/main/java/org/elasticsearch/common/util/concurrent/DeterministicTaskQueue.java b/test/framework/src/main/java/org/elasticsearch/common/util/concurrent/DeterministicTaskQueue.java index 531651e3c2f5..06650e8f0952 100644 --- a/test/framework/src/main/java/org/elasticsearch/common/util/concurrent/DeterministicTaskQueue.java +++ b/test/framework/src/main/java/org/elasticsearch/common/util/concurrent/DeterministicTaskQueue.java @@ -176,8 +176,8 @@ public class DeterministicTaskQueue { } private void scheduleDeferredTask(DeferredTask deferredTask) { - nextDeferredTaskExecutionTimeMillis = Math.min(nextDeferredTaskExecutionTimeMillis, deferredTask.getExecutionTimeMillis()); - latestDeferredExecutionTime = Math.max(latestDeferredExecutionTime, deferredTask.getExecutionTimeMillis()); + nextDeferredTaskExecutionTimeMillis = Math.min(nextDeferredTaskExecutionTimeMillis, deferredTask.executionTimeMillis()); + latestDeferredExecutionTime = Math.max(latestDeferredExecutionTime, deferredTask.executionTimeMillis()); deferredTasks.add(deferredTask); } @@ -195,13 +195,13 @@ public class DeterministicTaskQueue { nextDeferredTaskExecutionTimeMillis = Long.MAX_VALUE; List remainingDeferredTasks = new ArrayList<>(); for (final DeferredTask deferredTask : deferredTasks) { - assert currentTimeMillis <= deferredTask.getExecutionTimeMillis(); - if (deferredTask.getExecutionTimeMillis() == currentTimeMillis) { + assert currentTimeMillis <= deferredTask.executionTimeMillis(); + if (deferredTask.executionTimeMillis() == currentTimeMillis) { logger.trace("advanceTime: no longer deferred: {}", deferredTask); - runnableTasks.add(deferredTask.getTask()); + runnableTasks.add(deferredTask.task()); } else { remainingDeferredTasks.add(deferredTask); - nextDeferredTaskExecutionTimeMillis = Math.min(nextDeferredTaskExecutionTimeMillis, deferredTask.getExecutionTimeMillis()); + nextDeferredTaskExecutionTimeMillis = Math.min(nextDeferredTaskExecutionTimeMillis, deferredTask.executionTimeMillis()); } } deferredTasks = remainingDeferredTasks; @@ -497,28 +497,10 @@ public class DeterministicTaskQueue { return latestDeferredExecutionTime; } - private static class DeferredTask { - private final long executionTimeMillis; - private final Runnable task; - - DeferredTask(long executionTimeMillis, Runnable task) { - this.executionTimeMillis = executionTimeMillis; - this.task = task; + private record DeferredTask(long executionTimeMillis, Runnable task) { + private DeferredTask { assert executionTimeMillis < Long.MAX_VALUE : "Long.MAX_VALUE is special, cannot be an execution time"; } - - long getExecutionTimeMillis() { - return executionTimeMillis; - } - - Runnable getTask() { - return task; - } - - @Override - public String toString() { - return "DeferredTask{" + "executionTimeMillis=" + executionTimeMillis + ", task=" + task + '}'; - } } public static String getNodeIdForLogContext(DiscoveryNode node) { diff --git a/test/framework/src/main/java/org/elasticsearch/index/engine/DocIdSeqNoAndSource.java b/test/framework/src/main/java/org/elasticsearch/index/engine/DocIdSeqNoAndSource.java index 08b86c071c49..1e6e0972fd1f 100644 --- a/test/framework/src/main/java/org/elasticsearch/index/engine/DocIdSeqNoAndSource.java +++ b/test/framework/src/main/java/org/elasticsearch/index/engine/DocIdSeqNoAndSource.java @@ -10,74 +10,7 @@ package org.elasticsearch.index.engine; import org.apache.lucene.util.BytesRef; -import java.util.Objects; - -/** A tuple of document id, sequence number, primary term, source and version of a document */ -public final class DocIdSeqNoAndSource { - private final String id; - private final BytesRef source; - private final long seqNo; - private final long primaryTerm; - private final long version; - - public DocIdSeqNoAndSource(String id, BytesRef source, long seqNo, long primaryTerm, long version) { - this.id = id; - this.source = source; - this.seqNo = seqNo; - this.primaryTerm = primaryTerm; - this.version = version; - } - - public String getId() { - return id; - } - - public BytesRef getSource() { - return source; - } - - public long getSeqNo() { - return seqNo; - } - - public long getPrimaryTerm() { - return primaryTerm; - } - - public long getVersion() { - return version; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - DocIdSeqNoAndSource that = (DocIdSeqNoAndSource) o; - return Objects.equals(id, that.id) - && Objects.equals(source, that.source) - && seqNo == that.seqNo - && primaryTerm == that.primaryTerm - && version == that.version; - } - - @Override - public int hashCode() { - return Objects.hash(id, source, seqNo, primaryTerm, version); - } - - @Override - public String toString() { - return "doc{" - + "id='" - + id - + " seqNo=" - + seqNo - + " primaryTerm=" - + primaryTerm - + " version=" - + version - + " source= " - + (source != null ? source.utf8ToString() : null) - + "}"; - } -} +/** + * A tuple of document id, sequence number, primary term, source and version of a document + */ +public record DocIdSeqNoAndSource(String id, BytesRef source, long seqNo, long primaryTerm, long version) {} diff --git a/test/framework/src/main/java/org/elasticsearch/index/engine/EngineTestCase.java b/test/framework/src/main/java/org/elasticsearch/index/engine/EngineTestCase.java index 088c24cf7ae0..66a64a618950 100644 --- a/test/framework/src/main/java/org/elasticsearch/index/engine/EngineTestCase.java +++ b/test/framework/src/main/java/org/elasticsearch/index/engine/EngineTestCase.java @@ -1242,9 +1242,9 @@ public abstract class EngineTestCase extends ESTestCase { } } docs.sort( - Comparator.comparingLong(DocIdSeqNoAndSource::getSeqNo) - .thenComparingLong(DocIdSeqNoAndSource::getPrimaryTerm) - .thenComparing((DocIdSeqNoAndSource::getId)) + Comparator.comparingLong(DocIdSeqNoAndSource::seqNo) + .thenComparingLong(DocIdSeqNoAndSource::primaryTerm) + .thenComparing((DocIdSeqNoAndSource::id)) ); return docs; } diff --git a/test/framework/src/main/java/org/elasticsearch/index/mapper/MapperTestCase.java b/test/framework/src/main/java/org/elasticsearch/index/mapper/MapperTestCase.java index c20a8d183b98..69100699ff6d 100644 --- a/test/framework/src/main/java/org/elasticsearch/index/mapper/MapperTestCase.java +++ b/test/framework/src/main/java/org/elasticsearch/index/mapper/MapperTestCase.java @@ -364,15 +364,7 @@ public abstract class MapperTestCase extends MapperServiceTestCase { } } - private static class ConflictCheck { - final XContentBuilder init; - final XContentBuilder update; - - private ConflictCheck(XContentBuilder init, XContentBuilder update) { - this.init = init; - this.update = update; - } - } + private record ConflictCheck(XContentBuilder init, XContentBuilder update) {} public class ParameterChecker { diff --git a/test/framework/src/main/java/org/elasticsearch/index/mapper/MetadataMapperTestCase.java b/test/framework/src/main/java/org/elasticsearch/index/mapper/MetadataMapperTestCase.java index d52434fea667..be6b613da312 100644 --- a/test/framework/src/main/java/org/elasticsearch/index/mapper/MetadataMapperTestCase.java +++ b/test/framework/src/main/java/org/elasticsearch/index/mapper/MetadataMapperTestCase.java @@ -27,27 +27,9 @@ public abstract class MetadataMapperTestCase extends MapperServiceTestCase { protected abstract void registerParameters(ParameterChecker checker) throws IOException; - private static class ConflictCheck { - final XContentBuilder init; - final XContentBuilder update; + private record ConflictCheck(XContentBuilder init, XContentBuilder update) {} - private ConflictCheck(XContentBuilder init, XContentBuilder update) { - this.init = init; - this.update = update; - } - } - - private static class UpdateCheck { - final XContentBuilder init; - final XContentBuilder update; - final Consumer check; - - private UpdateCheck(XContentBuilder init, XContentBuilder update, Consumer check) { - this.init = init; - this.update = update; - this.check = check; - } - } + private record UpdateCheck(XContentBuilder init, XContentBuilder update, Consumer check) {} public class ParameterChecker { diff --git a/test/framework/src/main/java/org/elasticsearch/index/shard/IndexShardTestCase.java b/test/framework/src/main/java/org/elasticsearch/index/shard/IndexShardTestCase.java index 5f55a72d3166..92855c570e9e 100644 --- a/test/framework/src/main/java/org/elasticsearch/index/shard/IndexShardTestCase.java +++ b/test/framework/src/main/java/org/elasticsearch/index/shard/IndexShardTestCase.java @@ -830,7 +830,7 @@ public abstract class IndexShardTestCase extends ESTestCase { } public static Set getShardDocUIDs(final IndexShard shard) throws IOException { - return getDocIdAndSeqNos(shard).stream().map(DocIdSeqNoAndSource::getId).collect(Collectors.toSet()); + return getDocIdAndSeqNos(shard).stream().map(DocIdSeqNoAndSource::id).collect(Collectors.toSet()); } public static List getDocIdAndSeqNos(final IndexShard shard) throws IOException { diff --git a/test/framework/src/main/java/org/elasticsearch/test/fixture/AbstractHttpFixture.java b/test/framework/src/main/java/org/elasticsearch/test/fixture/AbstractHttpFixture.java index 5244ae5d7b40..87b8f5f89ffa 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/fixture/AbstractHttpFixture.java +++ b/test/framework/src/main/java/org/elasticsearch/test/fixture/AbstractHttpFixture.java @@ -163,30 +163,14 @@ public abstract class AbstractHttpFixture { /** * Represents an HTTP Response. */ - protected static class Response { + protected record Response(int status, Map headers, byte[] body) { - private final int status; - private final Map headers; - private final byte[] body; - - public Response(final int status, final Map headers, final byte[] body) { + public Response(int status, Map headers, byte[] body) { this.status = status; this.headers = Objects.requireNonNull(headers); this.body = Objects.requireNonNull(body); } - public int getStatus() { - return status; - } - - public Map getHeaders() { - return headers; - } - - public byte[] getBody() { - return body; - } - public String getContentType() { for (String header : headers.keySet()) { if (header.equalsIgnoreCase("Content-Type")) { @@ -195,11 +179,6 @@ public abstract class AbstractHttpFixture { } return null; } - - @Override - public String toString() { - return "Response{" + "status=" + status + ", headers=" + headers + ", body=" + new String(body, UTF_8) + '}'; - } } /** diff --git a/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/ClientYamlTestClient.java b/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/ClientYamlTestClient.java index 8f8690c90016..126d29e35c01 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/ClientYamlTestClient.java +++ b/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/ClientYamlTestClient.java @@ -125,7 +125,7 @@ public class ClientYamlTestClient implements Closeable { Map queryStringParams = new HashMap<>(); for (Map.Entry entry : params.entrySet()) { - if (path.getParts().contains(entry.getKey())) { + if (path.parts().contains(entry.getKey())) { pathParts.put(entry.getKey(), entry.getValue()); } else if (restApi.getParams().containsKey(entry.getKey()) || restSpec.isGlobalParameter(entry.getKey()) @@ -146,13 +146,11 @@ public class ClientYamlTestClient implements Closeable { } Set partNames = pathParts.keySet(); - if (path.getParts().size() != partNames.size() || path.getParts().containsAll(partNames) == false) { - throw new IllegalStateException( - "provided path parts don't match the best matching path: " + path.getParts() + " - " + partNames - ); + if (path.parts().size() != partNames.size() || path.parts().containsAll(partNames) == false) { + throw new IllegalStateException("provided path parts don't match the best matching path: " + path.parts() + " - " + partNames); } - String finalPath = path.getPath(); + String finalPath = path.path(); for (Entry pathPart : pathParts.entrySet()) { try { // Encode rules for path and query string parameters are different. We use URI to encode the path. We need to encode each @@ -167,7 +165,7 @@ public class ClientYamlTestClient implements Closeable { } } - List supportedMethods = Arrays.asList(path.getMethods()); + List supportedMethods = Arrays.asList(path.methods()); String requestMethod; if (entity != null) { if (false == restApi.isBodySupported()) { diff --git a/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/ESClientYamlSuiteTestCase.java b/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/ESClientYamlSuiteTestCase.java index 3729a09586e8..e70434f7225e 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/ESClientYamlSuiteTestCase.java +++ b/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/ESClientYamlSuiteTestCase.java @@ -314,7 +314,7 @@ public abstract class ESClientYamlSuiteTestCase extends ESRestTestCase { for (ClientYamlSuiteRestApi restApi : restSpec.getApis()) { if (restApi.isBodySupported()) { for (ClientYamlSuiteRestApi.Path path : restApi.getPaths()) { - List methodsList = Arrays.asList(path.getMethods()); + List methodsList = Arrays.asList(path.methods()); if (methodsList.contains("GET") && restApi.isBodySupported()) { if (methodsList.contains("POST") == false) { errorMessage.append("\n- ") @@ -494,7 +494,7 @@ public abstract class ESClientYamlSuiteTestCase extends ESRestTestCase { } private String errorMessage(ExecutableSection executableSection, Throwable t) { - return "Failure at [" + testCandidate.getSuitePath() + ":" + executableSection.getLocation().lineNumber + "]: " + t.getMessage(); + return "Failure at [" + testCandidate.getSuitePath() + ":" + executableSection.getLocation().lineNumber() + "]: " + t.getMessage(); } protected boolean randomizeContentType() { diff --git a/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/restspec/ClientYamlSuiteRestApi.java b/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/restspec/ClientYamlSuiteRestApi.java index b6264e0a6d5e..c936ff951664 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/restspec/ClientYamlSuiteRestApi.java +++ b/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/restspec/ClientYamlSuiteRestApi.java @@ -171,7 +171,7 @@ public class ClientYamlSuiteRestApi { for (ClientYamlSuiteRestApi.Path path : paths) { int matches = 0; for (String actualParameter : pathParams) { - if (path.getParts().contains(actualParameter)) { + if (path.parts().contains(actualParameter)) { matches++; } } @@ -193,28 +193,7 @@ public class ClientYamlSuiteRestApi { return pathsByRelevance; } - public static class Path { - private final String path; - private final String[] methods; - private final Set parts; - - private Path(String path, String[] methods, Set parts) { - this.path = path; - this.methods = methods; - this.parts = parts; - } - - public String getPath() { - return path; - } - - public String[] getMethods() { - return methods; - } - - public Set getParts() { - return parts; - } + public record Path(String path, String[] methods, Set parts) { @Override public boolean equals(Object o) { diff --git a/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/section/ClientYamlTestSuite.java b/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/section/ClientYamlTestSuite.java index 38fe230539e2..81961c774a72 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/section/ClientYamlTestSuite.java +++ b/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/section/ClientYamlTestSuite.java @@ -171,7 +171,7 @@ public class ClientYamlTestSuite { .map(section -> String.format(Locale.ROOT, """ attempted to add a [do] with a [warnings] section without a corresponding ["skip": "features": "warnings"] \ so runners that do not support the [warnings] section can skip the test at line [%d]\ - """, section.getLocation().lineNumber)); + """, section.getLocation().lineNumber())); errors = Stream.concat( errors, @@ -184,7 +184,7 @@ public class ClientYamlTestSuite { attempted to add a [do] with a [warnings_regex] section without a corresponding \ ["skip": "features": "warnings_regex"] so runners that do not support the [warnings_regex] \ section can skip the test at line [%d]\ - """, section.getLocation().lineNumber)) + """, section.getLocation().lineNumber())) ); errors = Stream.concat( @@ -198,7 +198,7 @@ public class ClientYamlTestSuite { attempted to add a [do] with a [allowed_warnings] section without a corresponding \ ["skip": "features": "allowed_warnings"] so runners that do not support the [allowed_warnings] \ section can skip the test at line [%d]\ - """, section.getLocation().lineNumber)) + """, section.getLocation().lineNumber())) ); errors = Stream.concat( @@ -212,7 +212,7 @@ public class ClientYamlTestSuite { attempted to add a [do] with a [allowed_warnings_regex] section without a corresponding \ ["skip": "features": "allowed_warnings_regex"] so runners that do not support the [allowed_warnings_regex] \ section can skip the test at line [%d]\ - """, section.getLocation().lineNumber)) + """, section.getLocation().lineNumber())) ); errors = Stream.concat( @@ -226,7 +226,7 @@ public class ClientYamlTestSuite { attempted to add a [do] with a [node_selector] section without a corresponding \ ["skip": "features": "node_selector"] so runners that do not support the [node_selector] section \ can skip the test at line [%d]\ - """, section.getLocation().lineNumber)) + """, section.getLocation().lineNumber())) ); errors = Stream.concat( @@ -237,7 +237,7 @@ public class ClientYamlTestSuite { .map(section -> String.format(Locale.ROOT, """ attempted to add a [contains] assertion without a corresponding ["skip": "features": "contains"] \ so runners that do not support the [contains] assertion can skip the test at line [%d]\ - """, section.getLocation().lineNumber)) + """, section.getLocation().lineNumber())) ); errors = Stream.concat( @@ -250,7 +250,7 @@ public class ClientYamlTestSuite { .map(section -> String.format(Locale.ROOT, """ attempted to add a [do] with a [headers] section without a corresponding ["skip": "features": "headers"] \ so runners that do not support the [headers] section can skip the test at line [%d]\ - """, section.getLocation().lineNumber)) + """, section.getLocation().lineNumber())) ); errors = Stream.concat( @@ -261,7 +261,7 @@ public class ClientYamlTestSuite { .map(section -> String.format(Locale.ROOT, """ attempted to add a [close_to] assertion without a corresponding ["skip": "features": "close_to"] \ so runners that do not support the [close_to] assertion can skip the test at line [%d]\ - """, section.getLocation().lineNumber)) + """, section.getLocation().lineNumber())) ); return errors; diff --git a/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/section/DoSection.java b/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/section/DoSection.java index fdc645b68ecf..23a7146561da 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/section/DoSection.java +++ b/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/section/DoSection.java @@ -465,7 +465,7 @@ public class DoSection implements ExecutableSection { if (warnings.next().endsWith(RestPutIndexTemplateAction.DEPRECATION_WARNING + "\"")) { logger.warn( "Test [{}] uses deprecated legacy index templates and should be updated to use composable templates", - (testPath == null ? "" : testPath) + ":" + getLocation().lineNumber + (testPath == null ? "" : testPath) + ":" + getLocation().lineNumber() ); warnings.remove(); } @@ -637,13 +637,10 @@ public class DoSection implements ExecutableSection { * first and then running the "left" selector on the results of the "right" * selector. */ - private static class ComposeNodeSelector implements NodeSelector { - private final NodeSelector lhs; - private final NodeSelector rhs; - - private ComposeNodeSelector(NodeSelector lhs, NodeSelector rhs) { - this.lhs = Objects.requireNonNull(lhs, "lhs is required"); - this.rhs = Objects.requireNonNull(rhs, "rhs is required"); + private record ComposeNodeSelector(NodeSelector lhs, NodeSelector rhs) implements NodeSelector { + private ComposeNodeSelector { + Objects.requireNonNull(lhs, "lhs is required"); + Objects.requireNonNull(rhs, "rhs is required"); } @Override @@ -652,23 +649,6 @@ public class DoSection implements ExecutableSection { lhs.select(nodes); } - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ComposeNodeSelector that = (ComposeNodeSelector) o; - return Objects.equals(lhs, that.lhs) && Objects.equals(rhs, that.rhs); - } - - @Override - public int hashCode() { - return Objects.hash(lhs, rhs); - } - @Override public String toString() { // . as in haskell's "compose" operator diff --git a/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/section/SkipSection.java b/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/section/SkipSection.java index ecf6ee4dc7ac..7e85ff77e54d 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/section/SkipSection.java +++ b/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/section/SkipSection.java @@ -131,11 +131,11 @@ public class SkipSection { } public Version getLowerVersion() { - return versionRanges.get(0).getLower(); + return versionRanges.get(0).lower(); } public Version getUpperVersion() { - return versionRanges.get(versionRanges.size() - 1).getUpper(); + return versionRanges.get(versionRanges.size() - 1).upper(); } public List getFeatures() { diff --git a/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/section/VersionRange.java b/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/section/VersionRange.java index d2655507d1a7..f4b9a3d4aef1 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/section/VersionRange.java +++ b/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/section/VersionRange.java @@ -9,22 +9,7 @@ package org.elasticsearch.test.rest.yaml.section; import org.elasticsearch.Version; -public class VersionRange { - private final Version lower; - private final Version upper; - - public VersionRange(Version lower, Version upper) { - this.lower = lower; - this.upper = upper; - } - - public Version getLower() { - return lower; - } - - public Version getUpper() { - return upper; - } +public record VersionRange(Version lower, Version upper) { public boolean contains(Version currentVersion) { return lower != null && upper != null && currentVersion.onOrAfter(lower) && currentVersion.onOrBefore(upper); diff --git a/test/framework/src/main/java/org/elasticsearch/test/transport/CapturingTransport.java b/test/framework/src/main/java/org/elasticsearch/test/transport/CapturingTransport.java index 2256c5cd1405..2f03303115e5 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/transport/CapturingTransport.java +++ b/test/framework/src/main/java/org/elasticsearch/test/transport/CapturingTransport.java @@ -25,19 +25,7 @@ import java.util.concurrent.BlockingQueue; */ public class CapturingTransport extends MockTransport implements Transport { - public static class CapturedRequest { - public final DiscoveryNode node; - public final long requestId; - public final String action; - public final TransportRequest request; - - CapturedRequest(DiscoveryNode node, long requestId, String action, TransportRequest request) { - this.node = node; - this.requestId = requestId; - this.action = action; - this.request = request; - } - } + public record CapturedRequest(DiscoveryNode node, long requestId, String action, TransportRequest request) {} private BlockingQueue capturedRequests = ConcurrentCollections.newBlockingQueue(); diff --git a/test/framework/src/test/java/org/elasticsearch/test/rest/yaml/restspec/ClientYamlSuiteRestApiParserTests.java b/test/framework/src/test/java/org/elasticsearch/test/rest/yaml/restspec/ClientYamlSuiteRestApiParserTests.java index 27367035a7df..8937d124d445 100644 --- a/test/framework/src/test/java/org/elasticsearch/test/rest/yaml/restspec/ClientYamlSuiteRestApiParserTests.java +++ b/test/framework/src/test/java/org/elasticsearch/test/rest/yaml/restspec/ClientYamlSuiteRestApiParserTests.java @@ -30,19 +30,19 @@ public class ClientYamlSuiteRestApiParserTests extends AbstractClientYamlTestFra Iterator iterator = restApi.getPaths().iterator(); { ClientYamlSuiteRestApi.Path next = iterator.next(); - assertThat(next.getPath(), equalTo("/{index}/{type}")); - assertThat(next.getMethods().length, equalTo(1)); - assertThat(next.getMethods()[0], equalTo("POST")); - assertThat(next.getParts().size(), equalTo(2)); - assertThat(next.getParts(), containsInAnyOrder("index", "type")); + assertThat(next.path(), equalTo("/{index}/{type}")); + assertThat(next.methods().length, equalTo(1)); + assertThat(next.methods()[0], equalTo("POST")); + assertThat(next.parts().size(), equalTo(2)); + assertThat(next.parts(), containsInAnyOrder("index", "type")); } { ClientYamlSuiteRestApi.Path next = iterator.next(); - assertThat(next.getPath(), equalTo("/{index}/{type}/{id}")); - assertThat(next.getMethods().length, equalTo(1)); - assertThat(next.getMethods()[0], equalTo("PUT")); - assertThat(next.getParts().size(), equalTo(3)); - assertThat(next.getParts(), containsInAnyOrder("id", "index", "type")); + assertThat(next.path(), equalTo("/{index}/{type}/{id}")); + assertThat(next.methods().length, equalTo(1)); + assertThat(next.methods()[0], equalTo("PUT")); + assertThat(next.parts().size(), equalTo(3)); + assertThat(next.parts(), containsInAnyOrder("id", "index", "type")); } assertThat(restApi.getParams().size(), equalTo(4)); assertThat(restApi.getParams().keySet(), containsInAnyOrder("wait_for_active_shards", "op_type", "routing", "refresh")); @@ -62,18 +62,18 @@ public class ClientYamlSuiteRestApiParserTests extends AbstractClientYamlTestFra Iterator iterator = restApi.getPaths().iterator(); { ClientYamlSuiteRestApi.Path next = iterator.next(); - assertThat(next.getPath(), equalTo("/_template")); - assertThat(next.getMethods().length, equalTo(1)); - assertThat(next.getMethods()[0], equalTo("GET")); - assertEquals(0, next.getParts().size()); + assertThat(next.path(), equalTo("/_template")); + assertThat(next.methods().length, equalTo(1)); + assertThat(next.methods()[0], equalTo("GET")); + assertEquals(0, next.parts().size()); } { ClientYamlSuiteRestApi.Path next = iterator.next(); - assertThat(next.getPath(), equalTo("/_template/{name}")); - assertThat(next.getMethods().length, equalTo(1)); - assertThat(next.getMethods()[0], equalTo("GET")); - assertThat(next.getParts().size(), equalTo(1)); - assertThat(next.getParts(), contains("name")); + assertThat(next.path(), equalTo("/_template/{name}")); + assertThat(next.methods().length, equalTo(1)); + assertThat(next.methods()[0], equalTo("GET")); + assertThat(next.parts().size(), equalTo(1)); + assertThat(next.parts(), contains("name")); } assertThat(restApi.getParams().size(), equalTo(0)); assertThat(restApi.isBodySupported(), equalTo(false)); @@ -91,28 +91,28 @@ public class ClientYamlSuiteRestApiParserTests extends AbstractClientYamlTestFra Iterator iterator = restApi.getPaths().iterator(); { ClientYamlSuiteRestApi.Path next = iterator.next(); - assertThat(next.getPath(), equalTo("/_count")); - assertThat(next.getMethods().length, equalTo(2)); - assertThat(next.getMethods()[0], equalTo("POST")); - assertThat(next.getMethods()[1], equalTo("GET")); - assertEquals(0, next.getParts().size()); + assertThat(next.path(), equalTo("/_count")); + assertThat(next.methods().length, equalTo(2)); + assertThat(next.methods()[0], equalTo("POST")); + assertThat(next.methods()[1], equalTo("GET")); + assertEquals(0, next.parts().size()); } { ClientYamlSuiteRestApi.Path next = iterator.next(); - assertThat(next.getPath(), equalTo("/{index}/_count")); - assertThat(next.getMethods().length, equalTo(2)); - assertThat(next.getMethods()[0], equalTo("POST")); - assertThat(next.getMethods()[1], equalTo("GET")); - assertEquals(1, next.getParts().size()); - assertThat(next.getParts(), contains("index")); + assertThat(next.path(), equalTo("/{index}/_count")); + assertThat(next.methods().length, equalTo(2)); + assertThat(next.methods()[0], equalTo("POST")); + assertThat(next.methods()[1], equalTo("GET")); + assertEquals(1, next.parts().size()); + assertThat(next.parts(), contains("index")); } { ClientYamlSuiteRestApi.Path next = iterator.next(); - assertThat(next.getPath(), equalTo("/{index}/{type}/_count")); - assertThat(next.getMethods().length, equalTo(2)); - assertThat(next.getMethods()[0], equalTo("POST")); - assertThat(next.getMethods()[1], equalTo("GET")); - assertThat(next.getParts(), containsInAnyOrder("index", "type")); + assertThat(next.path(), equalTo("/{index}/{type}/_count")); + assertThat(next.methods().length, equalTo(2)); + assertThat(next.methods()[0], equalTo("POST")); + assertThat(next.methods()[1], equalTo("GET")); + assertThat(next.parts(), containsInAnyOrder("index", "type")); } assertThat(restApi.getParams().size(), equalTo(1)); assertThat(restApi.getParams().keySet(), contains("ignore_unavailable")); @@ -151,7 +151,7 @@ public class ClientYamlSuiteRestApiParserTests extends AbstractClientYamlTestFra assertThat(restApi, notNullValue()); assertThat(restApi.getPaths().size(), equalTo(1)); - assertThat(restApi.getPaths().iterator().next().getParts().isEmpty(), equalTo(true)); + assertThat(restApi.getPaths().iterator().next().parts().isEmpty(), equalTo(true)); assertThat(restApi.getParams().isEmpty(), equalTo(true)); assertThat(restApi.isBodyRequired(), equalTo(true)); } diff --git a/test/framework/src/test/java/org/elasticsearch/test/rest/yaml/restspec/ClientYamlSuiteRestApiTests.java b/test/framework/src/test/java/org/elasticsearch/test/rest/yaml/restspec/ClientYamlSuiteRestApiTests.java index ccff64e0fd79..f56f7390fa11 100644 --- a/test/framework/src/test/java/org/elasticsearch/test/rest/yaml/restspec/ClientYamlSuiteRestApiTests.java +++ b/test/framework/src/test/java/org/elasticsearch/test/rest/yaml/restspec/ClientYamlSuiteRestApiTests.java @@ -36,34 +36,34 @@ public class ClientYamlSuiteRestApiTests extends ESTestCase { { List paths = restApi.getBestMatchingPaths(Collections.emptySet()); assertEquals(1, paths.size()); - assertEquals("/_doc", paths.get(0).getPath()); + assertEquals("/_doc", paths.get(0).path()); } { List paths = restApi.getBestMatchingPaths(Collections.singleton("wait_for_active_shards")); assertEquals(1, paths.size()); - assertEquals("/_doc", paths.get(0).getPath()); + assertEquals("/_doc", paths.get(0).path()); } { List paths = restApi.getBestMatchingPaths(Collections.singleton("index")); assertEquals(1, paths.size()); - assertEquals("/{index}/_doc", paths.get(0).getPath()); + assertEquals("/{index}/_doc", paths.get(0).path()); } { List paths = restApi.getBestMatchingPaths(Set.of("index", "id")); assertEquals(1, paths.size()); - assertEquals("/{index}/_doc/{id}", paths.get(0).getPath()); + assertEquals("/{index}/_doc/{id}", paths.get(0).path()); } { List paths = restApi.getBestMatchingPaths(Set.of("index", "type")); assertEquals(3, paths.size()); - assertEquals("/{index}/_mapping/{type}", paths.get(0).getPath()); - assertEquals("/{index}/{type}", paths.get(1).getPath()); - assertEquals("/{index}/_mappings/{type}", paths.get(2).getPath()); + assertEquals("/{index}/_mapping/{type}", paths.get(0).path()); + assertEquals("/{index}/{type}", paths.get(1).path()); + assertEquals("/{index}/_mappings/{type}", paths.get(2).path()); } { List paths = restApi.getBestMatchingPaths(Set.of("index", "type", "id")); assertEquals(1, paths.size()); - assertEquals("/{index}/{type}/{id}", paths.get(0).getPath()); + assertEquals("/{index}/{type}/{id}", paths.get(0).path()); } } diff --git a/test/logger-usage/src/main/java/org/elasticsearch/test/loggerusage/ESLoggerUsageChecker.java b/test/logger-usage/src/main/java/org/elasticsearch/test/loggerusage/ESLoggerUsageChecker.java index c2ba1f4e3384..bbf578429a13 100644 --- a/test/logger-usage/src/main/java/org/elasticsearch/test/loggerusage/ESLoggerUsageChecker.java +++ b/test/logger-usage/src/main/java/org/elasticsearch/test/loggerusage/ESLoggerUsageChecker.java @@ -109,40 +109,7 @@ public class ESLoggerUsageChecker { cr.accept(new ClassChecker(wrongUsageCallback, methodsToCheck), 0); } - public static class WrongLoggerUsage { - private final String className; - private final String methodName; - private final String logMethodName; - private final int line; - private final String errorMessage; - - public WrongLoggerUsage(String className, String methodName, String logMethodName, int line, String errorMessage) { - this.className = className; - this.methodName = methodName; - this.logMethodName = logMethodName; - this.line = line; - this.errorMessage = errorMessage; - } - - @Override - public String toString() { - return "WrongLoggerUsage{" - + "className='" - + className - + '\'' - + ", methodName='" - + methodName - + '\'' - + ", logMethodName='" - + logMethodName - + '\'' - + ", line=" - + line - + ", errorMessage='" - + errorMessage - + '\'' - + '}'; - } + public record WrongLoggerUsage(String className, String methodName, String logMethodName, int line, String errorMessage) { /** * Returns an error message that has the form of stack traces emitted by {@link Throwable#printStackTrace} diff --git a/x-pack/plugin/ccr/src/test/java/org/elasticsearch/xpack/CcrIntegTestCase.java b/x-pack/plugin/ccr/src/test/java/org/elasticsearch/xpack/CcrIntegTestCase.java index 534ea38fdbce..4fa728249b59 100644 --- a/x-pack/plugin/ccr/src/test/java/org/elasticsearch/xpack/CcrIntegTestCase.java +++ b/x-pack/plugin/ccr/src/test/java/org/elasticsearch/xpack/CcrIntegTestCase.java @@ -694,7 +694,7 @@ public abstract class CcrIntegTestCase extends ESTestCase { shardRouting.shardId().id(), docsOnShard.stream() // normalize primary term as the follower use its own term - .map(d -> new DocIdSeqNoAndSource(d.getId(), d.getSource(), d.getSeqNo(), 1L, d.getVersion())) + .map(d -> new DocIdSeqNoAndSource(d.id(), d.source(), d.seqNo(), 1L, d.version())) .collect(Collectors.toList()) ); } catch (AlreadyClosedException e) { diff --git a/x-pack/plugin/ccr/src/test/java/org/elasticsearch/xpack/ccr/action/ShardFollowTaskReplicationTests.java b/x-pack/plugin/ccr/src/test/java/org/elasticsearch/xpack/ccr/action/ShardFollowTaskReplicationTests.java index de1feb86440b..d5307477a6cd 100644 --- a/x-pack/plugin/ccr/src/test/java/org/elasticsearch/xpack/ccr/action/ShardFollowTaskReplicationTests.java +++ b/x-pack/plugin/ccr/src/test/java/org/elasticsearch/xpack/ccr/action/ShardFollowTaskReplicationTests.java @@ -739,7 +739,7 @@ public class ShardFollowTaskReplicationTests extends ESIndexLevelReplicationTest boolean assertMaxSeqNoOfUpdatesOrDeletes ) throws Exception { final List> docAndSeqNosOnLeader = getDocIdAndSeqNos(leader.getPrimary()).stream() - .map(d -> Tuple.tuple(d.getId(), d.getSeqNo())) + .map(d -> Tuple.tuple(d.id(), d.seqNo())) .collect(Collectors.toList()); final Map operationsOnLeader = new HashMap<>(); try ( @@ -759,7 +759,7 @@ public class ShardFollowTaskReplicationTests extends ESIndexLevelReplicationTest ); } List> docAndSeqNosOnFollower = getDocIdAndSeqNos(followingShard).stream() - .map(d -> Tuple.tuple(d.getId(), d.getSeqNo())) + .map(d -> Tuple.tuple(d.id(), d.seqNo())) .collect(Collectors.toList()); assertThat(docAndSeqNosOnFollower, equalTo(docAndSeqNosOnLeader)); try ( diff --git a/x-pack/plugin/ccr/src/test/java/org/elasticsearch/xpack/ccr/index/engine/FollowingEngineTests.java b/x-pack/plugin/ccr/src/test/java/org/elasticsearch/xpack/ccr/index/engine/FollowingEngineTests.java index 926afcb13d6e..5886fd92eace 100644 --- a/x-pack/plugin/ccr/src/test/java/org/elasticsearch/xpack/ccr/index/engine/FollowingEngineTests.java +++ b/x-pack/plugin/ccr/src/test/java/org/elasticsearch/xpack/ccr/index/engine/FollowingEngineTests.java @@ -408,7 +408,7 @@ public class FollowingEngineTests extends ESTestCase { // Apply optimization for documents that do not exist long moreDocs = between(1, 100); versionLookUps = getNumVersionLookups(follower); - Set docIds = getDocIds(follower, true).stream().map(doc -> doc.getId()).collect(Collectors.toSet()); + Set docIds = getDocIds(follower, true).stream().map(doc -> doc.id()).collect(Collectors.toSet()); for (int i = 0; i < moreDocs; i++) { String docId = randomValueOtherThanMany(docIds::contains, () -> Integer.toString(between(1, 1000))); docIds.add(docId); @@ -805,7 +805,7 @@ public class FollowingEngineTests extends ESTestCase { } } for (DocIdSeqNoAndSource docId : getDocIds(followingEngine, true)) { - assertThat(docId.getPrimaryTerm(), equalTo(operationWithTerms.get(docId.getSeqNo()))); + assertThat(docId.primaryTerm(), equalTo(operationWithTerms.get(docId.seqNo()))); } // Replica should accept duplicates primaryTerm.set(newTerm); @@ -819,7 +819,7 @@ public class FollowingEngineTests extends ESTestCase { assertThat(result.getResultType(), equalTo(Engine.Result.Type.SUCCESS)); } for (DocIdSeqNoAndSource docId : getDocIds(followingEngine, true)) { - assertThat(docId.getPrimaryTerm(), equalTo(operationWithTerms.get(docId.getSeqNo()))); + assertThat(docId.primaryTerm(), equalTo(operationWithTerms.get(docId.seqNo()))); } } } diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/dataframe/evaluation/common/AbstractAucRoc.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/dataframe/evaluation/common/AbstractAucRoc.java index 25eb993e7205..cd74f4e86eb8 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/dataframe/evaluation/common/AbstractAucRoc.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/dataframe/evaluation/common/AbstractAucRoc.java @@ -160,15 +160,7 @@ public abstract class AbstractAucRoc implements EvaluationMetric { return aucRoc; } - private static class RateThresholdCurve { - - private final double[] percentiles; - private final boolean isTp; - - private RateThresholdCurve(double[] percentiles, boolean isTp) { - this.percentiles = percentiles; - this.isTp = isTp; - } + private record RateThresholdCurve(double[] percentiles, boolean isTp) { private double getRate(int index) { return 1 - 0.01 * (index + 1); diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/CommandLineHttpClient.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/CommandLineHttpClient.java index a74313121501..4b1285cfe8a7 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/CommandLineHttpClient.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/CommandLineHttpClient.java @@ -157,7 +157,7 @@ public class CommandLineHttpClient { final SslConfiguration sslConfiguration = sslService.getHttpTransportSSLConfiguration(); // Requires permission java.lang.RuntimePermission "setFactory"; httpsConn.setSSLSocketFactory(sslService.sslSocketFactory(sslConfiguration)); - final boolean isHostnameVerificationEnabled = sslConfiguration.getVerificationMode().isHostnameVerificationEnabled(); + final boolean isHostnameVerificationEnabled = sslConfiguration.verificationMode().isHostnameVerificationEnabled(); if (isHostnameVerificationEnabled == false) { httpsConn.setHostnameVerifier((hostname, session) -> true); } diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ssl/SSLService.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ssl/SSLService.java index 51924b3080b7..a817f417170a 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ssl/SSLService.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ssl/SSLService.java @@ -230,10 +230,10 @@ public class SSLService { public SSLIOSessionStrategy sslIOSessionStrategy(SslConfiguration config) { SSLContext sslContext = sslContext(config); String[] ciphers = supportedCiphers(sslParameters(sslContext).getCipherSuites(), config.getCipherSuites(), false); - String[] supportedProtocols = config.getSupportedProtocols().toArray(Strings.EMPTY_ARRAY); + String[] supportedProtocols = config.supportedProtocols().toArray(Strings.EMPTY_ARRAY); HostnameVerifier verifier; - if (config.getVerificationMode().isHostnameVerificationEnabled()) { + if (config.verificationMode().isHostnameVerificationEnabled()) { verifier = SSLIOSessionStrategy.getDefaultHostnameVerifier(); } else { verifier = NoopHostnameVerifier.INSTANCE; @@ -244,7 +244,7 @@ public class SSLService { } public static HostnameVerifier getHostnameVerifier(SslConfiguration sslConfiguration) { - if (sslConfiguration.getVerificationMode().isHostnameVerificationEnabled()) { + if (sslConfiguration.verificationMode().isHostnameVerificationEnabled()) { return new DefaultHostnameVerifier(); } else { return NoopHostnameVerifier.INSTANCE; @@ -306,7 +306,7 @@ public class SSLService { SSLSocketFactory socketFactory = contextHolder.sslContext().getSocketFactory(); final SecuritySSLSocketFactory securitySSLSocketFactory = new SecuritySSLSocketFactory( () -> contextHolder.sslContext().getSocketFactory(), - configuration.getSupportedProtocols().toArray(Strings.EMPTY_ARRAY), + configuration.supportedProtocols().toArray(Strings.EMPTY_ARRAY), supportedCiphers(socketFactory.getSupportedCipherSuites(), configuration.getCipherSuites(), false) ); contextHolder.addReloadListener(securitySSLSocketFactory::reload); @@ -329,9 +329,9 @@ public class SSLService { SSLContext sslContext = sslContext(configuration); SSLEngine sslEngine = sslContext.createSSLEngine(host, port); String[] ciphers = supportedCiphers(sslEngine.getSupportedCipherSuites(), configuration.getCipherSuites(), false); - String[] supportedProtocols = configuration.getSupportedProtocols().toArray(Strings.EMPTY_ARRAY); + String[] supportedProtocols = configuration.supportedProtocols().toArray(Strings.EMPTY_ARRAY); SSLParameters parameters = new SSLParameters(ciphers, supportedProtocols); - if (configuration.getVerificationMode().isHostnameVerificationEnabled() && host != null) { + if (configuration.verificationMode().isHostnameVerificationEnabled() && host != null) { // By default, an SSLEngine will not perform hostname verification. In order to perform hostname verification // we need to specify a EndpointIdentificationAlgorithm. We use the HTTPS algorithm to prevent against // man in the middle attacks for all of our connections. @@ -339,7 +339,7 @@ public class SSLService { } // we use the cipher suite order so that we can prefer the ciphers we set first in the list parameters.setUseCipherSuitesOrder(true); - configuration.getClientAuth().configure(parameters); + configuration.clientAuth().configure(parameters); // many SSLEngine options can be configured using either SSLParameters or direct methods on the engine itself, but there is one // tricky aspect; if you set a value directly on the engine and then later set the SSLParameters the value set directly on the @@ -355,7 +355,7 @@ public class SSLService { */ public boolean isConfigurationValidForServerUsage(SslConfiguration sslConfiguration) { Objects.requireNonNull(sslConfiguration, "SslConfiguration cannot be null"); - return sslConfiguration.getKeyConfig().hasKeyMaterial(); + return sslConfiguration.keyConfig().hasKeyMaterial(); } /** @@ -363,7 +363,7 @@ public class SSLService { */ public boolean isSSLClientAuthEnabled(SslConfiguration sslConfiguration) { Objects.requireNonNull(sslConfiguration, "SslConfiguration cannot be null"); - return sslConfiguration.getClientAuth().enabled(); + return sslConfiguration.clientAuth().enabled(); } /** @@ -469,8 +469,8 @@ public class SSLService { if (logger.isDebugEnabled()) { logger.debug("using ssl settings [{}]", sslConfiguration); } - X509ExtendedTrustManager trustManager = sslConfiguration.getTrustConfig().createTrustManager(); - X509ExtendedKeyManager keyManager = sslConfiguration.getKeyConfig().createKeyManager(); + X509ExtendedTrustManager trustManager = sslConfiguration.trustConfig().createTrustManager(); + X509ExtendedKeyManager keyManager = sslConfiguration.keyConfig().createKeyManager(); return createSslContext(keyManager, trustManager, sslConfiguration); } @@ -490,7 +490,7 @@ public class SSLService { trustManager = wrapWithDiagnostics(trustManager, sslConfiguration); // Initialize sslContext try { - SSLContext sslContext = SSLContext.getInstance(sslContextAlgorithm(sslConfiguration.getSupportedProtocols())); + SSLContext sslContext = SSLContext.getInstance(sslContextAlgorithm(sslConfiguration.supportedProtocols())); sslContext.init(new X509ExtendedKeyManager[] { keyManager }, new X509ExtendedTrustManager[] { trustManager }, null); // check the supported ciphers and log them here to prevent spamming logs on every call @@ -521,7 +521,7 @@ public class SSLService { case 1 -> names.get(0); default -> "(shared)"; }; - return name + " (with trust configuration: " + configuration.getTrustConfig() + ")"; + return name + " (with trust configuration: " + configuration.trustConfig() + ")"; }; trustManager = new DiagnosticTrustManager(trustManager, contextName, diagnosticLogger::warn); } @@ -669,9 +669,7 @@ public class SSLService { .stream() .map(SslConfiguration::getConfiguredCertificates) .flatMap(Collection::stream) - .map( - cert -> new CertificateInfo(cert.getPath(), cert.getFormat(), cert.getAlias(), cert.hasPrivateKey(), cert.getCertificate()) - ) + .map(cert -> new CertificateInfo(cert.path(), cert.format(), cert.alias(), cert.hasPrivateKey(), cert.certificate())) .collect(Sets.toUnmodifiableSortedSet()); } @@ -774,8 +772,8 @@ public class SSLService { SSLContextHolder(SSLContext context, SslConfiguration sslConfiguration) { this.context = context; this.sslConfiguration = sslConfiguration; - this.keyConfig = sslConfiguration.getKeyConfig(); - this.trustConfig = sslConfiguration.getTrustConfig(); + this.keyConfig = sslConfiguration.keyConfig(); + this.trustConfig = sslConfiguration.trustConfig(); this.reloadListeners = new ArrayList<>(); } @@ -796,7 +794,7 @@ public class SSLService { X509ExtendedTrustManager loadedTrustManager = trustConfig.createTrustManager(); loadedTrustManager = wrapWithDiagnostics(loadedTrustManager, sslConfiguration); - SSLContext loadedSslContext = SSLContext.getInstance(sslContextAlgorithm(sslConfiguration.getSupportedProtocols())); + SSLContext loadedSslContext = SSLContext.getInstance(sslContextAlgorithm(sslConfiguration.supportedProtocols())); loadedSslContext.init( new X509ExtendedKeyManager[] { loadedKeyManager }, new X509ExtendedTrustManager[] { loadedTrustManager }, diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/actions/ActionStatus.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/actions/ActionStatus.java index 9279662ffbb0..b8829546e9a9 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/actions/ActionStatus.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/actions/ActionStatus.java @@ -323,7 +323,7 @@ public class ActionStatus implements ToXContentObject { } } - public static class Execution implements ToXContentObject { + public record Execution(ZonedDateTime timestamp, boolean successful, String reason) implements ToXContentObject { public static Execution successful(ZonedDateTime timestamp) { return new Execution(timestamp, true, null); @@ -333,45 +333,12 @@ public class ActionStatus implements ToXContentObject { return new Execution(timestamp, false, reason); } - private final ZonedDateTime timestamp; - private final boolean successful; - private final String reason; - - private Execution(ZonedDateTime timestamp, boolean successful, String reason) { + public Execution(ZonedDateTime timestamp, boolean successful, String reason) { this.timestamp = timestamp.withZoneSameInstant(ZoneOffset.UTC); this.successful = successful; this.reason = reason; } - public ZonedDateTime timestamp() { - return timestamp; - } - - public boolean successful() { - return successful; - } - - public String reason() { - return reason; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - Execution execution = (Execution) o; - - return Objects.equals(successful, execution.successful) - && Objects.equals(timestamp, execution.timestamp) - && Objects.equals(reason, execution.reason); - } - - @Override - public int hashCode() { - return Objects.hash(timestamp, successful, reason); - } - @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); @@ -460,38 +427,13 @@ public class ActionStatus implements ToXContentObject { } } - public static class Throttle implements ToXContentObject { - - private final ZonedDateTime timestamp; - private final String reason; + public record Throttle(ZonedDateTime timestamp, String reason) implements ToXContentObject { public Throttle(ZonedDateTime timestamp, String reason) { this.timestamp = timestamp.withZoneSameInstant(ZoneOffset.UTC); this.reason = reason; } - public ZonedDateTime timestamp() { - return timestamp; - } - - public String reason() { - return reason; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - Throttle throttle = (Throttle) o; - return Objects.equals(timestamp, throttle.timestamp) && Objects.equals(reason, throttle.reason); - } - - @Override - public int hashCode() { - return Objects.hash(timestamp, reason); - } - @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { return builder.startObject() diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ssl/SSLServiceTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ssl/SSLServiceTests.java index 13b080fe0d7d..9c04b7078c3d 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ssl/SSLServiceTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ssl/SSLServiceTests.java @@ -300,7 +300,7 @@ public class SSLServiceTests extends ESTestCase { final SslConfiguration sslConfiguration = sslService.getSSLConfiguration("xpack.security.transport.ssl"); assertThat(sslConfiguration, notNullValue()); - final SslTrustConfig trust = sslConfiguration.getTrustConfig(); + final SslTrustConfig trust = sslConfiguration.trustConfig(); assertThat(trust, notNullValue()); final Collection files = trust.getDependentFiles(); assertThat(files, hasItem(testnodeStore)); @@ -351,7 +351,7 @@ public class SSLServiceTests extends ESTestCase { assumeFalse("Can't run in a FIPS JVM, TrustAllConfig is not a SunJSSE TrustManagers", inFipsJvm()); SSLService sslService = new SSLService(env); assertThat( - sslService.getSSLConfiguration("xpack.security.transport.ssl").getVerificationMode(), + sslService.getSSLConfiguration("xpack.security.transport.ssl").verificationMode(), is(XPackSettings.VERIFICATION_MODE_DEFAULT) ); @@ -361,19 +361,16 @@ public class SSLServiceTests extends ESTestCase { .put("transport.profiles.foo.xpack.security.ssl.verification_mode", "full") .build(); sslService = new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(settings))); + assertThat(sslService.getSSLConfiguration("xpack.security.transport.ssl.").verificationMode(), is(SslVerificationMode.CERTIFICATE)); assertThat( - sslService.getSSLConfiguration("xpack.security.transport.ssl.").getVerificationMode(), - is(SslVerificationMode.CERTIFICATE) - ); - assertThat( - sslService.getSSLConfiguration("transport.profiles.foo.xpack.security.ssl.").getVerificationMode(), + sslService.getSSLConfiguration("transport.profiles.foo.xpack.security.ssl.").verificationMode(), is(SslVerificationMode.FULL) ); } public void testIsSSLClientAuthEnabled() throws Exception { SSLService sslService = new SSLService(env); - assertTrue(sslService.getSSLConfiguration("xpack.security.transport.ssl").getClientAuth().enabled()); + assertTrue(sslService.getSSLConfiguration("xpack.security.transport.ssl").clientAuth().enabled()); Settings settings = Settings.builder() .put("xpack.security.transport.ssl.enabled", false) @@ -403,10 +400,10 @@ public class SSLServiceTests extends ESTestCase { final SSLService sslService = new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(globalSettings))); final SslConfiguration globalConfig = sslService.getSSLConfiguration("xpack.security.transport.ssl"); - assertThat(globalConfig.getClientAuth(), is(SslClientAuthenticationMode.OPTIONAL)); + assertThat(globalConfig.clientAuth(), is(SslClientAuthenticationMode.OPTIONAL)); final SslConfiguration httpConfig = sslService.getHttpTransportSSLConfiguration(); - assertThat(httpConfig.getClientAuth(), is(SslClientAuthenticationMode.NONE)); + assertThat(httpConfig.clientAuth(), is(SslClientAuthenticationMode.NONE)); } public void testThatTruststorePasswordIsRequired() throws Exception { @@ -517,7 +514,7 @@ public class SSLServiceTests extends ESTestCase { final String[] ciphers = sslService.supportedCiphers(factory.getSupportedCipherSuites(), config.getCipherSuites(), false); assertThat(factory.getDefaultCipherSuites(), is(ciphers)); - final String[] getSupportedProtocols = config.getSupportedProtocols().toArray(Strings.EMPTY_ARRAY); + final String[] getSupportedProtocols = config.supportedProtocols().toArray(Strings.EMPTY_ARRAY); try (SSLSocket socket = (SSLSocket) factory.createSocket()) { assertThat(socket.getEnabledCipherSuites(), is(ciphers)); // the order we set the protocols in is not going to be what is returned as internally the JDK may sort the versions @@ -541,7 +538,7 @@ public class SSLServiceTests extends ESTestCase { SslConfiguration configuration = sslService.getSSLConfiguration("xpack.security.transport.ssl"); SSLEngine engine = sslService.createSSLEngine(configuration, null, -1); final String[] ciphers = sslService.supportedCiphers(engine.getSupportedCipherSuites(), configuration.getCipherSuites(), false); - final String[] getSupportedProtocols = configuration.getSupportedProtocols().toArray(Strings.EMPTY_ARRAY); + final String[] getSupportedProtocols = configuration.supportedProtocols().toArray(Strings.EMPTY_ARRAY); assertThat(engine.getEnabledCipherSuites(), is(ciphers)); assertArrayEquals(ciphers, engine.getSSLParameters().getCipherSuites()); // the order we set the protocols in is not going to be what is returned as internally the JDK may sort the versions @@ -642,7 +639,7 @@ public class SSLServiceTests extends ESTestCase { final String name = contextNames[i]; final SslConfiguration configuration = sslService.getSSLConfiguration(name); assertThat("Configuration for " + name, configuration, notNullValue()); - final SslKeyConfig keyConfig = configuration.getKeyConfig(); + final SslKeyConfig keyConfig = configuration.keyConfig(); assertThat("KeyStore Path for " + name, keyConfig.getDependentFiles(), contains(testnodeStore)); assertThat("Cipher for " + name, configuration.getCipherSuites(), contains(getCipherSuites[i])); assertThat("Configuration for " + name + ".", sslService.getSSLConfiguration(name + "."), sameInstance(configuration)); diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ssl/SslSettingsLoaderTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ssl/SslSettingsLoaderTests.java index e21a91772c80..97114eecc7c0 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ssl/SslSettingsLoaderTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ssl/SslSettingsLoaderTests.java @@ -64,10 +64,10 @@ public class SslSettingsLoaderTests extends ESTestCase { public void testThatSslConfigurationHasCorrectDefaults() { SslConfiguration globalConfig = getSslConfiguration(Settings.EMPTY); - assertThat(globalConfig.getKeyConfig(), sameInstance(EmptyKeyConfig.INSTANCE)); - assertThat(globalConfig.getTrustConfig().getClass().getSimpleName(), is("DefaultJdkTrustConfig")); - assertThat(globalConfig.getSupportedProtocols(), equalTo(XPackSettings.DEFAULT_SUPPORTED_PROTOCOLS)); - assertThat(globalConfig.getSupportedProtocols(), not(hasItem("TLSv1"))); + assertThat(globalConfig.keyConfig(), sameInstance(EmptyKeyConfig.INSTANCE)); + assertThat(globalConfig.trustConfig().getClass().getSimpleName(), is("DefaultJdkTrustConfig")); + assertThat(globalConfig.supportedProtocols(), equalTo(XPackSettings.DEFAULT_SUPPORTED_PROTOCOLS)); + assertThat(globalConfig.supportedProtocols(), not(hasItem("TLSv1"))); } public void testThatOnlyKeystoreInSettingsSetsTruststoreSettings() { @@ -77,8 +77,8 @@ public class SslSettingsLoaderTests extends ESTestCase { Settings settings = Settings.builder().put("keystore.path", path).setSecureSettings(secureSettings).build(); // Pass settings in as component settings SslConfiguration sslConfiguration = getSslConfiguration(settings); - assertThat(sslConfiguration.getKeyConfig(), instanceOf(StoreKeyConfig.class)); - SslKeyConfig keyStore = sslConfiguration.getKeyConfig(); + assertThat(sslConfiguration.keyConfig(), instanceOf(StoreKeyConfig.class)); + SslKeyConfig keyStore = sslConfiguration.keyConfig(); assertThat(keyStore.getDependentFiles(), contains(path)); assertThat(keyStore.hasKeyMaterial(), is(true)); @@ -104,8 +104,8 @@ public class SslSettingsLoaderTests extends ESTestCase { environment, ks -> KeyStoreUtil.filter(ks, e -> e.getAlias().endsWith("sa")) // "_dsa" & "_rsa" but not "_ec" ); - assertThat(sslConfiguration.getKeyConfig(), instanceOf(StoreKeyConfig.class)); - StoreKeyConfig keyStore = (StoreKeyConfig) sslConfiguration.getKeyConfig(); + assertThat(sslConfiguration.keyConfig(), instanceOf(StoreKeyConfig.class)); + StoreKeyConfig keyStore = (StoreKeyConfig) sslConfiguration.keyConfig(); assertThat(keyStore.getDependentFiles(), contains(path)); assertThat(keyStore.hasKeyMaterial(), is(true)); @@ -135,8 +135,8 @@ public class SslSettingsLoaderTests extends ESTestCase { .setSecureSettings(secureSettings) .build(); SslConfiguration sslConfiguration = getSslConfiguration(settings); - assertThat(sslConfiguration.getKeyConfig(), instanceOf(StoreKeyConfig.class)); - StoreKeyConfig ksKeyInfo = (StoreKeyConfig) sslConfiguration.getKeyConfig(); + assertThat(sslConfiguration.keyConfig(), instanceOf(StoreKeyConfig.class)); + StoreKeyConfig ksKeyInfo = (StoreKeyConfig) sslConfiguration.keyConfig(); assertThat( ksKeyInfo, equalTo(new StoreKeyConfig("path", PASSWORD, "type", null, PASSWORD, KEY_MGR_ALGORITHM, environment.configFile())) @@ -150,8 +150,8 @@ public class SslSettingsLoaderTests extends ESTestCase { .put("keystore.password", "password") .build(); SslConfiguration sslConfiguration = getSslConfiguration(settings); - assertThat(sslConfiguration.getKeyConfig(), instanceOf(StoreKeyConfig.class)); - StoreKeyConfig ksKeyInfo = (StoreKeyConfig) sslConfiguration.getKeyConfig(); + assertThat(sslConfiguration.keyConfig(), instanceOf(StoreKeyConfig.class)); + StoreKeyConfig ksKeyInfo = (StoreKeyConfig) sslConfiguration.keyConfig(); assertThat( ksKeyInfo, equalTo(new StoreKeyConfig("path", PASSWORD, "type", null, PASSWORD, KEY_MGR_ALGORITHM, environment.configFile())) @@ -169,8 +169,8 @@ public class SslSettingsLoaderTests extends ESTestCase { .setSecureSettings(secureSettings) .build(); SslConfiguration sslConfiguration = getSslConfiguration(settings); - assertThat(sslConfiguration.getKeyConfig(), instanceOf(StoreKeyConfig.class)); - StoreKeyConfig ksKeyInfo = (StoreKeyConfig) sslConfiguration.getKeyConfig(); + assertThat(sslConfiguration.keyConfig(), instanceOf(StoreKeyConfig.class)); + StoreKeyConfig ksKeyInfo = (StoreKeyConfig) sslConfiguration.keyConfig(); assertThat( ksKeyInfo, equalTo(new StoreKeyConfig("path", PASSWORD, "type", null, KEYPASS, KEY_MGR_ALGORITHM, environment.configFile())) @@ -185,8 +185,8 @@ public class SslSettingsLoaderTests extends ESTestCase { .put("keystore.key_password", "keypass") .build(); SslConfiguration sslConfiguration = getSslConfiguration(settings); - assertThat(sslConfiguration.getKeyConfig(), instanceOf(StoreKeyConfig.class)); - StoreKeyConfig ksKeyInfo = (StoreKeyConfig) sslConfiguration.getKeyConfig(); + assertThat(sslConfiguration.keyConfig(), instanceOf(StoreKeyConfig.class)); + StoreKeyConfig ksKeyInfo = (StoreKeyConfig) sslConfiguration.keyConfig(); assertThat( ksKeyInfo, equalTo(new StoreKeyConfig("path", PASSWORD, "type", null, KEYPASS, KEY_MGR_ALGORITHM, environment.configFile())) @@ -204,8 +204,8 @@ public class SslSettingsLoaderTests extends ESTestCase { secureSettings.setString("keystore.secure_key_password", "keypass"); Settings settings = Settings.builder().put("keystore.path", "xpack/tls/path.jks").setSecureSettings(secureSettings).build(); SslConfiguration sslConfiguration = getSslConfiguration(settings); - assertThat(sslConfiguration.getKeyConfig(), instanceOf(StoreKeyConfig.class)); - StoreKeyConfig ksKeyInfo = (StoreKeyConfig) sslConfiguration.getKeyConfig(); + assertThat(sslConfiguration.keyConfig(), instanceOf(StoreKeyConfig.class)); + StoreKeyConfig ksKeyInfo = (StoreKeyConfig) sslConfiguration.keyConfig(); assertThat( ksKeyInfo, equalTo(new StoreKeyConfig("xpack/tls/path.jks", PASSWORD, "jks", null, KEYPASS, KEY_MGR_ALGORITHM, environment.configFile())) @@ -220,8 +220,8 @@ public class SslSettingsLoaderTests extends ESTestCase { final String path = "xpack/tls/path." + ext; Settings settings = Settings.builder().put("keystore.path", path).setSecureSettings(secureSettings).build(); SslConfiguration sslConfiguration = getSslConfiguration(settings); - assertThat(sslConfiguration.getKeyConfig(), instanceOf(StoreKeyConfig.class)); - StoreKeyConfig ksKeyInfo = (StoreKeyConfig) sslConfiguration.getKeyConfig(); + assertThat(sslConfiguration.keyConfig(), instanceOf(StoreKeyConfig.class)); + StoreKeyConfig ksKeyInfo = (StoreKeyConfig) sslConfiguration.keyConfig(); assertThat( ksKeyInfo, equalTo(new StoreKeyConfig(path, PASSWORD, "PKCS12", null, KEYPASS, KEY_MGR_ALGORITHM, environment.configFile())) @@ -234,8 +234,8 @@ public class SslSettingsLoaderTests extends ESTestCase { secureSettings.setString("keystore.secure_key_password", "keypass"); Settings settings = Settings.builder().put("keystore.path", "xpack/tls/path.foo").setSecureSettings(secureSettings).build(); SslConfiguration sslConfiguration = getSslConfiguration(settings); - assertThat(sslConfiguration.getKeyConfig(), instanceOf(StoreKeyConfig.class)); - StoreKeyConfig ksKeyInfo = (StoreKeyConfig) sslConfiguration.getKeyConfig(); + assertThat(sslConfiguration.keyConfig(), instanceOf(StoreKeyConfig.class)); + StoreKeyConfig ksKeyInfo = (StoreKeyConfig) sslConfiguration.keyConfig(); assertThat( ksKeyInfo, equalTo(new StoreKeyConfig("xpack/tls/path.foo", PASSWORD, "jks", null, KEYPASS, KEY_MGR_ALGORITHM, environment.configFile())) @@ -255,8 +255,8 @@ public class SslSettingsLoaderTests extends ESTestCase { .setSecureSettings(secureSettings) .build(); SslConfiguration sslConfiguration = getSslConfiguration(settings); - assertThat(sslConfiguration.getKeyConfig(), instanceOf(StoreKeyConfig.class)); - StoreKeyConfig ksKeyInfo = (StoreKeyConfig) sslConfiguration.getKeyConfig(); + assertThat(sslConfiguration.keyConfig(), instanceOf(StoreKeyConfig.class)); + StoreKeyConfig ksKeyInfo = (StoreKeyConfig) sslConfiguration.keyConfig(); assertThat( ksKeyInfo, equalTo(new StoreKeyConfig(path, PASSWORD, type, null, KEYPASS, KEY_MGR_ALGORITHM, environment.configFile())) @@ -318,8 +318,8 @@ public class SslSettingsLoaderTests extends ESTestCase { .build(); SslConfiguration config = getSslConfiguration(settings); - assertThat(config.getKeyConfig(), instanceOf(PemKeyConfig.class)); - PemKeyConfig keyConfig = (PemKeyConfig) config.getKeyConfig(); + assertThat(config.keyConfig(), instanceOf(PemKeyConfig.class)); + PemKeyConfig keyConfig = (PemKeyConfig) config.keyConfig(); KeyManager keyManager = keyConfig.createKeyManager(); assertNotNull(keyManager); assertCombiningTrustConfigContainsCorrectIssuers(config); @@ -333,8 +333,8 @@ public class SslSettingsLoaderTests extends ESTestCase { .build(); SslConfiguration config = getSslConfiguration(settings); - assertThat(config.getKeyConfig(), instanceOf(PemKeyConfig.class)); - SslKeyConfig keyConfig = config.getKeyConfig(); + assertThat(config.keyConfig(), instanceOf(PemKeyConfig.class)); + SslKeyConfig keyConfig = config.keyConfig(); KeyManager keyManager = keyConfig.createKeyManager(); assertNotNull(keyManager); assertCombiningTrustConfigContainsCorrectIssuers(config); @@ -356,12 +356,12 @@ public class SslSettingsLoaderTests extends ESTestCase { .build(); SslConfiguration config = getSslConfiguration(settings); - assertThat(config.getKeyConfig(), instanceOf(PemKeyConfig.class)); - PemKeyConfig keyConfig = (PemKeyConfig) config.getKeyConfig(); + assertThat(config.keyConfig(), instanceOf(PemKeyConfig.class)); + PemKeyConfig keyConfig = (PemKeyConfig) config.keyConfig(); KeyManager keyManager = keyConfig.createKeyManager(); assertNotNull(keyManager); - assertThat(config.getTrustConfig(), not(sameInstance(keyConfig))); - assertThat(config.getTrustConfig(), instanceOf(PemTrustConfig.class)); + assertThat(config.trustConfig(), not(sameInstance(keyConfig))); + assertThat(config.trustConfig(), instanceOf(PemTrustConfig.class)); TrustManager trustManager = keyConfig.asTrustConfig().createTrustManager(); assertNotNull(trustManager); } @@ -379,19 +379,19 @@ public class SslSettingsLoaderTests extends ESTestCase { .build(); SslConfiguration config = getSslConfiguration(settings); - assertThat(config.getKeyConfig(), instanceOf(PemKeyConfig.class)); - PemKeyConfig keyConfig = (PemKeyConfig) config.getKeyConfig(); + assertThat(config.keyConfig(), instanceOf(PemKeyConfig.class)); + PemKeyConfig keyConfig = (PemKeyConfig) config.keyConfig(); KeyManager keyManager = keyConfig.createKeyManager(); assertNotNull(keyManager); - assertThat(config.getTrustConfig(), not(sameInstance(keyConfig))); - assertThat(config.getTrustConfig(), instanceOf(PemTrustConfig.class)); + assertThat(config.trustConfig(), not(sameInstance(keyConfig))); + assertThat(config.trustConfig(), instanceOf(PemTrustConfig.class)); TrustManager trustManager = keyConfig.asTrustConfig().createTrustManager(); assertNotNull(trustManager); assertSettingDeprecationsAndWarnings(new Setting[] { configurationSettings.x509KeyPair.legacyKeyPassword }); } public void testExplicitlyConfigured() { - assertThat(SslSettingsLoader.load(Settings.EMPTY, null, environment).isExplicitlyConfigured(), is(false)); + assertThat(SslSettingsLoader.load(Settings.EMPTY, null, environment).explicitlyConfigured(), is(false)); assertThat( SslSettingsLoader.load( Settings.builder() @@ -401,7 +401,7 @@ public class SslSettingsLoaderTests extends ESTestCase { .build(), "xpack.http.ssl.", environment - ).isExplicitlyConfigured(), + ).explicitlyConfigured(), is(false) ); @@ -410,7 +410,7 @@ public class SslSettingsLoaderTests extends ESTestCase { Settings.builder().put("verification_mode", randomFrom(SslVerificationMode.values()).name()).build(), null, environment - ).isExplicitlyConfigured(), + ).explicitlyConfigured(), is(true) ); @@ -419,15 +419,15 @@ public class SslSettingsLoaderTests extends ESTestCase { Settings.builder().putList("xpack.security.transport.ssl.truststore.path", "truststore.p12").build(), "xpack.security.transport.ssl.", environment - ).isExplicitlyConfigured(), + ).explicitlyConfigured(), is(true) ); } private void assertCombiningTrustConfigContainsCorrectIssuers(SslConfiguration sslConfig) { - assertThat(sslConfig.getTrustConfig(), instanceOf(CompositeTrustConfig.class)); - X509Certificate[] trustConfAcceptedIssuers = sslConfig.getTrustConfig().createTrustManager().getAcceptedIssuers(); - X509Certificate[] keyConfAcceptedIssuers = sslConfig.getKeyConfig().asTrustConfig().createTrustManager().getAcceptedIssuers(); + assertThat(sslConfig.trustConfig(), instanceOf(CompositeTrustConfig.class)); + X509Certificate[] trustConfAcceptedIssuers = sslConfig.trustConfig().createTrustManager().getAcceptedIssuers(); + X509Certificate[] keyConfAcceptedIssuers = sslConfig.keyConfig().asTrustConfig().createTrustManager().getAcceptedIssuers(); X509Certificate[] defaultAcceptedIssuers = DefaultJdkTrustConfig.DEFAULT_INSTANCE.createTrustManager().getAcceptedIssuers(); assertEquals(keyConfAcceptedIssuers.length + defaultAcceptedIssuers.length, trustConfAcceptedIssuers.length); assertThat(Arrays.asList(keyConfAcceptedIssuers), everyItem(is(in(trustConfAcceptedIssuers)))); diff --git a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/datafeed/extractor/aggregation/AggregationDataExtractorFactory.java b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/datafeed/extractor/aggregation/AggregationDataExtractorFactory.java index 5679a1da6040..727c597ff34f 100644 --- a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/datafeed/extractor/aggregation/AggregationDataExtractorFactory.java +++ b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/datafeed/extractor/aggregation/AggregationDataExtractorFactory.java @@ -18,15 +18,13 @@ import org.elasticsearch.xpack.core.ml.utils.Intervals; import org.elasticsearch.xpack.ml.datafeed.DatafeedTimingStatsReporter; import org.elasticsearch.xpack.ml.datafeed.extractor.DataExtractorFactory; -import java.util.Objects; - -public class AggregationDataExtractorFactory implements DataExtractorFactory { - - private final Client client; - private final DatafeedConfig datafeedConfig; - private final Job job; - private final NamedXContentRegistry xContentRegistry; - private final DatafeedTimingStatsReporter timingStatsReporter; +public record AggregationDataExtractorFactory( + Client client, + DatafeedConfig datafeedConfig, + Job job, + NamedXContentRegistry xContentRegistry, + DatafeedTimingStatsReporter timingStatsReporter +) implements DataExtractorFactory { public static AggregatedSearchRequestBuilder requestBuilder(Client client, String[] indices, IndicesOptions indicesOptions) { return (searchSourceBuilder) -> new SearchRequestBuilder(client, SearchAction.INSTANCE).setSource(searchSourceBuilder) @@ -35,20 +33,6 @@ public class AggregationDataExtractorFactory implements DataExtractorFactory { .setIndices(indices); } - public AggregationDataExtractorFactory( - Client client, - DatafeedConfig datafeedConfig, - Job job, - NamedXContentRegistry xContentRegistry, - DatafeedTimingStatsReporter timingStatsReporter - ) { - this.client = Objects.requireNonNull(client); - this.datafeedConfig = Objects.requireNonNull(datafeedConfig); - this.job = Objects.requireNonNull(job); - this.xContentRegistry = xContentRegistry; - this.timingStatsReporter = Objects.requireNonNull(timingStatsReporter); - } - @Override public DataExtractor newExtractor(long start, long end) { long histogramInterval = datafeedConfig.getHistogramIntervalMillis(xContentRegistry); diff --git a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/job/retention/AbstractExpiredJobDataRemover.java b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/job/retention/AbstractExpiredJobDataRemover.java index e8e67161f7a8..aa82c7a261b9 100644 --- a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/job/retention/AbstractExpiredJobDataRemover.java +++ b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/job/retention/AbstractExpiredJobDataRemover.java @@ -12,7 +12,6 @@ import org.elasticsearch.tasks.TaskId; import org.elasticsearch.xpack.core.ml.job.config.Job; import java.util.Iterator; -import java.util.Objects; import java.util.function.BooleanSupplier; /** @@ -108,31 +107,5 @@ abstract class AbstractExpiredJobDataRemover implements MlDataRemover { * being removed. This class groups the cutoff time with it's "latest" * reference point. */ - protected static final class CutoffDetails { - - public final long latestTimeMs; - public final long cutoffEpochMs; - - public CutoffDetails(long latestTimeMs, long cutoffEpochMs) { - this.latestTimeMs = latestTimeMs; - this.cutoffEpochMs = cutoffEpochMs; - } - - @Override - public int hashCode() { - return Objects.hash(latestTimeMs, cutoffEpochMs); - } - - @Override - public boolean equals(Object other) { - if (other == this) { - return true; - } - if (other instanceof CutoffDetails == false) { - return false; - } - CutoffDetails that = (CutoffDetails) other; - return this.latestTimeMs == that.latestTimeMs && this.cutoffEpochMs == that.cutoffEpochMs; - } - } + protected record CutoffDetails(long latestTimeMs, long cutoffEpochMs) {} } diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/core/security/transport/netty4/SecurityNetty4Transport.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/core/security/transport/netty4/SecurityNetty4Transport.java index 02533a97e613..611f5a3ce763 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/core/security/transport/netty4/SecurityNetty4Transport.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/core/security/transport/netty4/SecurityNetty4Transport.java @@ -157,7 +157,7 @@ public class SecurityNetty4Transport extends Netty4Transport { private final SNIHostName serverName; SecurityClientChannelInitializer(DiscoveryNode node) { - this.hostnameVerificationEnabled = sslEnabled && sslConfiguration.getVerificationMode().isHostnameVerificationEnabled(); + this.hostnameVerificationEnabled = sslEnabled && sslConfiguration.verificationMode().isHostnameVerificationEnabled(); String configuredServerName = node.getAttributes().get("server_name"); if (configuredServerName != null) { try { diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/enrollment/TransportKibanaEnrollmentAction.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/enrollment/TransportKibanaEnrollmentAction.java index a2dbaa9d8206..fe997ca18d5c 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/enrollment/TransportKibanaEnrollmentAction.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/enrollment/TransportKibanaEnrollmentAction.java @@ -60,7 +60,7 @@ public class TransportKibanaEnrollmentAction extends HandledTransportAction listener) { - final SslKeyConfig keyConfig = sslService.getHttpTransportSSLConfiguration().getKeyConfig(); + final SslKeyConfig keyConfig = sslService.getHttpTransportSSLConfiguration().keyConfig(); if (keyConfig instanceof StoreKeyConfig == false) { listener.onFailure( new ElasticsearchException( diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/enrollment/TransportNodeEnrollmentAction.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/enrollment/TransportNodeEnrollmentAction.java index 8185449f2c19..86d32116b229 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/enrollment/TransportNodeEnrollmentAction.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/enrollment/TransportNodeEnrollmentAction.java @@ -58,8 +58,8 @@ public class TransportNodeEnrollmentAction extends HandledTransportAction listener) { - final SslKeyConfig transportKeyConfig = sslService.getTransportSSLConfiguration().getKeyConfig(); - final SslKeyConfig httpKeyConfig = sslService.getHttpTransportSSLConfiguration().getKeyConfig(); + final SslKeyConfig transportKeyConfig = sslService.getTransportSSLConfiguration().keyConfig(); + final SslKeyConfig httpKeyConfig = sslService.getHttpTransportSSLConfiguration().keyConfig(); if (transportKeyConfig instanceof StoreKeyConfig == false) { listener.onFailure( new IllegalStateException( @@ -102,7 +102,7 @@ public class TransportNodeEnrollmentAction extends HandledTransportAction x509Certificate.getBasicConstraints() != -1) .collect(Collectors.toList()); } catch (Exception e) { diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/ldap/support/SessionFactory.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/ldap/support/SessionFactory.java index 268e8a59756a..0f241c403f3b 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/ldap/support/SessionFactory.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/ldap/support/SessionFactory.java @@ -170,7 +170,7 @@ public abstract class SessionFactory implements Closeable { if (sslConfiguration == null) { throw new IllegalStateException("cannot find SSL configuration for " + sslKey); } - if (sslConfiguration.getVerificationMode().isHostnameVerificationEnabled()) { + if (sslConfiguration.verificationMode().isHostnameVerificationEnabled()) { options.setSSLSocketVerifier(new HostNameSSLSocketVerifier(true)); } } else if (hostnameVerificationExists) { @@ -214,7 +214,7 @@ public abstract class SessionFactory implements Closeable { final String sslKey = RealmSettings.realmSslPrefix(config.identifier()); final SslConfiguration ssl = clientSSLService.getSSLConfiguration(sslKey); socketFactory = clientSSLService.sslSocketFactory(ssl); - if (ssl.getVerificationMode().isHostnameVerificationEnabled()) { + if (ssl.verificationMode().isHostnameVerificationEnabled()) { logger.debug("using encryption for LDAP connections with hostname verification"); } else { logger.debug("using encryption for LDAP connections without hostname verification"); diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/pki/PkiRealm.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/pki/PkiRealm.java index 8052659a9155..a4562e07430b 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/pki/PkiRealm.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/pki/PkiRealm.java @@ -291,7 +291,7 @@ public class PkiRealm extends Realm implements CachingRealm { RealmSettings.realmSettingPrefix(realmConfig.identifier()), realmConfig.env() ); - final SslTrustConfig trustConfig = sslConfiguration.getTrustConfig(); + final SslTrustConfig trustConfig = sslConfiguration.trustConfig(); if (trustConfig.isSystemDefault()) { return null; } diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/enrollment/BaseEnrollmentTokenGenerator.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/enrollment/BaseEnrollmentTokenGenerator.java index ba5350e50ea3..013d3dc86aba 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/enrollment/BaseEnrollmentTokenGenerator.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/enrollment/BaseEnrollmentTokenGenerator.java @@ -30,7 +30,7 @@ public class BaseEnrollmentTokenGenerator { public BaseEnrollmentTokenGenerator() {} static String getHttpsCaFingerprint(SSLService sslService) throws Exception { - final SslKeyConfig keyConfig = sslService.getHttpTransportSSLConfiguration().getKeyConfig(); + final SslKeyConfig keyConfig = sslService.getHttpTransportSSLConfiguration().keyConfig(); if (keyConfig instanceof StoreKeyConfig == false) { throw new IllegalStateException( "Unable to create an enrollment token. Elasticsearch node HTTP layer SSL configuration is " diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/transport/nio/SecurityNioHttpServerTransport.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/transport/nio/SecurityNioHttpServerTransport.java index 43b954937c26..a1578f103e62 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/transport/nio/SecurityNioHttpServerTransport.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/transport/nio/SecurityNioHttpServerTransport.java @@ -142,7 +142,7 @@ public class SecurityNioHttpServerTransport extends NioHttpServerTransport { SocketChannelContext context; if (sslEnabled) { SSLEngine sslEngine; - boolean hostnameVerificationEnabled = sslConfiguration.getVerificationMode().isHostnameVerificationEnabled(); + boolean hostnameVerificationEnabled = sslConfiguration.verificationMode().isHostnameVerificationEnabled(); if (hostnameVerificationEnabled) { InetSocketAddress address = (InetSocketAddress) channel.getRemoteAddress(); // we create the socket based on the name given. don't reverse DNS diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/transport/nio/SecurityNioTransport.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/transport/nio/SecurityNioTransport.java index d76862a3d26a..f8b4240d1844 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/transport/nio/SecurityNioTransport.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/transport/nio/SecurityNioTransport.java @@ -213,7 +213,7 @@ public class SecurityNioTransport extends NioTransport { SSLEngine sslEngine; SslConfiguration defaultConfig = profileConfiguration.get(TransportSettings.DEFAULT_PROFILE); SslConfiguration sslConfig = profileConfiguration.getOrDefault(profileName, defaultConfig); - boolean hostnameVerificationEnabled = sslConfig.getVerificationMode().isHostnameVerificationEnabled(); + boolean hostnameVerificationEnabled = sslConfig.verificationMode().isHostnameVerificationEnabled(); if (hostnameVerificationEnabled && socketConfig.isAccepted() == false) { InetSocketAddress remoteAddress = socketConfig.getRemoteAddress(); // we create the socket based on the name given. don't reverse DNS diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/core/security/transport/ProfileConfigurationsTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/core/security/transport/ProfileConfigurationsTests.java index da4ced4c22a7..8f9789941f44 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/core/security/transport/ProfileConfigurationsTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/core/security/transport/ProfileConfigurationsTests.java @@ -36,8 +36,8 @@ public class ProfileConfigurationsTests extends ESTestCase { final Map profileConfigurations = ProfileConfigurations.get(settings, sslService, defaultConfig); assertThat(profileConfigurations.size(), Matchers.equalTo(3)); assertThat(profileConfigurations.keySet(), Matchers.containsInAnyOrder("full", "cert", "default")); - assertThat(profileConfigurations.get("full").getVerificationMode(), Matchers.equalTo(SslVerificationMode.FULL)); - assertThat(profileConfigurations.get("cert").getVerificationMode(), Matchers.equalTo(SslVerificationMode.CERTIFICATE)); + assertThat(profileConfigurations.get("full").verificationMode(), Matchers.equalTo(SslVerificationMode.FULL)); + assertThat(profileConfigurations.get("cert").verificationMode(), Matchers.equalTo(SslVerificationMode.CERTIFICATE)); assertThat(profileConfigurations.get("default"), Matchers.sameInstance(defaultConfig)); } @@ -53,7 +53,7 @@ public class ProfileConfigurationsTests extends ESTestCase { final Map profileConfigurations = ProfileConfigurations.get(settings, sslService, defaultConfig); assertThat(profileConfigurations.size(), Matchers.equalTo(2)); assertThat(profileConfigurations.keySet(), Matchers.containsInAnyOrder("none", "default")); - assertThat(profileConfigurations.get("none").getVerificationMode(), Matchers.equalTo(SslVerificationMode.NONE)); + assertThat(profileConfigurations.get("none").verificationMode(), Matchers.equalTo(SslVerificationMode.NONE)); assertThat(profileConfigurations.get("default"), Matchers.sameInstance(defaultConfig)); } diff --git a/x-pack/plugin/sql/sql-action/src/main/java/org/elasticsearch/xpack/sql/action/ProtoShim.java b/x-pack/plugin/sql/sql-action/src/main/java/org/elasticsearch/xpack/sql/action/ProtoShim.java index 62f949d4f688..3c3f76e44ee9 100644 --- a/x-pack/plugin/sql/sql-action/src/main/java/org/elasticsearch/xpack/sql/action/ProtoShim.java +++ b/x-pack/plugin/sql/sql-action/src/main/java/org/elasticsearch/xpack/sql/action/ProtoShim.java @@ -49,6 +49,6 @@ final class ProtoShim { if (toProto == null) { return null; } - return new ContentLocation(toProto.lineNumber, toProto.columnNumber); + return new ContentLocation(toProto.lineNumber(), toProto.columnNumber()); } } diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/notification/email/EmailService.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/notification/email/EmailService.java index cb30b8945849..a6b6ef2896ff 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/notification/email/EmailService.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/notification/email/EmailService.java @@ -187,7 +187,7 @@ public class EmailService extends NotificationService { @Nullable private SSLSocketFactory getSmtpSslSocketFactory() { final SslConfiguration sslConfiguration = sslService.getSSLConfiguration(EMAIL_NOTIFICATION_SSL_PREFIX); - if (sslConfiguration == null || sslConfiguration.isExplicitlyConfigured() == false) { + if (sslConfiguration == null || sslConfiguration.explicitlyConfigured() == false) { return null; } return sslService.sslSocketFactory(sslConfiguration); diff --git a/x-pack/qa/third-party/active-directory/src/test/java/org/elasticsearch/xpack/security/authc/ldap/AbstractAdLdapRealmTestCase.java b/x-pack/qa/third-party/active-directory/src/test/java/org/elasticsearch/xpack/security/authc/ldap/AbstractAdLdapRealmTestCase.java index 06ef14655f75..abcd85b2fbff 100644 --- a/x-pack/qa/third-party/active-directory/src/test/java/org/elasticsearch/xpack/security/authc/ldap/AbstractAdLdapRealmTestCase.java +++ b/x-pack/qa/third-party/active-directory/src/test/java/org/elasticsearch/xpack/security/authc/ldap/AbstractAdLdapRealmTestCase.java @@ -172,7 +172,7 @@ public abstract class AbstractAdLdapRealmTestCase extends SecurityIntegTestCase public void setupRoleMappings() throws Exception { assertSecurityIndexActive(); - List content = getRoleMappingContent(RoleMappingEntry::getNativeContent); + List content = getRoleMappingContent(RoleMappingEntry::nativeContent); if (content.isEmpty()) { return; } @@ -206,7 +206,7 @@ public abstract class AbstractAdLdapRealmTestCase extends SecurityIntegTestCase } protected final void configureFileRoleMappings(Settings.Builder builder, String realmType, List mappings) { - String content = getRoleMappingContent(RoleMappingEntry::getFileContent, mappings).stream().collect(Collectors.joining("\n")); + String content = getRoleMappingContent(RoleMappingEntry::fileContent, mappings).stream().collect(Collectors.joining("\n")); Path nodeFiles = createTempDir(); String file = writeFile(nodeFiles, "role_mapping.yml", content); builder.put("xpack.security.authc.realms." + realmType + ".external.files.role_mapping", file); @@ -304,24 +304,7 @@ public abstract class AbstractAdLdapRealmTestCase extends SecurityIntegTestCase ); } - static class RoleMappingEntry { - @Nullable - public final String fileContent; - @Nullable - public final String nativeContent; - - RoleMappingEntry(@Nullable String fileContent, @Nullable String nativeContent) { - this.fileContent = fileContent; - this.nativeContent = nativeContent; - } - - String getFileContent() { - return fileContent; - } - - String getNativeContent() { - return nativeContent; - } + record RoleMappingEntry(@Nullable String fileContent, @Nullable String nativeContent) { RoleMappingEntry pickEntry(Supplier shouldPickFileContent) { if (nativeContent == null) { @@ -336,26 +319,6 @@ public abstract class AbstractAdLdapRealmTestCase extends SecurityIntegTestCase return new RoleMappingEntry(null, nativeContent); } } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - final RoleMappingEntry that = (RoleMappingEntry) o; - return Objects.equals(this.fileContent, that.fileContent) && Objects.equals(this.nativeContent, that.nativeContent); - } - - @Override - public int hashCode() { - int result = Objects.hashCode(fileContent); - result = 31 * result + Objects.hashCode(nativeContent); - return result; - } } /**