diff --git a/benchmarks/src/main/java/org/elasticsearch/benchmark/common/util/IntArrayBenchmark.java b/benchmarks/src/main/java/org/elasticsearch/benchmark/common/util/IntArrayBenchmark.java index 973155f69effd..48946e61b5789 100644 --- a/benchmarks/src/main/java/org/elasticsearch/benchmark/common/util/IntArrayBenchmark.java +++ b/benchmarks/src/main/java/org/elasticsearch/benchmark/common/util/IntArrayBenchmark.java @@ -62,10 +62,10 @@ public void init() throws IOException { } private BytesReference bytesImpl(BytesReference bytes) { - if (type.equals("array")) { + if ("array".equals(type)) { return new BytesArray(bytes.toBytesRef()); } - if (type.equals("paged_bytes_array")) { + if ("paged_bytes_array".equals(type)) { if (bytes instanceof PagedBytesReference == false) { throw new AssertionError("expected PagedBytesReference but saw [" + bytes.getClass() + "]"); } diff --git a/benchmarks/src/main/java/org/elasticsearch/benchmark/compute/operator/AggregatorBenchmark.java b/benchmarks/src/main/java/org/elasticsearch/benchmark/compute/operator/AggregatorBenchmark.java index 7b1efb82cd1f0..443e5942fb694 100644 --- a/benchmarks/src/main/java/org/elasticsearch/benchmark/compute/operator/AggregatorBenchmark.java +++ b/benchmarks/src/main/java/org/elasticsearch/benchmark/compute/operator/AggregatorBenchmark.java @@ -118,7 +118,7 @@ public class AggregatorBenchmark { private static Operator operator(String grouping, String op, String dataType) { DriverContext driverContext = driverContext(); - if (grouping.equals("none")) { + if ("none".equals(grouping)) { return new AggregationOperator( List.of(supplier(op, dataType, 0).aggregatorFactory(AggregatorMode.SINGLE).apply(driverContext)), driverContext @@ -181,7 +181,7 @@ private static AggregatorFunctionSupplier supplier(String op, String dataType, i private static void checkExpected(String grouping, String op, String blockType, String dataType, Page page, int opCount) { String prefix = String.format("[%s][%s][%s] ", grouping, op, blockType); - if (grouping.equals("none")) { + if ("none".equals(grouping)) { checkUngrouped(prefix, op, dataType, page, opCount); return; } @@ -434,7 +434,7 @@ private static void checkUngrouped(String prefix, String op, String dataType, Pa private static Page page(String grouping, String blockType) { Block dataBlock = dataBlock(blockType); - if (grouping.equals("none")) { + if ("none".equals(grouping)) { return new Page(dataBlock); } List blocks = groupingBlocks(grouping, blockType); diff --git a/benchmarks/src/main/java/org/elasticsearch/benchmark/search/aggregations/AggConstructionContentionBenchmark.java b/benchmarks/src/main/java/org/elasticsearch/benchmark/search/aggregations/AggConstructionContentionBenchmark.java index 8e60a7435cbc7..17f408a9f0ff3 100644 --- a/benchmarks/src/main/java/org/elasticsearch/benchmark/search/aggregations/AggConstructionContentionBenchmark.java +++ b/benchmarks/src/main/java/org/elasticsearch/benchmark/search/aggregations/AggConstructionContentionBenchmark.java @@ -118,7 +118,7 @@ public void setup() { case "noop" -> new NoneCircuitBreakerService(); default -> throw new UnsupportedOperationException(); }; - preallocateBreaker = breaker.equals("preallocate"); + preallocateBreaker = "preallocate".equals(breaker); bigArrays = new BigArrays(recycler, breakerService, "request"); } diff --git a/benchmarks/src/main/java/org/elasticsearch/benchmark/tdigest/TDigestBench.java b/benchmarks/src/main/java/org/elasticsearch/benchmark/tdigest/TDigestBench.java index abf08395f90a6..81044393edbce 100644 --- a/benchmarks/src/main/java/org/elasticsearch/benchmark/tdigest/TDigestBench.java +++ b/benchmarks/src/main/java/org/elasticsearch/benchmark/tdigest/TDigestBench.java @@ -93,7 +93,7 @@ public void setUp() { random = ThreadLocalRandom.current(); tdigest = tdigestFactory.create(compression); - Supplier nextRandom = () -> distribution.equals("GAUSSIAN") ? random.nextGaussian() : random.nextDouble(); + Supplier nextRandom = () -> "GAUSSIAN".equals(distribution) ? random.nextGaussian() : random.nextDouble(); for (int i = 0; i < 10000; ++i) { tdigest.add(nextRandom.get()); } diff --git a/build-conventions/src/main/java/org/elasticsearch/gradle/internal/checkstyle/StringFormattingCheck.java b/build-conventions/src/main/java/org/elasticsearch/gradle/internal/checkstyle/StringFormattingCheck.java index 48fa3ad6ee485..b0b1c48239519 100644 --- a/build-conventions/src/main/java/org/elasticsearch/gradle/internal/checkstyle/StringFormattingCheck.java +++ b/build-conventions/src/main/java/org/elasticsearch/gradle/internal/checkstyle/StringFormattingCheck.java @@ -62,7 +62,7 @@ private void checkFormattedMethod(DetailAST ast) { } final String methodName = dotAst.findFirstToken(TokenTypes.IDENT).getText(); - if (methodName.equals("formatted") == false) { + if ("formatted".equals(methodName) == false) { return; } diff --git a/build-conventions/src/main/java/org/elasticsearch/gradle/internal/checkstyle/SwitchBetweenCheck.java b/build-conventions/src/main/java/org/elasticsearch/gradle/internal/checkstyle/SwitchBetweenCheck.java index 7957b65cc0e7e..721b70532129a 100644 --- a/build-conventions/src/main/java/org/elasticsearch/gradle/internal/checkstyle/SwitchBetweenCheck.java +++ b/build-conventions/src/main/java/org/elasticsearch/gradle/internal/checkstyle/SwitchBetweenCheck.java @@ -89,7 +89,7 @@ private void checkSwitchBetween(DetailAST ast) { final DetailAST argListAst = methodCallAst.findFirstToken(TokenTypes.ELIST); int min; int max; - if (switchMethodName.equals("randomInt")) { + if ("randomInt".equals(switchMethodName)) { if (argListAst.getChildCount() != 1) { // 1 arg return; } @@ -139,7 +139,7 @@ private void checkSwitchBetween(DetailAST ast) { try { int value = Integer.parseInt(exprAst.getFirstChild().getText()); if (value < min || value > max) { - if (switchMethodName.equals("randomInt")) { + if ("randomInt".equals(switchMethodName)) { log(caseAst, SWITCH_RANDOM_INT_MSG_KEY, value, switchMethodName, max); } else { log(caseAst, SWITCH_BETWEEN_MSG_KEY, value, switchMethodName, min, max); diff --git a/build-conventions/src/main/java/org/elasticsearch/gradle/internal/conventions/info/GitInfo.java b/build-conventions/src/main/java/org/elasticsearch/gradle/internal/conventions/info/GitInfo.java index 17d6ef6917c94..f8e2d8ddbb997 100644 --- a/build-conventions/src/main/java/org/elasticsearch/gradle/internal/conventions/info/GitInfo.java +++ b/build-conventions/src/main/java/org/elasticsearch/gradle/internal/conventions/info/GitInfo.java @@ -154,7 +154,7 @@ private static String findOriginUrl(final Path configFile) throws IOException { String[] pair = line.trim().split("=", 2); props.put(pair[0].trim(), pair[1].trim()); } else { - if (line.equals("[remote \"origin\"]")) { + if ("[remote \"origin\"]".equals(line)) { foundOrigin = true; } } diff --git a/build-conventions/src/main/java/org/elasticsearch/gradle/internal/conventions/info/ParallelDetector.java b/build-conventions/src/main/java/org/elasticsearch/gradle/internal/conventions/info/ParallelDetector.java index 688f2f858ae16..8f306056b78e3 100644 --- a/build-conventions/src/main/java/org/elasticsearch/gradle/internal/conventions/info/ParallelDetector.java +++ b/build-conventions/src/main/java/org/elasticsearch/gradle/internal/conventions/info/ParallelDetector.java @@ -51,11 +51,11 @@ public static int findDefaultParallel(Project project) { String name = parts.get(0); String value = parts.get(1); // the ID of the CPU socket - if (name.equals("physical id")) { + if ("physical id".equals(name)) { currentID = value; } // Number of cores not including hyper-threading - if (name.equals("cpu cores")) { + if ("cpu cores".equals(name)) { assert currentID.isEmpty() == false; socketToCore.put("currentID", Integer.valueOf(value)); currentID = ""; 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 d71c893cdd20f..fdb438f07b834 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 @@ -117,9 +117,9 @@ private TaskProvider createRunBwcGradleTask( } final String showStacktraceName = project.getGradle().getStartParameter().getShowStacktrace().name(); assert Arrays.asList("INTERNAL_EXCEPTIONS", "ALWAYS", "ALWAYS_FULL").contains(showStacktraceName); - if (showStacktraceName.equals("ALWAYS")) { + if ("ALWAYS".equals(showStacktraceName)) { loggedExec.args("--stacktrace"); - } else if (showStacktraceName.equals("ALWAYS_FULL")) { + } else if ("ALWAYS_FULL".equals(showStacktraceName)) { loggedExec.args("--full-stacktrace"); } if (project.getGradle().getStartParameter().isParallelProjectExecutionEnabled()) { diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/ElasticsearchBuildCompletePlugin.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/ElasticsearchBuildCompletePlugin.java index 4902168d9b4ff..228cfff617690 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/ElasticsearchBuildCompletePlugin.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/ElasticsearchBuildCompletePlugin.java @@ -133,7 +133,7 @@ public void execute(BuildFinishedFlowAction.Parameters parameters) throws FileNo } uploadFile.getParentFile().mkdirs(); createBuildArchiveTar(parameters.getFilteredFiles().get(), parameters.getProjectDir().get(), uploadFile); - if (uploadFile.exists() && System.getenv("BUILDKITE").equals("true")) { + if (uploadFile.exists() && "true".equals(System.getenv("BUILDKITE"))) { String uploadFilePath = "build/" + uploadFile.getName(); try { System.out.println("Uploading buildkite artifact: " + uploadFilePath + "..."); diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/ElasticsearchJavaModulePathPlugin.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/ElasticsearchJavaModulePathPlugin.java index 662e1845850a7..eeb00abc2dc72 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/ElasticsearchJavaModulePathPlugin.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/ElasticsearchJavaModulePathPlugin.java @@ -207,7 +207,7 @@ static String pathToString(String path) { } static boolean isIdea() { - return System.getProperty("idea.sync.active", "false").equals("true"); + return "true".equals(System.getProperty("idea.sync.active", "false")); } File findProjectIdPath(String currentBuildPath, Project project, ProjectComponentIdentifier id) { @@ -220,7 +220,7 @@ File findProjectIdPath(String currentBuildPath, Project project, ProjectComponen File includedBuildDir = project.getGradle().includedBuild(buildName).getProjectDir(); // We have to account for us renaming the :libs projects here String[] pathSegments = id.getProjectPath().split(":"); - if (pathSegments[1].equals("libs")) { + if ("libs".equals(pathSegments[1])) { pathSegments[2] = pathSegments[2].replaceFirst("elasticsearch-", ""); } diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/InternalDistributionArchiveCheckPlugin.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/InternalDistributionArchiveCheckPlugin.java index 6fafe513662c5..ae80958a24185 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/InternalDistributionArchiveCheckPlugin.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/InternalDistributionArchiveCheckPlugin.java @@ -70,7 +70,7 @@ public void apply(Project project) { }); String projectName = project.getName(); - if (projectName.equalsIgnoreCase("integ-test-zip") == false && (projectName.contains("zip") || projectName.contains("tar"))) { + if ("integ-test-zip".equalsIgnoreCase(projectName) == false && (projectName.contains("zip") || projectName.contains("tar"))) { project.getExtensions() .add( "projectLicenses", 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 f727dc165a8a9..71a031bfdd16d 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 @@ -231,7 +231,7 @@ private static List resolveArchiveProjects(File checkoutDir String baseName = name.startsWith("oss-") ? name.substring(4, index) : name.substring(0, index); classifier = "-" + baseName + (name.contains("aarch64") ? "-aarch64" : "-x86_64"); extension = name.substring(index + 1); - if (extension.equals("tar")) { + if ("tar".equals(extension)) { extension += ".gz"; } } else if (name.contains("deb")) { diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/JdkDownloadPlugin.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/JdkDownloadPlugin.java index 5aa72c57e4be4..a4bbc946c88ff 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/JdkDownloadPlugin.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/JdkDownloadPlugin.java @@ -99,7 +99,7 @@ private void setupRepository(Project project, Jdk jdk) { if (jdk.getVendor().equals(VENDOR_ADOPTIUM)) { repoUrl = "https://api.adoptium.net/v3/binary/version/"; - if (jdk.getMajor().equals("8")) { + if ("8".equals(jdk.getMajor())) { // legacy pattern for JDK 8 artifactPattern = "jdk" + jdk.getBaseVersion() @@ -135,7 +135,7 @@ private void setupRepository(Project project, Jdk jdk) { } } else if (jdk.getVendor().equals(VENDOR_ZULU)) { repoUrl = "https://cdn.azul.com"; - if (jdk.getMajor().equals("8") && isJdkOnMacOsPlatform(jdk) && jdk.getArchitecture().equals("aarch64")) { + if ("8".equals(jdk.getMajor()) && isJdkOnMacOsPlatform(jdk) && "aarch64".equals(jdk.getArchitecture())) { artifactPattern = "zulu/bin/zulu" + jdk.getDistributionVersion() + "-ca-jdk" @@ -167,12 +167,12 @@ public static NamedDomainObjectContainer getContainer(Project project) { private static String dependencyNotation(Jdk jdk) { String platformDep = isJdkOnMacOsPlatform(jdk) ? (jdk.getVendor().equals(VENDOR_ADOPTIUM) ? "mac" : "macos") : jdk.getPlatform(); - String extension = jdk.getPlatform().equals("windows") ? "zip" : "tar.gz"; + String extension = "windows".equals(jdk.getPlatform()) ? "zip" : "tar.gz"; return groupName(jdk) + ":" + platformDep + ":" + jdk.getBaseVersion() + ":" + jdk.getArchitecture() + "@" + extension; } private static boolean isJdkOnMacOsPlatform(Jdk jdk) { - return jdk.getPlatform().equals("darwin") || jdk.getPlatform().equals("mac"); + return "darwin".equals(jdk.getPlatform()) || "mac".equals(jdk.getPlatform()); } private static String groupName(Jdk jdk) { diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/NoticeTask.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/NoticeTask.java index 751ac92512dad..7929e967255ec 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/NoticeTask.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/NoticeTask.java @@ -130,7 +130,7 @@ public void generateNotice() throws IOException { // Find any source files with "@notice" annotated license header for (File sourceFile : sources.getFiles()) { - boolean isPackageInfo = sourceFile.getName().equals("package-info.java"); + boolean isPackageInfo = "package-info.java".equals(sourceFile.getName()); boolean foundNotice = false; boolean inNotice = false; StringBuilder header = new StringBuilder(); diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/ResolveAllDependencies.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/ResolveAllDependencies.java index e9a3da6a4c8d3..63b949b08ea6d 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/ResolveAllDependencies.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/ResolveAllDependencies.java @@ -63,7 +63,7 @@ private void resolveDefaultJavaToolChain() { String bundledJdkMajorVersion = VersionProperties.getBundledJdkMajorVersion(); javaToolchainSpec.getLanguageVersion().set(JavaLanguageVersion.of(bundledJdkMajorVersion)); javaToolchainSpec.getVendor() - .set(bundledVendor.equals("openjdk") ? JvmVendorSpec.ORACLE : JvmVendorSpec.matching(bundledVendor)); + .set("openjdk".equals(bundledVendor) ? JvmVendorSpec.ORACLE : JvmVendorSpec.matching(bundledVendor)); }).get(); } diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/docker/TransformLog4jConfigFilter.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/docker/TransformLog4jConfigFilter.java index 4be9380388a74..8aa3b4cd8de34 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/docker/TransformLog4jConfigFilter.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/docker/TransformLog4jConfigFilter.java @@ -81,14 +81,14 @@ static List transformConfig(List lines) { // We don't need to explicitly define a console appender because the // "rolling" appender will become a console appender. We also don't // carry over "*_old" appenders - if (keyParts[1].equals("console") || keyParts[1].endsWith("_old")) { + if ("console".equals(keyParts[1]) || keyParts[1].endsWith("_old")) { skipNext = line.endsWith("\\"); continue; } switch (keyParts[2]) { case "type" -> { - if (value.equals("RollingFile")) { + if ("RollingFile".equals(value)) { value = "Console"; } line = key + " = " + value; @@ -103,7 +103,7 @@ static List transformConfig(List lines) { String[] parts = line.split("\\s*=\\s*"); // The root logger only needs this appender - if (parts[1].equals("rolling") == false) { + if ("rolling".equals(parts[1]) == false) { skipNext = line.endsWith("\\"); continue; } @@ -112,7 +112,7 @@ static List transformConfig(List lines) { String key = parts[0]; String[] keyParts = key.split("\\."); - if (keyParts[2].equals("appenderRef") && keyParts[3].endsWith("_old")) { + if ("appenderRef".equals(keyParts[2]) && keyParts[3].endsWith("_old")) { skipNext = line.endsWith("\\"); continue; } diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/info/GlobalBuildInfoPlugin.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/info/GlobalBuildInfoPlugin.java index 115c4b0694141..d19968a5dda01 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/info/GlobalBuildInfoPlugin.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/info/GlobalBuildInfoPlugin.java @@ -289,7 +289,7 @@ private static void throwInvalidJavaHomeException(String description, File javaH private static void assertMinimumCompilerVersion(JavaVersion minimumCompilerVersion) { JavaVersion currentVersion = Jvm.current().getJavaVersion(); - if (System.getProperty("idea.active", "false").equals("true") == false && minimumCompilerVersion.compareTo(currentVersion) > 0) { + if ("true".equals(System.getProperty("idea.active", "false")) == false && minimumCompilerVersion.compareTo(currentVersion) > 0) { throw new GradleException( "Project requires Java version of " + minimumCompilerVersion + " or newer but Gradle JAVA_HOME is " + currentVersion ); diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/precommit/JavaModulePrecommitTask.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/precommit/JavaModulePrecommitTask.java index d031113550295..d84e180ee7f68 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/precommit/JavaModulePrecommitTask.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/precommit/JavaModulePrecommitTask.java @@ -109,7 +109,7 @@ private void checkModuleVersion(ModuleReference mref) { String mVersion = mref.descriptor() .rawVersion() .orElseThrow(() -> new GradleException("no version found in module " + mref.descriptor().name())); - if (mVersion.equals(expectedVersion) == false) { + if (expectedVersion.equals(mVersion) == false) { throw new GradleException("Expected version [" + expectedVersion + "], in " + mref.descriptor()); } } diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/precommit/SplitPackagesAuditTask.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/precommit/SplitPackagesAuditTask.java index ec279589a6bed..584a8745993e6 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/precommit/SplitPackagesAuditTask.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/precommit/SplitPackagesAuditTask.java @@ -252,7 +252,7 @@ private void filterSplitPackages(Map> splitPackages) { LOGGER.error("Package is not split: " + fqcn); filterErrorsFound = true; } else { - if (className.equals("*")) { + if ("*".equals(className)) { currentClasses.clear(); } else if (currentClasses.remove(fqcn) == false) { LOGGER.error("Class does not exist: " + fqcn); @@ -316,7 +316,7 @@ private static String getPackageName(Path path) { private String formatDependency(File dependencyFile) { if (dependencyFile.isDirectory()) { - while (dependencyFile.getName().equals("build") == false) { + while ("build".equals(dependencyFile.getName()) == false) { dependencyFile = dependencyFile.getParentFile(); } String projectName = getParameters().getProjectBuildDirs().get().get(dependencyFile); diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/snyk/GenerateSnykDependencyGraph.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/snyk/GenerateSnykDependencyGraph.java index 9eb57eb636aa1..a263a06e79086 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/snyk/GenerateSnykDependencyGraph.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/snyk/GenerateSnykDependencyGraph.java @@ -94,7 +94,7 @@ private Map generateGradleGraphPayload() { SnykDependencyGraphBuilder builder = new SnykDependencyGraphBuilder(gradleVersion.get()); String effectiveProjectPath = projectPath.get(); builder.walkGraph( - (effectiveProjectPath.equals(":") ? projectName.get() : effectiveProjectPath), + (":".equals(effectiveProjectPath) ? projectName.get() : effectiveProjectPath), version.get(), firstLevelModuleDependencies ); diff --git a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/toolchain/OracleOpenJdkToolchainResolver.java b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/toolchain/OracleOpenJdkToolchainResolver.java index e29fdc109a104..6b10e8b2022a8 100644 --- a/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/toolchain/OracleOpenJdkToolchainResolver.java +++ b/build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/toolchain/OracleOpenJdkToolchainResolver.java @@ -81,7 +81,7 @@ public Optional resolve(JavaToolchainRequest request) { * 4. Aarch64 windows images are not supported */ private boolean requestIsSupported(JavaToolchainRequest request) { - if (VersionProperties.getBundledJdkVendor().toLowerCase().equals("openjdk") == false) { + if ("openjdk".equals(VersionProperties.getBundledJdkVendor().toLowerCase()) == false) { return false; } JavaToolchainSpec javaToolchainSpec = request.getJavaToolchainSpec(); diff --git a/distribution/tools/plugin-cli/src/main/java/org/elasticsearch/plugins/cli/PluginSecurity.java b/distribution/tools/plugin-cli/src/main/java/org/elasticsearch/plugins/cli/PluginSecurity.java index 6e762ffd43d3e..d05e20bf1bab0 100644 --- a/distribution/tools/plugin-cli/src/main/java/org/elasticsearch/plugins/cli/PluginSecurity.java +++ b/distribution/tools/plugin-cli/src/main/java/org/elasticsearch/plugins/cli/PluginSecurity.java @@ -78,7 +78,7 @@ static void confirmPolicyExceptions(Terminal terminal, Set permissions, private static void prompt(final Terminal terminal) throws UserException { terminal.println(Verbosity.NORMAL, ""); String text = terminal.readText("Continue with installation? [y/N]"); - if (text.equalsIgnoreCase("y") == false) { + if ("y".equalsIgnoreCase(text) == false) { throw new UserException(ExitCodes.DATA_ERROR, "installation aborted by user"); } } diff --git a/distribution/tools/server-cli/src/main/java/org/elasticsearch/server/cli/JvmErgonomics.java b/distribution/tools/server-cli/src/main/java/org/elasticsearch/server/cli/JvmErgonomics.java index 926d5727a1b4a..d4f702a698499 100644 --- a/distribution/tools/server-cli/src/main/java/org/elasticsearch/server/cli/JvmErgonomics.java +++ b/distribution/tools/server-cli/src/main/java/org/elasticsearch/server/cli/JvmErgonomics.java @@ -88,7 +88,7 @@ static boolean tuneG1GCInitiatingHeapOccupancyPercent(final Map finalJvmOptions, String optionName) { - return getRequiredOption(finalJvmOptions, "UseG1GC").getMandatoryValue().equals("true") + return "true".equals(getRequiredOption(finalJvmOptions, "UseG1GC").getMandatoryValue()) && getRequiredOption(finalJvmOptions, optionName).isCommandLineOrigin() == false; } diff --git a/libs/cli/src/main/java/org/elasticsearch/cli/Terminal.java b/libs/cli/src/main/java/org/elasticsearch/cli/Terminal.java index 856dfc6a5a078..0d0e63b8a4f76 100644 --- a/libs/cli/src/main/java/org/elasticsearch/cli/Terminal.java +++ b/libs/cli/src/main/java/org/elasticsearch/cli/Terminal.java @@ -206,8 +206,8 @@ public final boolean promptYesNo(String prompt, boolean defaultYes) { return defaultYes; } answer = answer.toLowerCase(Locale.ROOT); - boolean answerYes = answer.equals("y"); - if (answerYes == false && answer.equals("n") == false) { + boolean answerYes = "y".equals(answer); + if (answerYes == false && "n".equals(answer) == false) { errorPrintln("Did not understand answer '" + answer + "'"); continue; } diff --git a/libs/core/src/main/java/org/elasticsearch/core/PathUtils.java b/libs/core/src/main/java/org/elasticsearch/core/PathUtils.java index 71d89c5bf063b..994fbf1365e09 100644 --- a/libs/core/src/main/java/org/elasticsearch/core/PathUtils.java +++ b/libs/core/src/main/java/org/elasticsearch/core/PathUtils.java @@ -56,7 +56,7 @@ public static Path get(String first, String... more) { * a path against an existing one! */ public static Path get(URI uri) { - if (uri.getScheme().equalsIgnoreCase("file")) { + if ("file".equalsIgnoreCase(uri.getScheme())) { return DEFAULT.provider().getPath(uri); } else { return Paths.get(uri); diff --git a/libs/core/src/main/java/org/elasticsearch/core/internal/provider/EmbeddedImplClassLoader.java b/libs/core/src/main/java/org/elasticsearch/core/internal/provider/EmbeddedImplClassLoader.java index 049b619fb57ac..925b1a0360b08 100644 --- a/libs/core/src/main/java/org/elasticsearch/core/internal/provider/EmbeddedImplClassLoader.java +++ b/libs/core/src/main/java/org/elasticsearch/core/internal/provider/EmbeddedImplClassLoader.java @@ -298,7 +298,7 @@ InMemoryModuleFinder moduleFinder(Set missingModules) throws IOException Path[] modulePath = modulePath(); assert modulePath.length >= 1; InMemoryModuleFinder moduleFinder = InMemoryModuleFinder.of(missingModules, modulePath); - if (modulePath[0].getFileSystem().provider().getScheme().equals("jar")) { + if ("jar".equals(modulePath[0].getFileSystem().provider().getScheme())) { modulePath[0].getFileSystem().close(); } return moduleFinder; @@ -328,9 +328,9 @@ private static Path[] embeddedJarPath(Set prefixes, URI rootURI) throws .distinct() .map(pfx -> path.resolve(pfx)) .toArray(Path[]::new); - if (rootURI.getScheme().equals("file")) { + if ("file".equals(rootURI.getScheme())) { return entries.apply(Path.of(rootURI)); - } else if (rootURI.getScheme().equals("jar")) { + } else if ("jar".equals(rootURI.getScheme())) { FileSystem fileSystem = FileSystems.newFileSystem(rootURI, Map.of(), ClassLoader.getSystemClassLoader()); Path rootPath = fileSystem.getPath("/"); return entries.apply(rootPath); @@ -356,7 +356,7 @@ private static Path[] embeddedJarPath(Set prefixes, URI rootURI) throws static URI rootURI(URL url) { try { URI uri = url.toURI(); - if (uri.getScheme().equals("jar")) { + if ("jar".equals(uri.getScheme())) { String s = uri.toString(); return URI.create(s.substring(0, s.lastIndexOf("!/"))); } else { @@ -453,7 +453,7 @@ private static Map getProviderPrefixes(ClassLoader parent, try { scan = scanPackages(p, isMultiRelease); } finally { - if (p.getFileSystem().provider().getScheme().equals("jar")) { + if ("jar".equals(p.getFileSystem().provider().getScheme())) { p.getFileSystem().close(); } } diff --git a/libs/core/src/main/java/org/elasticsearch/core/internal/provider/EmbeddedModulePath.java b/libs/core/src/main/java/org/elasticsearch/core/internal/provider/EmbeddedModulePath.java index abf29c3c43656..d9a8c5a2af684 100644 --- a/libs/core/src/main/java/org/elasticsearch/core/internal/provider/EmbeddedModulePath.java +++ b/libs/core/src/main/java/org/elasticsearch/core/internal/provider/EmbeddedModulePath.java @@ -212,7 +212,7 @@ static Optional toPackageName(Path file, String separator) { Path parent = file.getParent(); if (parent == null) { String name = file.toString(); - if (name.endsWith(".class") && name.equals(MODULE_INFO) == false) { + if (name.endsWith(".class") && MODULE_INFO.equals(name) == false) { String msg = name + " found in top-level directory (unnamed package not allowed in module)"; throw new InvalidModuleDescriptorException(msg); } @@ -234,7 +234,7 @@ static Optional toPackageName(String name, String separator) { assert name.endsWith(separator) == false; int index = name.lastIndexOf(separator); if (index == -1) { - if (name.endsWith(".class") && name.equals(MODULE_INFO) == false) { + if (name.endsWith(".class") && MODULE_INFO.equals(name) == false) { String msg = name + " found in top-level directory (unnamed package not allowed in module)"; throw new InvalidModuleDescriptorException(msg); } @@ -258,7 +258,7 @@ static Optional toServiceName(String cf) { } if (SERVICES_PREFIX.length() < cf.length()) { String prefix = cf.substring(0, SERVICES_PREFIX.length()); - if (prefix.equals(SERVICES_PREFIX)) { + if (SERVICES_PREFIX.equals(prefix)) { String sn = cf.substring(SERVICES_PREFIX.length()); if (isClassName(sn)) { return Optional.of(sn); diff --git a/libs/core/src/main/java/org/elasticsearch/jdk/JarHell.java b/libs/core/src/main/java/org/elasticsearch/jdk/JarHell.java index 6abbfec2297ea..901b3549f0ad5 100644 --- a/libs/core/src/main/java/org/elasticsearch/jdk/JarHell.java +++ b/libs/core/src/main/java/org/elasticsearch/jdk/JarHell.java @@ -143,7 +143,7 @@ static Set parseClassPath(String classPath) { } // now just parse as ordinary file try { - if (element.equals("/")) { + if ("/".equals(element)) { // Eclipse adds this to the classpath when running unit tests... continue; } @@ -283,7 +283,7 @@ public static void checkJavaVersion(String resource, String targetVersion) { } private static void checkClass(Map clazzes, String clazz, Path jarpath) { - if (clazz.equals("module-info") || clazz.endsWith(".module-info")) { + if ("module-info".equals(clazz) || clazz.endsWith(".module-info")) { // Ignore jigsaw module descriptions return; } diff --git a/libs/geo/src/main/java/org/elasticsearch/geometry/utils/WellKnownText.java b/libs/geo/src/main/java/org/elasticsearch/geometry/utils/WellKnownText.java index da7386d6bb00f..8532d13ee4d56 100644 --- a/libs/geo/src/main/java/org/elasticsearch/geometry/utils/WellKnownText.java +++ b/libs/geo/src/main/java/org/elasticsearch/geometry/utils/WellKnownText.java @@ -320,7 +320,7 @@ private static void parseCoordinate(StreamTokenizer stream, ArrayList la private static MultiPoint parseMultiPoint(StreamTokenizer stream) throws IOException, ParseException { String token = nextEmptyOrOpen(stream); - if (token.equals(EMPTY)) { + if (EMPTY.equals(token)) { return MultiPoint.EMPTY; } ArrayList lats = new ArrayList<>(); @@ -340,7 +340,7 @@ private static MultiPoint parseMultiPoint(StreamTokenizer stream) throws IOExcep private static Line parseLine(StreamTokenizer stream) throws IOException, ParseException { String token = nextEmptyOrOpen(stream); - if (token.equals(EMPTY)) { + if (EMPTY.equals(token)) { return Line.EMPTY; } ArrayList lats = new ArrayList<>(); @@ -356,7 +356,7 @@ private static Line parseLine(StreamTokenizer stream) throws IOException, ParseE private static MultiLine parseMultiLine(StreamTokenizer stream) throws IOException, ParseException { String token = nextEmptyOrOpen(stream); - if (token.equals(EMPTY)) { + if (EMPTY.equals(token)) { return MultiLine.EMPTY; } ArrayList lines = new ArrayList<>(); @@ -429,7 +429,7 @@ private static void closeLinearRingIfCoerced(ArrayList lats, ArrayList polygons = new ArrayList<>(); @@ -479,7 +479,7 @@ private static String nextWord(StreamTokenizer stream) throws ParseException, IO switch (stream.nextToken()) { case StreamTokenizer.TT_WORD: final String word = stream.sval; - return word.equalsIgnoreCase(EMPTY) ? EMPTY : word; + return EMPTY.equalsIgnoreCase(word) ? EMPTY : word; case '(': return LPAREN; case ')': @@ -523,7 +523,7 @@ private static boolean isNumberNext(StreamTokenizer stream) throws IOException { private static String nextEmptyOrOpen(StreamTokenizer stream) throws IOException, ParseException { final String next = nextWord(stream); - if (next.equals(EMPTY) || next.equals(LPAREN)) { + if (EMPTY.equals(next) || LPAREN.equals(next)) { return next; } throw new ParseException("expected " + EMPTY + " or " + LPAREN + " but found: " + tokenString(stream), stream.lineno()); @@ -552,7 +552,7 @@ private static String nextOpener(StreamTokenizer stream) throws IOException, Par private static String nextCloserOrComma(StreamTokenizer stream) throws IOException, ParseException { String token = nextWord(stream); - if (token.equals(COMMA) || token.equals(RPAREN)) { + if (COMMA.equals(token) || RPAREN.equals(token)) { return token; } throw new ParseException("expected " + COMMA + " or " + RPAREN + " but found: " + tokenString(stream), stream.lineno()); diff --git a/libs/secure-sm/src/main/java/org/elasticsearch/secure_sm/SecureSM.java b/libs/secure-sm/src/main/java/org/elasticsearch/secure_sm/SecureSM.java index 68d2f45386c59..5d5c2798298f0 100644 --- a/libs/secure-sm/src/main/java/org/elasticsearch/secure_sm/SecureSM.java +++ b/libs/secure-sm/src/main/java/org/elasticsearch/secure_sm/SecureSM.java @@ -156,7 +156,7 @@ private static void debugThreadGroups(final ThreadGroup caller, final ThreadGrou // Returns true if the given thread is an instance of the JDK's InnocuousThread. private static boolean isInnocuousThread(Thread t) { final Class c = t.getClass(); - return c.getModule() == Object.class.getModule() && c.getName().equals("jdk.internal.misc.InnocuousThread"); + return c.getModule() == Object.class.getModule() && "jdk.internal.misc.InnocuousThread".equals(c.getName()); } protected void checkThreadAccess(Thread t) { diff --git a/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/DefaultJdkTrustConfig.java b/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/DefaultJdkTrustConfig.java index 1ed506a8813a3..62e5cc5da585a 100644 --- a/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/DefaultJdkTrustConfig.java +++ b/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/DefaultJdkTrustConfig.java @@ -89,7 +89,7 @@ private KeyStore getSystemTrustStore() { } private static boolean isPkcs11Truststore(BiFunction systemProperties) { - return systemProperties.apply("javax.net.ssl.trustStoreType", "").equalsIgnoreCase("PKCS11"); + return "PKCS11".equalsIgnoreCase(systemProperties.apply("javax.net.ssl.trustStoreType", "")); } private static char[] getSystemTrustStorePassword(BiFunction systemProperties) { diff --git a/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/PemUtils.java b/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/PemUtils.java index 9bb0643907eb5..c2268e4932b22 100644 --- a/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/PemUtils.java +++ b/libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/PemUtils.java @@ -392,7 +392,7 @@ private static PrivateKey parsePKCS8Encrypted(BufferedReader bReader, char[] key final EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = getEncryptedPrivateKeyInfo(keyBytes); String algorithm = encryptedPrivateKeyInfo.getAlgName(); - if (algorithm.equals("PBES2") || algorithm.equals("1.2.840.113549.1.5.13")) { + if ("PBES2".equals(algorithm) || "1.2.840.113549.1.5.13".equals(algorithm)) { algorithm = getPBES2Algorithm(encryptedPrivateKeyInfo); } SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm); diff --git a/libs/x-content/src/main/java/org/elasticsearch/xcontent/support/filtering/FilterPath.java b/libs/x-content/src/main/java/org/elasticsearch/xcontent/support/filtering/FilterPath.java index 733e5b6b77684..b318ce2b7b09c 100644 --- a/libs/x-content/src/main/java/org/elasticsearch/xcontent/support/filtering/FilterPath.java +++ b/libs/x-content/src/main/java/org/elasticsearch/xcontent/support/filtering/FilterPath.java @@ -32,7 +32,7 @@ private FilterPath(String pattern, boolean isFinalNode, Map this.isFinalNode = isFinalNode; this.termsChildren = Collections.unmodifiableMap(termsChildren); this.wildcardChildren = wildcardChildren; - this.isDoubleWildcard = pattern.equals(DOUBLE_WILDCARD); + this.isDoubleWildcard = DOUBLE_WILDCARD.equals(pattern); } public boolean hasDoubleWildcard() { diff --git a/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/DelimitedPayloadTokenFilterFactory.java b/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/DelimitedPayloadTokenFilterFactory.java index 5f266d1517893..83add1d19bbb1 100644 --- a/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/DelimitedPayloadTokenFilterFactory.java +++ b/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/DelimitedPayloadTokenFilterFactory.java @@ -40,11 +40,11 @@ public class DelimitedPayloadTokenFilterFactory extends AbstractTokenFilterFacto } if (settings.get(ENCODING) != null) { - if (settings.get(ENCODING).equals("float")) { + if ("float".equals(settings.get(ENCODING))) { encoder = new FloatEncoder(); - } else if (settings.get(ENCODING).equals("int")) { + } else if ("int".equals(settings.get(ENCODING))) { encoder = new IntegerEncoder(); - } else if (settings.get(ENCODING).equals("identity")) { + } else if ("identity".equals(settings.get(ENCODING))) { encoder = new IdentityEncoder(); } else { encoder = DEFAULT_ENCODER; diff --git a/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/KeepTypesFilterFactory.java b/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/KeepTypesFilterFactory.java index bc1587a4fc66f..9f9946fe367c4 100644 --- a/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/KeepTypesFilterFactory.java +++ b/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/KeepTypesFilterFactory.java @@ -50,9 +50,9 @@ public String toString() { private static KeepTypesMode fromString(String modeString) { String lc = modeString.toLowerCase(Locale.ROOT); - if (lc.equals("include")) { + if ("include".equals(lc)) { return INCLUDE; - } else if (lc.equals("exclude")) { + } else if ("exclude".equals(lc)) { return EXCLUDE; } else { throw new IllegalArgumentException( diff --git a/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/LowerCaseTokenFilterFactory.java b/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/LowerCaseTokenFilterFactory.java index 9d6bb37cdf540..4b37a4e7e808b 100644 --- a/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/LowerCaseTokenFilterFactory.java +++ b/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/LowerCaseTokenFilterFactory.java @@ -41,11 +41,11 @@ public class LowerCaseTokenFilterFactory extends AbstractTokenFilterFactory impl public TokenStream create(TokenStream tokenStream) { if (lang == null) { return new LowerCaseFilter(tokenStream); - } else if (lang.equalsIgnoreCase("greek")) { + } else if ("greek".equalsIgnoreCase(lang)) { return new GreekLowerCaseFilter(tokenStream); - } else if (lang.equalsIgnoreCase("irish")) { + } else if ("irish".equalsIgnoreCase(lang)) { return new IrishLowerCaseFilter(tokenStream); - } else if (lang.equalsIgnoreCase("turkish")) { + } else if ("turkish".equalsIgnoreCase(lang)) { return new TurkishLowerCaseFilter(tokenStream); } else { throw new IllegalArgumentException("language [" + lang + "] not support for lower case"); diff --git a/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/NGramTokenizerFactory.java b/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/NGramTokenizerFactory.java index a8b5489f81d0b..cf8c88180ee79 100644 --- a/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/NGramTokenizerFactory.java +++ b/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/NGramTokenizerFactory.java @@ -70,7 +70,7 @@ static CharMatcher parseTokenChars(Settings settings) { characterClass = characterClass.toLowerCase(Locale.ROOT).trim(); CharMatcher matcher = MATCHERS.get(characterClass); if (matcher == null) { - if (characterClass.equals("custom") == false) { + if ("custom".equals(characterClass) == false) { throw new IllegalArgumentException( "Unknown token type: '" + characterClass diff --git a/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/SnowballAnalyzer.java b/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/SnowballAnalyzer.java index 9a10cc2493523..206d14d9fa1af 100644 --- a/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/SnowballAnalyzer.java +++ b/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/SnowballAnalyzer.java @@ -52,9 +52,9 @@ public TokenStreamComponents createComponents(String fieldName) { final Tokenizer tokenizer = new StandardTokenizer(); TokenStream result = tokenizer; // remove the possessive 's for english stemmers - if (name.equals("English") || name.equals("Porter") || name.equals("Lovins")) result = new EnglishPossessiveFilter(result); + if ("English".equals(name) || "Porter".equals(name) || "Lovins".equals(name)) result = new EnglishPossessiveFilter(result); // Use a special lowercase filter for turkish, the stemmer expects it. - if (name.equals("Turkish")) result = new TurkishLowerCaseFilter(result); + if ("Turkish".equals(name)) result = new TurkishLowerCaseFilter(result); else result = new LowerCaseFilter(result); if (stopSet != null) result = new StopFilter(result, stopSet); result = new SnowballFilter(result, name); diff --git a/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/WordDelimiterTokenFilterFactory.java b/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/WordDelimiterTokenFilterFactory.java index 9848a56f5395a..203cc2414db84 100644 --- a/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/WordDelimiterTokenFilterFactory.java +++ b/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/WordDelimiterTokenFilterFactory.java @@ -132,12 +132,12 @@ static byte[] parseTypes(Collection rules) { } private static Byte parseType(String s) { - if (s.equals("LOWER")) return WordDelimiterFilter.LOWER; - else if (s.equals("UPPER")) return WordDelimiterFilter.UPPER; - else if (s.equals("ALPHA")) return WordDelimiterFilter.ALPHA; - else if (s.equals("DIGIT")) return WordDelimiterFilter.DIGIT; - else if (s.equals("ALPHANUM")) return WordDelimiterFilter.ALPHANUM; - else if (s.equals("SUBWORD_DELIM")) return WordDelimiterFilter.SUBWORD_DELIM; + if ("LOWER".equals(s)) return WordDelimiterFilter.LOWER; + else if ("UPPER".equals(s)) return WordDelimiterFilter.UPPER; + else if ("ALPHA".equals(s)) return WordDelimiterFilter.ALPHA; + else if ("DIGIT".equals(s)) return WordDelimiterFilter.DIGIT; + else if ("ALPHANUM".equals(s)) return WordDelimiterFilter.ALPHANUM; + else if ("SUBWORD_DELIM".equals(s)) return WordDelimiterFilter.SUBWORD_DELIM; else return null; } diff --git a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/ConvertProcessor.java b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/ConvertProcessor.java index 3ba21de567a0c..a7bc6636ef9af 100644 --- a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/ConvertProcessor.java +++ b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/ConvertProcessor.java @@ -80,9 +80,9 @@ public Object convert(Object value) { BOOLEAN { @Override public Object convert(Object value) { - if (value.toString().equalsIgnoreCase("true")) { + if ("true".equalsIgnoreCase(value.toString())) { return true; - } else if (value.toString().equalsIgnoreCase("false")) { + } else if ("false".equalsIgnoreCase(value.toString())) { return false; } else { throw new IllegalArgumentException("[" + value + "] is not a boolean value, cannot convert to boolean"); diff --git a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/DotExpanderProcessor.java b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/DotExpanderProcessor.java index 5174ea614c0ee..186888b96cc11 100644 --- a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/DotExpanderProcessor.java +++ b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/DotExpanderProcessor.java @@ -48,7 +48,7 @@ public IngestDocument execute(IngestDocument ingestDocument) throws Exception { map = ingestDocument.getSourceAndMetadata(); } - if (this.field.equals("*")) { + if ("*".equals(this.field)) { for (String key : new ArrayList<>(map.keySet())) { if (key.indexOf('.') > 0) { pathToExpand = this.path != null ? this.path + "." + key : key; @@ -122,7 +122,7 @@ public Processor create( Map config ) throws Exception { String field = ConfigurationUtils.readStringProperty(TYPE, tag, config, "field"); - if (field.contains(".") == false && field.equals("*") == false) { + if (field.contains(".") == false && "*".equals(field) == false) { throw ConfigurationUtils.newConfigurationException( ConfigurationUtils.TAG_KEY, tag, diff --git a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/FingerprintProcessor.java b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/FingerprintProcessor.java index 701eab051dd1e..4cb9bb565b0ce 100644 --- a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/FingerprintProcessor.java +++ b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/FingerprintProcessor.java @@ -284,7 +284,7 @@ private MessageDigestHasher(MessageDigest md) { } static Hasher getInstance(String method) throws NoSuchAlgorithmException { - if (method.equalsIgnoreCase(MurmurHasher.METHOD)) { + if (MurmurHasher.METHOD.equalsIgnoreCase(method)) { return MurmurHasher.getInstance(method); } else { MessageDigest md = MessageDigest.getInstance(method); @@ -323,7 +323,7 @@ private MurmurHasher() { } static Hasher getInstance(String method) throws NoSuchAlgorithmException { - if (method.equalsIgnoreCase(METHOD) == false) { + if (METHOD.equalsIgnoreCase(method) == false) { throw new NoSuchAlgorithmException("supports only [" + METHOD + "] as method"); } return new MurmurHasher(); diff --git a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/GrokProcessor.java b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/GrokProcessor.java index f7d1c9f62305b..377c378c48d17 100644 --- a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/GrokProcessor.java +++ b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/GrokProcessor.java @@ -123,7 +123,7 @@ static String combinePatterns(List patterns, boolean traceMatch) { } else { valueWrap = "(?:" + patterns.get(i) + ")"; } - if (combinedPattern.equals("")) { + if ("".equals(combinedPattern)) { combinedPattern = valueWrap; } else { combinedPattern = combinedPattern + "|" + valueWrap; diff --git a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/RegisteredDomainProcessor.java b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/RegisteredDomainProcessor.java index 6b949889fc960..f1299042f42b9 100644 --- a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/RegisteredDomainProcessor.java +++ b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/RegisteredDomainProcessor.java @@ -56,7 +56,7 @@ public IngestDocument execute(IngestDocument ingestDocument) throws Exception { } } String fieldPrefix = targetField; - if (fieldPrefix.equals("") == false) { + if ("".equals(fieldPrefix) == false) { fieldPrefix += "."; } String domainTarget = fieldPrefix + "domain"; 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 41ced0c7ff4cc..91285aedc11b1 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 @@ -57,7 +57,7 @@ private void init(InputStream regexStream) throws IOException { token = yamlParser.nextToken(); for (; token != null; token = yamlParser.nextToken()) { - if (token == XContentParser.Token.FIELD_NAME && yamlParser.currentName().equals("user_agent_parsers")) { + if (token == XContentParser.Token.FIELD_NAME && "user_agent_parsers".equals(yamlParser.currentName())) { List> parserConfigurations = readParserConfigurations(yamlParser); for (Map map : parserConfigurations) { @@ -72,7 +72,7 @@ private void init(InputStream regexStream) throws IOException { ) ); } - } else if (token == XContentParser.Token.FIELD_NAME && yamlParser.currentName().equals("os_parsers")) { + } else if (token == XContentParser.Token.FIELD_NAME && "os_parsers".equals(yamlParser.currentName())) { List> parserConfigurations = readParserConfigurations(yamlParser); for (Map map : parserConfigurations) { @@ -87,7 +87,7 @@ private void init(InputStream regexStream) throws IOException { ) ); } - } else if (token == XContentParser.Token.FIELD_NAME && yamlParser.currentName().equals("device_parsers")) { + } else if (token == XContentParser.Token.FIELD_NAME && "device_parsers".equals(yamlParser.currentName())) { List> parserConfigurations = readParserConfigurations(yamlParser); for (Map map : parserConfigurations) { diff --git a/modules/lang-expression/src/main/java/org/elasticsearch/script/expression/ExpressionScriptEngine.java b/modules/lang-expression/src/main/java/org/elasticsearch/script/expression/ExpressionScriptEngine.java index 7d80a0d401013..607802fb0a721 100644 --- a/modules/lang-expression/src/main/java/org/elasticsearch/script/expression/ExpressionScriptEngine.java +++ b/modules/lang-expression/src/main/java/org/elasticsearch/script/expression/ExpressionScriptEngine.java @@ -245,7 +245,7 @@ private static NumberSortScript.LeafFactory newSortScript(Expression expr, Searc boolean needsScores = false; for (String variable : expr.variables) { try { - if (variable.equals("_score")) { + if ("_score".equals(variable)) { bindings.add("_score", DoubleValuesSource.SCORES); needsScores = true; } else if (vars != null && vars.containsKey(variable)) { @@ -302,10 +302,10 @@ private static AggregationScript.LeafFactory newAggregationScript( ReplaceableConstDoubleValueSource specialValue = null; for (String variable : expr.variables) { try { - if (variable.equals("_score")) { + if ("_score".equals(variable)) { bindings.add("_score", DoubleValuesSource.SCORES); needsScores = true; - } else if (variable.equals("_value")) { + } else if ("_value".equals(variable)) { specialValue = new ReplaceableConstDoubleValueSource(); bindings.add("_value", specialValue); // noop: _value is special for aggregations, and is handled in ExpressionScriptBindings @@ -374,10 +374,10 @@ private static ScoreScript.LeafFactory newScoreScript(Expression expr, SearchLoo boolean needsScores = false; for (String variable : expr.variables) { try { - if (variable.equals("_score")) { + if ("_score".equals(variable)) { bindings.add("_score", DoubleValuesSource.SCORES); needsScores = true; - } else if (variable.equals("_value")) { + } else if ("_value".equals(variable)) { bindings.add("_value", DoubleValuesSource.constant(0)); // noop: _value is special for aggregations, and is handled in ExpressionScriptBindings // TODO: if some uses it in a scoring expression, they will get a nasty failure when evaluating...need a diff --git a/modules/lang-painless/spi/src/main/java/org/elasticsearch/painless/spi/WhitelistLoader.java b/modules/lang-painless/spi/src/main/java/org/elasticsearch/painless/spi/WhitelistLoader.java index 238f4522fd7a0..e2685a57521b9 100644 --- a/modules/lang-painless/spi/src/main/java/org/elasticsearch/painless/spi/WhitelistLoader.java +++ b/modules/lang-painless/spi/src/main/java/org/elasticsearch/painless/spi/WhitelistLoader.java @@ -221,7 +221,7 @@ public static Whitelist loadFromResourceFiles(Class resource, Map getDisplayNames(List sortClassInfos(Collection excludeCommonClassInfos( diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/ScriptClassInfo.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/ScriptClassInfo.java index 8b0b57e6389fc..308ac09bc4007 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/ScriptClassInfo.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/ScriptClassInfo.java @@ -53,7 +53,7 @@ public ScriptClassInfo(PainlessLookup painlessLookup, Class baseClass) { if (m.isDefault()) { continue; } - if (m.getName().equals("execute")) { + if ("execute".equals(m.getName())) { if (executeMethod == null) { executeMethod = m; returnType = m.getReturnType(); @@ -67,7 +67,7 @@ public ScriptClassInfo(PainlessLookup painlessLookup, Class baseClass) { } else if (m.getName().startsWith("needs") && m.getReturnType() == boolean.class && m.getParameterTypes().length == 0) { needsMethods.add(new org.objectweb.asm.commons.Method(m.getName(), NEEDS_PARAMETER_METHOD_TYPE.toMethodDescriptorString())); } else if (m.getName().startsWith("get") - && m.getName().equals("getClass") == false + && "getClass".equals(m.getName()) == false && Modifier.isStatic(m.getModifiers()) == false) { getReturns.add( definitionTypeForClass( @@ -104,7 +104,7 @@ public ScriptClassInfo(PainlessLookup painlessLookup, Class baseClass) { && m.getReturnType() == returnType && Modifier.isStatic(m.getModifiers())) { - if (m.getName().equals("convertFromDef")) { + if ("convertFromDef".equals(m.getName())) { if (m.getParameterTypes()[0] != Object.class) { throw new IllegalStateException( "convertFromDef must take a single Object as an argument, " + "not [" + m.getParameterTypes()[0] + "]" diff --git a/modules/legacy-geo/src/main/java/org/elasticsearch/legacygeo/mapper/LegacyGeoShapeFieldMapper.java b/modules/legacy-geo/src/main/java/org/elasticsearch/legacygeo/mapper/LegacyGeoShapeFieldMapper.java index afd969cc17ad4..7b7fd3e8f3e93 100644 --- a/modules/legacy-geo/src/main/java/org/elasticsearch/legacygeo/mapper/LegacyGeoShapeFieldMapper.java +++ b/modules/legacy-geo/src/main/java/org/elasticsearch/legacygeo/mapper/LegacyGeoShapeFieldMapper.java @@ -286,17 +286,17 @@ private void setupFieldTypeDeprecatedParameters(GeoShapeFieldType ft) { private static void setupPrefixTrees(GeoShapeFieldType ft) { SpatialPrefixTree prefixTree; - if (ft.tree().equals(PrefixTrees.GEOHASH)) { + if (PrefixTrees.GEOHASH.equals(ft.tree())) { prefixTree = new GeohashPrefixTree( ShapeBuilder.SPATIAL_CONTEXT, getLevels(ft.treeLevels(), ft.precisionInMeters(), Defaults.GEOHASH_TREE_LEVELS, true) ); - } else if (ft.tree().equals(PrefixTrees.LEGACY_QUADTREE)) { + } else if (PrefixTrees.LEGACY_QUADTREE.equals(ft.tree())) { prefixTree = new QuadPrefixTree( ShapeBuilder.SPATIAL_CONTEXT, getLevels(ft.treeLevels(), ft.precisionInMeters(), Defaults.QUADTREE_LEVELS, false) ); - } else if (ft.tree().equals(PrefixTrees.QUADTREE)) { + } else if (PrefixTrees.QUADTREE.equals(ft.tree())) { prefixTree = new PackedQuadPrefixTree( ShapeBuilder.SPATIAL_CONTEXT, getLevels(ft.treeLevels(), ft.precisionInMeters(), Defaults.QUADTREE_LEVELS, false) diff --git a/modules/legacy-geo/src/main/java/org/elasticsearch/legacygeo/parsers/GeoWKTParser.java b/modules/legacy-geo/src/main/java/org/elasticsearch/legacygeo/parsers/GeoWKTParser.java index 805ed8a65597a..a3e445b701108 100644 --- a/modules/legacy-geo/src/main/java/org/elasticsearch/legacygeo/parsers/GeoWKTParser.java +++ b/modules/legacy-geo/src/main/java/org/elasticsearch/legacygeo/parsers/GeoWKTParser.java @@ -181,7 +181,7 @@ private static Coordinate parseCoordinate(StreamTokenizer stream, final boolean private static MultiPointBuilder parseMultiPoint(StreamTokenizer stream, final boolean ignoreZValue, final boolean coerce) throws IOException, ElasticsearchParseException { String token = nextEmptyOrOpen(stream); - if (token.equals(EMPTY)) { + if (EMPTY.equals(token)) { return new MultiPointBuilder(); } return new MultiPointBuilder(parseCoordinateList(stream, ignoreZValue, coerce)); @@ -190,7 +190,7 @@ private static MultiPointBuilder parseMultiPoint(StreamTokenizer stream, final b private static LineStringBuilder parseLine(StreamTokenizer stream, final boolean ignoreZValue, final boolean coerce) throws IOException, ElasticsearchParseException { String token = nextEmptyOrOpen(stream); - if (token.equals(EMPTY)) { + if (EMPTY.equals(token)) { return null; } return new LineStringBuilder(parseCoordinateList(stream, ignoreZValue, coerce)); @@ -201,7 +201,7 @@ private static LineStringBuilder parseLine(StreamTokenizer stream, final boolean private static LineStringBuilder parseLinearRing(StreamTokenizer stream, final boolean ignoreZValue, final boolean coerce) throws IOException, ElasticsearchParseException { String token = nextEmptyOrOpen(stream); - if (token.equals(EMPTY)) { + if (EMPTY.equals(token)) { return null; } List coordinates = parseCoordinateList(stream, ignoreZValue, coerce); @@ -224,7 +224,7 @@ private static LineStringBuilder parseLinearRing(StreamTokenizer stream, final b private static MultiLineStringBuilder parseMultiLine(StreamTokenizer stream, final boolean ignoreZValue, final boolean coerce) throws IOException, ElasticsearchParseException { String token = nextEmptyOrOpen(stream); - if (token.equals(EMPTY)) { + if (EMPTY.equals(token)) { return new MultiLineStringBuilder(); } MultiLineStringBuilder builder = new MultiLineStringBuilder(); @@ -281,7 +281,7 @@ private static String nextWord(StreamTokenizer stream) throws ElasticsearchParse switch (stream.nextToken()) { case StreamTokenizer.TT_WORD: final String word = stream.sval; - return word.equalsIgnoreCase(EMPTY) ? EMPTY : word; + return EMPTY.equalsIgnoreCase(word) ? EMPTY : word; case '(': return LPAREN; case ')': @@ -325,7 +325,7 @@ private static boolean isNumberNext(StreamTokenizer stream) throws IOException { private static String nextEmptyOrOpen(StreamTokenizer stream) throws IOException, ElasticsearchParseException { final String next = nextWord(stream); - if (next.equals(EMPTY) || next.equals(LPAREN)) { + if (EMPTY.equals(next) || LPAREN.equals(next)) { return next; } throw new ElasticsearchParseException( @@ -350,7 +350,7 @@ private static String nextComma(StreamTokenizer stream) throws IOException, Elas private static String nextCloserOrComma(StreamTokenizer stream) throws IOException, ElasticsearchParseException { String token = nextWord(stream); - if (token.equals(COMMA) || token.equals(RPAREN)) { + if (COMMA.equals(token) || RPAREN.equals(token)) { return token; } throw new ElasticsearchParseException( diff --git a/modules/mapper-extras/src/internalClusterTest/java/org/elasticsearch/index/mapper/RankFeaturesMapperIntegrationIT.java b/modules/mapper-extras/src/internalClusterTest/java/org/elasticsearch/index/mapper/RankFeaturesMapperIntegrationIT.java index c6544bac2b13c..e9e6752920b64 100644 --- a/modules/mapper-extras/src/internalClusterTest/java/org/elasticsearch/index/mapper/RankFeaturesMapperIntegrationIT.java +++ b/modules/mapper-extras/src/internalClusterTest/java/org/elasticsearch/index/mapper/RankFeaturesMapperIntegrationIT.java @@ -68,13 +68,13 @@ public void testRankFeaturesTermQuery() throws IOException { searchResponse -> { assertThat(searchResponse.getHits().getTotalHits().value, equalTo(3L)); for (SearchHit hit : searchResponse.getHits().getHits()) { - if (hit.getId().equals("all")) { + if ("all".equals(hit.getId())) { assertThat(hit.getScore(), equalTo(50f)); } - if (hit.getId().equals("lower")) { + if ("lower".equals(hit.getId())) { assertThat(hit.getScore(), equalTo(30f)); } - if (hit.getId().equals("higher")) { + if ("higher".equals(hit.getId())) { assertThat(hit.getScore(), equalTo(20f)); } } diff --git a/modules/mapper-extras/src/internalClusterTest/java/org/elasticsearch/index/mapper/TokenCountFieldMapperIntegrationIT.java b/modules/mapper-extras/src/internalClusterTest/java/org/elasticsearch/index/mapper/TokenCountFieldMapperIntegrationIT.java index 08a3d046b00f7..deb3d557a835e 100644 --- a/modules/mapper-extras/src/internalClusterTest/java/org/elasticsearch/index/mapper/TokenCountFieldMapperIntegrationIT.java +++ b/modules/mapper-extras/src/internalClusterTest/java/org/elasticsearch/index/mapper/TokenCountFieldMapperIntegrationIT.java @@ -211,17 +211,17 @@ private void assertSearchReturns(SearchResponse result, String... ids) { assertThat(foundIds, containsInAnyOrder(ids)); for (SearchHit hit : result.getHits()) { String id = hit.getId(); - if (id.equals("single")) { + if ("single".equals(id)) { assertSearchHit(hit, new int[] { 4 }, new int[] { 4 }); - } else if (id.equals("bulk1")) { + } else if ("bulk1".equals(id)) { assertSearchHit(hit, new int[] { 3 }, new int[] { 3 }); - } else if (id.equals("bulk2")) { + } else if ("bulk2".equals(id)) { assertSearchHit(hit, new int[] { 5 }, new int[] { 4 }); - } else if (id.equals("multi")) { + } else if ("multi".equals(id)) { assertSearchHit(hit, new int[] { 2, 7 }, new int[] { 2, 7 }); - } else if (id.equals("multibulk1")) { + } else if ("multibulk1".equals(id)) { assertSearchHit(hit, new int[] { 1, 8 }, new int[] { 1, 8 }); - } else if (id.equals("multibulk2")) { + } else if ("multibulk2".equals(id)) { assertSearchHit(hit, new int[] { 6, 10 }, new int[] { 3, 9 }); } else { throw new ElasticsearchException("Unexpected response!"); diff --git a/modules/rank-eval/src/internalClusterTest/java/org/elasticsearch/index/rankeval/RankEvalRequestIT.java b/modules/rank-eval/src/internalClusterTest/java/org/elasticsearch/index/rankeval/RankEvalRequestIT.java index 699cb307e3310..59cfc8762ab96 100644 --- a/modules/rank-eval/src/internalClusterTest/java/org/elasticsearch/index/rankeval/RankEvalRequestIT.java +++ b/modules/rank-eval/src/internalClusterTest/java/org/elasticsearch/index/rankeval/RankEvalRequestIT.java @@ -104,7 +104,7 @@ public void testPrecisionAtRequest() { assertEquals(6, hitsAndRatings.size()); for (RatedSearchHit hit : hitsAndRatings) { String id = hit.getSearchHit().getId(); - if (id.equals("1") || id.equals("6")) { + if ("1".equals(id) || "6".equals(id)) { assertFalse(hit.getRating().isPresent()); } else { assertEquals(RELEVANT_RATING_1, hit.getRating().getAsInt()); @@ -117,7 +117,7 @@ public void testPrecisionAtRequest() { assertEquals(6, hitsAndRatings.size()); for (RatedSearchHit hit : hitsAndRatings) { String id = hit.getSearchHit().getId(); - if (id.equals("1")) { + if ("1".equals(id)) { assertEquals(RELEVANT_RATING_1, hit.getRating().getAsInt()); } else { assertFalse(hit.getRating().isPresent()); diff --git a/modules/repository-azure/src/main/java/org/elasticsearch/repositories/azure/AzureBlobStore.java b/modules/repository-azure/src/main/java/org/elasticsearch/repositories/azure/AzureBlobStore.java index 91ac9996f97ca..62438bf0204bf 100644 --- a/modules/repository-azure/src/main/java/org/elasticsearch/repositories/azure/AzureBlobStore.java +++ b/modules/repository-azure/src/main/java/org/elasticsearch/repositories/azure/AzureBlobStore.java @@ -159,19 +159,19 @@ && isPutBlockListRequest(httpMethod, url) == false, } private static boolean isListRequest(String httpMethod, URL url) { - return httpMethod.equals("GET") && url.getQuery() != null && url.getQuery().contains("comp=list"); + return "GET".equals(httpMethod) && url.getQuery() != null && url.getQuery().contains("comp=list"); } // https://docs.microsoft.com/en-us/rest/api/storageservices/put-block private static boolean isPutBlockRequest(String httpMethod, URL url) { String queryParams = url.getQuery() == null ? "" : url.getQuery(); - return httpMethod.equals("PUT") && queryParams.contains("comp=block") && queryParams.contains("blockid="); + return "PUT".equals(httpMethod) && queryParams.contains("comp=block") && queryParams.contains("blockid="); } // https://docs.microsoft.com/en-us/rest/api/storageservices/put-block-list private static boolean isPutBlockListRequest(String httpMethod, URL url) { String queryParams = url.getQuery() == null ? "" : url.getQuery(); - return httpMethod.equals("PUT") && queryParams.contains("comp=blocklist"); + return "PUT".equals(httpMethod) && queryParams.contains("comp=blocklist"); } public long getReadChunkSize() { diff --git a/modules/repository-s3/src/main/java/org/elasticsearch/repositories/s3/S3BlobStore.java b/modules/repository-s3/src/main/java/org/elasticsearch/repositories/s3/S3BlobStore.java index 37d076362f396..3db94af452430 100644 --- a/modules/repository-s3/src/main/java/org/elasticsearch/repositories/s3/S3BlobStore.java +++ b/modules/repository-s3/src/main/java/org/elasticsearch/repositories/s3/S3BlobStore.java @@ -382,7 +382,7 @@ public StorageClass getStorageClass() { } public static StorageClass initStorageClass(String storageClass) { - if ((storageClass == null) || storageClass.equals("")) { + if ((storageClass == null) || "".equals(storageClass)) { return StorageClass.Standard; } @@ -402,7 +402,7 @@ public static StorageClass initStorageClass(String storageClass) { * Constructs canned acl from string */ public static CannedAccessControlList initCannedACL(String cannedACL) { - if ((cannedACL == null) || cannedACL.equals("")) { + if ((cannedACL == null) || "".equals(cannedACL)) { return CannedAccessControlList.Private; } diff --git a/modules/repository-url/src/main/java/org/elasticsearch/common/blobstore/url/URLBlobStore.java b/modules/repository-url/src/main/java/org/elasticsearch/common/blobstore/url/URLBlobStore.java index 0a6a7c22e79e5..5de95e0880bf6 100644 --- a/modules/repository-url/src/main/java/org/elasticsearch/common/blobstore/url/URLBlobStore.java +++ b/modules/repository-url/src/main/java/org/elasticsearch/common/blobstore/url/URLBlobStore.java @@ -61,7 +61,7 @@ public URLBlobStore(Settings settings, URL path, URLHttpClient httpClient, URLHt this.bufferSizeInBytes = (int) BUFFER_SIZE_SETTING.get(settings).getBytes(); final String protocol = this.path.getProtocol(); - if (protocol.equals("http") || protocol.equals("https")) { + if ("http".equals(protocol) || "https".equals(protocol)) { this.blobContainerFactory = (blobPath) -> new HttpURLBlobContainer( this, blobPath, @@ -69,7 +69,7 @@ public URLBlobStore(Settings settings, URL path, URLHttpClient httpClient, URLHt httpClient, httpClientSettings ); - } else if (protocol.equals("file")) { + } else if ("file".equals(protocol)) { this.blobContainerFactory = (blobPath) -> new FileURLBlobContainer(this, blobPath, buildPath(blobPath)); } else { this.blobContainerFactory = (blobPath) -> new URLBlobContainer(this, blobPath, buildPath(blobPath)); diff --git a/plugins/repository-hdfs/src/main/java/org/elasticsearch/repositories/hdfs/HdfsRepository.java b/plugins/repository-hdfs/src/main/java/org/elasticsearch/repositories/hdfs/HdfsRepository.java index a855428c3252b..6001e2c2c30af 100644 --- a/plugins/repository-hdfs/src/main/java/org/elasticsearch/repositories/hdfs/HdfsRepository.java +++ b/plugins/repository-hdfs/src/main/java/org/elasticsearch/repositories/hdfs/HdfsRepository.java @@ -84,7 +84,7 @@ public HdfsRepository( ) ); } - if (Strings.hasLength(uri.getPath()) && uri.getPath().equals("/") == false) { + if (Strings.hasLength(uri.getPath()) && "/".equals(uri.getPath()) == false) { throw new IllegalArgumentException( String.format( Locale.ROOT, diff --git a/qa/logging-config/src/javaRestTest/java/org/elasticsearch/common/logging/ESJsonLogsConfigIT.java b/qa/logging-config/src/javaRestTest/java/org/elasticsearch/common/logging/ESJsonLogsConfigIT.java index 1f838d01517bb..aa93e5ab55f83 100644 --- a/qa/logging-config/src/javaRestTest/java/org/elasticsearch/common/logging/ESJsonLogsConfigIT.java +++ b/qa/logging-config/src/javaRestTest/java/org/elasticsearch/common/logging/ESJsonLogsConfigIT.java @@ -33,7 +33,7 @@ protected Matcher nodeNameMatcher() { protected BufferedReader openReader(Path logFile) { assumeFalse( "Skipping test because it is being run against an external cluster.", - logFile.getFileName().toString().equals("--external--") + "--external--".equals(logFile.getFileName().toString()) ); return AccessController.doPrivileged((PrivilegedAction) () -> { diff --git a/qa/smoke-test-http/src/javaRestTest/java/org/elasticsearch/http/HttpStatsIT.java b/qa/smoke-test-http/src/javaRestTest/java/org/elasticsearch/http/HttpStatsIT.java index ac1bde443f703..d7c7ab65efd00 100644 --- a/qa/smoke-test-http/src/javaRestTest/java/org/elasticsearch/http/HttpStatsIT.java +++ b/qa/smoke-test-http/src/javaRestTest/java/org/elasticsearch/http/HttpStatsIT.java @@ -94,7 +94,7 @@ private void assertHttpStats(XContentTestUtils.JsonMapView jsonMapView) { assertThat(route, jsonMapView.get("http.routes." + route + ".requests.size_histogram"), hasSize(1)); assertThat(route, jsonMapView.get("http.routes." + route + ".requests.size_histogram.0.count"), equalTo(1)); assertThat(route, jsonMapView.get("http.routes." + route + ".requests.size_histogram.0.lt_bytes"), notNullValue()); - if (route.equals("/{index}/_search")) { + if ("/{index}/_search".equals(route)) { assertThat(route, jsonMapView.get("http.routes." + route + ".requests.size_histogram.0.ge_bytes"), notNullValue()); } assertThat(route, jsonMapView.get("http.routes." + route + ".responses.size_histogram"), hasSize(1)); diff --git a/server/src/internalClusterTest/java/org/elasticsearch/action/admin/cluster/allocation/ClusterAllocationExplainIT.java b/server/src/internalClusterTest/java/org/elasticsearch/action/admin/cluster/allocation/ClusterAllocationExplainIT.java index 1c358fe06b68f..ced349a835516 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/action/admin/cluster/allocation/ClusterAllocationExplainIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/action/admin/cluster/allocation/ClusterAllocationExplainIT.java @@ -238,7 +238,7 @@ public void testUnassignedReplicaDelayedAllocation() throws Exception { assertEquals(nodeHoldingPrimary ? 1 : 0, result.getCanAllocateDecision().getDecisions().size()); } for (Decision d : result.getCanAllocateDecision().getDecisions()) { - if (d.label().equals("same_shard") && nodeHoldingPrimary) { + if ("same_shard".equals(d.label()) && nodeHoldingPrimary) { assertEquals(Decision.Type.NO, d.type()); assertThat(d.getExplanation(), startsWith("a copy of this shard is already allocated to this node [")); } else { @@ -356,10 +356,10 @@ public void testUnassignedReplicaWithPriorCopy() throws Exception { assertEquals(1, result.getCanAllocateDecision().getDecisions().size()); } for (Decision d : result.getCanAllocateDecision().getDecisions()) { - if (d.label().equals("same_shard") && nodeHoldingPrimary) { + if ("same_shard".equals(d.label()) && nodeHoldingPrimary) { assertEquals(Decision.Type.NO, d.type()); assertThat(d.getExplanation(), startsWith("a copy of this shard is already allocated to this node [")); - } else if (d.label().equals("filter") && nodeHoldingPrimary == false) { + } else if ("filter".equals(d.label()) && nodeHoldingPrimary == false) { assertEquals(Decision.Type.NO, d.type()); assertEquals(Strings.format(""" node does not match index setting [index.routing.allocation.include] \ @@ -386,7 +386,7 @@ public void testUnassignedReplicaWithPriorCopy() throws Exception { parser.nextToken(); assertEquals("allocate_explanation", parser.currentName()); parser.nextToken(); - if (allocationDecision.equals("awaiting_info")) { + if ("awaiting_info".equals(allocationDecision)) { assertEquals(Explanations.Allocation.AWAITING_INFO, parser.text()); } else { assertEquals(Explanations.Allocation.ALL_NODES_FORBIDDEN, parser.text()); @@ -462,7 +462,7 @@ public void testAllocationFilteringOnIndexCreation() throws Exception { assertEquals(1, result.getCanAllocateDecision().getDecisions().size()); } for (Decision d : result.getCanAllocateDecision().getDecisions()) { - if (d.label().equals("filter")) { + if ("filter".equals(d.label())) { assertEquals(Decision.Type.NO, d.type()); assertEquals( "node does not match index setting [index.routing.allocation.include] filters [_name:\"non_existent_node\"]", @@ -486,7 +486,7 @@ public void testAllocationFilteringOnIndexCreation() throws Exception { parser.nextToken(); assertEquals("allocate_explanation", parser.currentName()); parser.nextToken(); - if (allocationDecision.equals("awaiting_info")) { + if ("awaiting_info".equals(allocationDecision)) { assertEquals(Explanations.Allocation.AWAITING_INFO, parser.text()); } else { assertEquals(Explanations.Allocation.ALL_NODES_FORBIDDEN, parser.text()); @@ -552,7 +552,7 @@ public void testAllocationFilteringPreventsShardMove() throws Exception { assertNotNull(moveDecision.getCanRemainDecision()); assertEquals(Decision.Type.NO, moveDecision.getCanRemainDecision().type()); for (Decision d : moveDecision.getCanRemainDecision().getDecisions()) { - if (d.label().equals("filter")) { + if ("filter".equals(d.label())) { assertEquals(Decision.Type.NO, d.type()); assertEquals( "node does not match index setting [index.routing.allocation.include] filters [_name:\"non_existent_node\"]", @@ -575,7 +575,7 @@ public void testAllocationFilteringPreventsShardMove() throws Exception { assertEquals(1, result.getCanAllocateDecision().getDecisions().size()); } for (Decision d : result.getCanAllocateDecision().getDecisions()) { - if (d.label().equals("filter")) { + if ("filter".equals(d.label())) { assertEquals(Decision.Type.NO, d.type()); assertEquals( "node does not match index setting [index.routing.allocation.include] filters [_name:\"non_existent_node\"]", @@ -665,7 +665,7 @@ public void testRebalancingNotAllowed() throws Exception { assertNotNull(moveDecision.getClusterRebalanceDecision()); assertEquals(Decision.Type.NO, moveDecision.getClusterRebalanceDecision().type()); for (Decision d : moveDecision.getClusterRebalanceDecision().getDecisions()) { - if (d.label().equals("enable")) { + if ("enable".equals(d.label())) { assertEquals(Decision.Type.NO, d.type()); assertEquals("no rebalancing is allowed due to index setting [index.routing.rebalance.enable=none]", d.getExplanation()); } else { @@ -885,7 +885,7 @@ public void testBetterBalanceButCannotAllocate() throws Exception { } String primaryNodeName = primaryNodeName(); for (Decision d : result.getCanAllocateDecision().getDecisions()) { - if (d.label().equals("filter")) { + if ("filter".equals(d.label())) { assertEquals(Decision.Type.NO, d.type()); assertEquals(Strings.format(""" node does not match index setting [index.routing.allocation.include] filters [_name:"%s"]\ @@ -1333,7 +1333,7 @@ private void verifyShardInfo(XContentParser parser, boolean primary, boolean inc while ((token = parser.nextToken()) != Token.END_OBJECT) { // until we reach end of unassigned_info if (token == XContentParser.Token.FIELD_NAME) { assertNotEquals("delayed", parser.currentName()); // we should never display "delayed" from unassigned info - if (parser.currentName().equals("last_allocation_status")) { + if ("last_allocation_status".equals(parser.currentName())) { parser.nextToken(); assertThat( parser.text(), @@ -1358,11 +1358,11 @@ private void verifyShardInfo(XContentParser parser, boolean primary, boolean inc while ((token = parser.nextToken()) != Token.END_OBJECT) { // until we reach end of current_node if (token == Token.FIELD_NAME) { assertTrue( - parser.currentName().equals("id") - || parser.currentName().equals("name") - || parser.currentName().equals("transport_address") - || parser.currentName().equals("roles") - || parser.currentName().equals("weight_ranking") + "id".equals(parser.currentName()) + || "name".equals(parser.currentName()) + || "transport_address".equals(parser.currentName()) + || "roles".equals(parser.currentName()) + || "weight_ranking".equals(parser.currentName()) ); } else if (token == Token.START_ARRAY || token == Token.END_ARRAY) { assertEquals("roles", parser.currentName()); @@ -1513,8 +1513,8 @@ private boolean verifyDeciders(XContentParser parser, AllocationDecision allocat assertEquals("decision", parser.currentName()); parser.nextToken(); String decisionText = parser.text(); - if ((allocationDecision == AllocationDecision.NO && decisionText.equals("NO") - || (allocationDecision == AllocationDecision.THROTTLED && decisionText.equals("THROTTLE")))) { + if ((allocationDecision == AllocationDecision.NO && "NO".equals(decisionText) + || (allocationDecision == AllocationDecision.THROTTLED && "THROTTLE".equals(decisionText)))) { atLeastOneMatchingDecisionFound = true; } assertNotNull(decisionText); diff --git a/server/src/internalClusterTest/java/org/elasticsearch/action/admin/cluster/stats/ClusterStatsIT.java b/server/src/internalClusterTest/java/org/elasticsearch/action/admin/cluster/stats/ClusterStatsIT.java index 902f74ef778a0..ea8c36682fdbc 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/action/admin/cluster/stats/ClusterStatsIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/action/admin/cluster/stats/ClusterStatsIT.java @@ -291,11 +291,11 @@ public void testFieldTypes() { assertThat(response.getIndicesStats().getMappings().getFieldTypeStats().size(), equalTo(3)); List stats = response.getIndicesStats().getMappings().getFieldTypeStats(); for (FieldStats stat : stats) { - if (stat.getName().equals("integer")) { + if ("integer".equals(stat.getName())) { assertThat(stat.getCount(), greaterThanOrEqualTo(1)); - } else if (stat.getName().equals("keyword")) { + } else if ("keyword".equals(stat.getName())) { assertThat(stat.getCount(), greaterThanOrEqualTo(3)); - } else if (stat.getName().equals("object")) { + } else if ("object".equals(stat.getName())) { assertThat(stat.getCount(), greaterThanOrEqualTo(1)); } } diff --git a/server/src/internalClusterTest/java/org/elasticsearch/action/bulk/BulkProcessor2IT.java b/server/src/internalClusterTest/java/org/elasticsearch/action/bulk/BulkProcessor2IT.java index f5fdb7b50c59c..10da53c55e136 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/action/bulk/BulkProcessor2IT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/action/bulk/BulkProcessor2IT.java @@ -202,7 +202,7 @@ public void testBulkProcessor2ConcurrentRequestsReadOnlyIndex() throws Exception Set readOnlyIds = new HashSet<>(); for (BulkItemResponse bulkItemResponse : listener.bulkItems) { assertThat(bulkItemResponse.getIndex(), either(equalTo("test")).or(equalTo("test-ro"))); - if (bulkItemResponse.getIndex().equals("test")) { + if ("test".equals(bulkItemResponse.getIndex())) { assertThat(bulkItemResponse.isFailed(), equalTo(false)); // with concurrent requests > 1 we can't rely on the order of the bulk requests assertThat(Integer.valueOf(bulkItemResponse.getId()), both(greaterThan(0)).and(lessThanOrEqualTo(testDocs))); diff --git a/server/src/internalClusterTest/java/org/elasticsearch/action/bulk/BulkProcessorIT.java b/server/src/internalClusterTest/java/org/elasticsearch/action/bulk/BulkProcessorIT.java index dc0ccb803eb52..a1ed9aa9c8011 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/action/bulk/BulkProcessorIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/action/bulk/BulkProcessorIT.java @@ -281,7 +281,7 @@ public void testBulkProcessorConcurrentRequestsReadOnlyIndex() throws Exception Set readOnlyIds = new HashSet<>(); for (BulkItemResponse bulkItemResponse : listener.bulkItems) { assertThat(bulkItemResponse.getIndex(), either(equalTo("test")).or(equalTo("test-ro"))); - if (bulkItemResponse.getIndex().equals("test")) { + if ("test".equals(bulkItemResponse.getIndex())) { assertThat(bulkItemResponse.isFailed(), equalTo(false)); // with concurrent requests > 1 we can't rely on the order of the bulk requests assertThat(Integer.valueOf(bulkItemResponse.getId()), both(greaterThan(0)).and(lessThanOrEqualTo(testDocs))); diff --git a/server/src/internalClusterTest/java/org/elasticsearch/cluster/ClusterInfoServiceIT.java b/server/src/internalClusterTest/java/org/elasticsearch/cluster/ClusterInfoServiceIT.java index 48ba897ebb76c..9e136fa2cb595 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/cluster/ClusterInfoServiceIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/cluster/ClusterInfoServiceIT.java @@ -138,7 +138,7 @@ public void testClusterInfoServiceCollectsInformation() { Settings.builder() .put(Store.INDEX_STORE_STATS_REFRESH_INTERVAL_SETTING.getKey(), 0) .put(EnableAllocationDecider.INDEX_ROUTING_REBALANCE_ENABLE_SETTING.getKey(), EnableAllocationDecider.Rebalance.NONE) - .put(IndexMetadata.SETTING_INDEX_HIDDEN, indexName.equals(TEST_SYSTEM_INDEX_NAME) || randomBoolean()) + .put(IndexMetadata.SETTING_INDEX_HIDDEN, TEST_SYSTEM_INDEX_NAME.equals(indexName) || randomBoolean()) .build() ) ); diff --git a/server/src/internalClusterTest/java/org/elasticsearch/cluster/metadata/AutoExpandReplicasIT.java b/server/src/internalClusterTest/java/org/elasticsearch/cluster/metadata/AutoExpandReplicasIT.java index ce69a088a1739..102e50947d117 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/cluster/metadata/AutoExpandReplicasIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/cluster/metadata/AutoExpandReplicasIT.java @@ -30,7 +30,7 @@ public void testClampToMinMax() throws Exception { .build() ); - final int initialReplicas = autoExpandValue.equals("0-1") ? 1 : internalCluster().numDataNodes() - 1; + final int initialReplicas = "0-1".equals(autoExpandValue) ? 1 : internalCluster().numDataNodes() - 1; assertBusy(() -> { assertThat( diff --git a/server/src/internalClusterTest/java/org/elasticsearch/cluster/shards/ClusterSearchShardsIT.java b/server/src/internalClusterTest/java/org/elasticsearch/cluster/shards/ClusterSearchShardsIT.java index d52498043366a..b2e6f484284f2 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/cluster/shards/ClusterSearchShardsIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/cluster/shards/ClusterSearchShardsIT.java @@ -93,10 +93,10 @@ public void testMultipleIndicesAllocation() throws Exception { boolean seenTest1 = false; boolean seenTest2 = false; for (ClusterSearchShardsGroup group : response.getGroups()) { - if (group.getShardId().getIndexName().equals("test1")) { + if ("test1".equals(group.getShardId().getIndexName())) { seenTest1 = true; assertThat(group.getShards().length, equalTo(2)); - } else if (group.getShardId().getIndexName().equals("test2")) { + } else if ("test2".equals(group.getShardId().getIndexName())) { seenTest2 = true; assertThat(group.getShards().length, equalTo(2)); } else { diff --git a/server/src/internalClusterTest/java/org/elasticsearch/env/NodeEnvironmentIT.java b/server/src/internalClusterTest/java/org/elasticsearch/env/NodeEnvironmentIT.java index 8c6abc3e14cd8..3fd1ad62c0536 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/env/NodeEnvironmentIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/env/NodeEnvironmentIT.java @@ -172,7 +172,7 @@ public void testUpgradeDataFolder() throws IOException, InterruptedException { for (Path subPath : stream) { String fileName = subPath.getFileName().toString(); Path targetSubPath = targetPath.resolve(fileName); - if (fileName.equals("nodes") == false) { + if ("nodes".equals(fileName) == false) { Files.move(subPath, targetSubPath, StandardCopyOption.ATOMIC_MOVE); } } diff --git a/server/src/internalClusterTest/java/org/elasticsearch/health/HealthMetadataServiceIT.java b/server/src/internalClusterTest/java/org/elasticsearch/health/HealthMetadataServiceIT.java index 660d6028486a0..d3f5499be2640 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/health/HealthMetadataServiceIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/health/HealthMetadataServiceIT.java @@ -287,7 +287,7 @@ private Settings createWatermarkSettings(String highWatermark, String highMaxHea settings = settings.put(CLUSTER_ROUTING_ALLOCATION_LOW_DISK_MAX_HEADROOM_SETTING.getKey(), "20b") .put(CLUSTER_ROUTING_ALLOCATION_DISK_FLOOD_STAGE_MAX_HEADROOM_SETTING.getKey(), "1b") .put(DiskThresholdSettings.CLUSTER_ROUTING_ALLOCATION_DISK_FLOOD_STAGE_FROZEN_MAX_HEADROOM_SETTING.getKey(), "5b"); - if (highMaxHeadroom.equals("-1") == false) { + if ("-1".equals(highMaxHeadroom) == false) { settings = settings.put(CLUSTER_ROUTING_ALLOCATION_HIGH_DISK_MAX_HEADROOM_SETTING.getKey(), highMaxHeadroom); } } diff --git a/server/src/internalClusterTest/java/org/elasticsearch/index/SettingsListenerIT.java b/server/src/internalClusterTest/java/org/elasticsearch/index/SettingsListenerIT.java index de783a28bce1d..2056f891079c6 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/index/SettingsListenerIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/index/SettingsListenerIT.java @@ -41,7 +41,7 @@ public List> getSettings() { @Override public void onIndexModule(IndexModule module) { - if (module.getIndex().getName().equals("test")) { // only for the test index + if ("test".equals(module.getIndex().getName())) { // only for the test index module.addSettingsUpdateConsumer(SettingsTestingService.VALUE, service::setValue); service.setValue(SettingsTestingService.VALUE.get(module.getSettings())); } diff --git a/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/bucket/TermsShardMinDocCountIT.java b/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/bucket/TermsShardMinDocCountIT.java index c8e23d65b4e37..ff216f4747605 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/bucket/TermsShardMinDocCountIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/search/aggregations/bucket/TermsShardMinDocCountIT.java @@ -114,7 +114,7 @@ public void testShardMinDocCountTermsTest() throws Exception { final String[] termTypes = { "text", "long", "integer", "float", "double" }; String termtype = termTypes[randomInt(termTypes.length - 1)]; String termMappings = "type=" + termtype; - if (termtype.equals("text")) { + if ("text".equals(termtype)) { termMappings += ",fielddata=true"; } assertAcked(prepareCreate(index).setSettings(indexSettings(1, 0)).setMapping("text", termMappings)); diff --git a/server/src/internalClusterTest/java/org/elasticsearch/search/fetch/subphase/MatchedQueriesIT.java b/server/src/internalClusterTest/java/org/elasticsearch/search/fetch/subphase/MatchedQueriesIT.java index c996725e6285e..db783ebb234c4 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/search/fetch/subphase/MatchedQueriesIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/search/fetch/subphase/MatchedQueriesIT.java @@ -57,11 +57,11 @@ public void testSimpleMatchedQueryFromFilteredQuery() throws Exception { response -> { assertHitCount(response, 3L); for (SearchHit hit : response.getHits()) { - if (hit.getId().equals("3") || hit.getId().equals("2")) { + if ("3".equals(hit.getId()) || "2".equals(hit.getId())) { assertThat(hit.getMatchedQueriesAndScores().size(), equalTo(1)); assertThat(hit.getMatchedQueriesAndScores(), hasKey("test2")); assertThat(hit.getMatchedQueryScore("test2"), equalTo(1f)); - } else if (hit.getId().equals("1")) { + } else if ("1".equals(hit.getId())) { assertThat(hit.getMatchedQueriesAndScores().size(), equalTo(1)); assertThat(hit.getMatchedQueriesAndScores(), hasKey("test1")); assertThat(hit.getMatchedQueryScore("test1"), equalTo(1f)); @@ -79,11 +79,11 @@ public void testSimpleMatchedQueryFromFilteredQuery() throws Exception { response -> { assertHitCount(response, 3L); for (SearchHit hit : response.getHits()) { - if (hit.getId().equals("1") || hit.getId().equals("2")) { + if ("1".equals(hit.getId()) || "2".equals(hit.getId())) { assertThat(hit.getMatchedQueriesAndScores().size(), equalTo(1)); assertThat(hit.getMatchedQueriesAndScores(), hasKey("test1")); assertThat(hit.getMatchedQueryScore("test1"), equalTo(1f)); - } else if (hit.getId().equals("3")) { + } else if ("3".equals(hit.getId())) { assertThat(hit.getMatchedQueriesAndScores().size(), equalTo(1)); assertThat(hit.getMatchedQueriesAndScores(), hasKey("test2")); assertThat(hit.getMatchedQueryScore("test2"), equalTo(1f)); @@ -112,13 +112,13 @@ public void testSimpleMatchedQueryFromTopLevelFilter() throws Exception { response -> { assertHitCount(response, 3L); for (SearchHit hit : response.getHits()) { - if (hit.getId().equals("1")) { + if ("1".equals(hit.getId())) { assertThat(hit.getMatchedQueriesAndScores().size(), equalTo(2)); assertThat(hit.getMatchedQueriesAndScores(), hasKey("name")); assertThat(hit.getMatchedQueryScore("name"), greaterThan(0f)); assertThat(hit.getMatchedQueriesAndScores(), hasKey("title")); assertThat(hit.getMatchedQueryScore("title"), greaterThan(0f)); - } else if (hit.getId().equals("2") || hit.getId().equals("3")) { + } else if ("2".equals(hit.getId()) || "3".equals(hit.getId())) { assertThat(hit.getMatchedQueriesAndScores().size(), equalTo(1)); assertThat(hit.getMatchedQueriesAndScores(), hasKey("name")); assertThat(hit.getMatchedQueryScore("name"), greaterThan(0f)); @@ -137,13 +137,13 @@ public void testSimpleMatchedQueryFromTopLevelFilter() throws Exception { response -> { assertHitCount(response, 3L); for (SearchHit hit : response.getHits()) { - if (hit.getId().equals("1")) { + if ("1".equals(hit.getId())) { assertThat(hit.getMatchedQueriesAndScores().size(), equalTo(2)); assertThat(hit.getMatchedQueriesAndScores(), hasKey("name")); assertThat(hit.getMatchedQueryScore("name"), greaterThan(0f)); assertThat(hit.getMatchedQueriesAndScores(), hasKey("title")); assertThat(hit.getMatchedQueryScore("title"), greaterThan(0f)); - } else if (hit.getId().equals("2") || hit.getId().equals("3")) { + } else if ("2".equals(hit.getId()) || "3".equals(hit.getId())) { assertThat(hit.getMatchedQueriesAndScores().size(), equalTo(1)); assertThat(hit.getMatchedQueriesAndScores(), hasKey("name")); assertThat(hit.getMatchedQueryScore("name"), greaterThan(0f)); @@ -171,7 +171,7 @@ public void testSimpleMatchedQueryFromTopLevelFilterAndFilteredQuery() throws Ex response -> { assertHitCount(response, 3L); for (SearchHit hit : response.getHits()) { - if (hit.getId().equals("1") || hit.getId().equals("2") || hit.getId().equals("3")) { + if ("1".equals(hit.getId()) || "2".equals(hit.getId()) || "3".equals(hit.getId())) { assertThat(hit.getMatchedQueriesAndScores().size(), equalTo(2)); assertThat(hit.getMatchedQueriesAndScores(), hasKey("name")); assertThat(hit.getMatchedQueryScore("name"), greaterThan(0f)); @@ -190,7 +190,7 @@ public void testSimpleMatchedQueryFromTopLevelFilterAndFilteredQuery() throws Ex response -> { assertHitCount(response, 3L); for (SearchHit hit : response.getHits()) { - if (hit.getId().equals("1") || hit.getId().equals("2") || hit.getId().equals("3")) { + if ("1".equals(hit.getId()) || "2".equals(hit.getId()) || "3".equals(hit.getId())) { assertThat(hit.getMatchedQueriesAndScores().size(), equalTo(2)); assertThat(hit.getMatchedQueriesAndScores(), hasKey("name")); assertThat(hit.getMatchedQueryScore("name"), greaterThan(0f)); @@ -215,7 +215,7 @@ public void testRegExpQuerySupportsName() { assertHitCount(response, 1L); for (SearchHit hit : response.getHits()) { - if (hit.getId().equals("1")) { + if ("1".equals(hit.getId())) { assertThat(hit.getMatchedQueriesAndScores().size(), equalTo(1)); assertThat(hit.getMatchedQueriesAndScores(), hasKey("regex")); assertThat(hit.getMatchedQueryScore("regex"), equalTo(1f)); @@ -237,7 +237,7 @@ public void testPrefixQuerySupportsName() { assertHitCount(response, 1L); for (SearchHit hit : response.getHits()) { - if (hit.getId().equals("1")) { + if ("1".equals(hit.getId())) { assertThat(hit.getMatchedQueriesAndScores().size(), equalTo(1)); assertThat(hit.getMatchedQueriesAndScores(), hasKey("prefix")); assertThat(hit.getMatchedQueryScore("prefix"), equalTo(1f)); @@ -259,7 +259,7 @@ public void testFuzzyQuerySupportsName() { assertHitCount(response, 1L); for (SearchHit hit : response.getHits()) { - if (hit.getId().equals("1")) { + if ("1".equals(hit.getId())) { assertThat(hit.getMatchedQueriesAndScores().size(), equalTo(1)); assertThat(hit.getMatchedQueriesAndScores(), hasKey("fuzzy")); assertThat(hit.getMatchedQueryScore("fuzzy"), greaterThan(0f)); @@ -281,7 +281,7 @@ public void testWildcardQuerySupportsName() { assertHitCount(response, 1L); for (SearchHit hit : response.getHits()) { - if (hit.getId().equals("1")) { + if ("1".equals(hit.getId())) { assertThat(hit.getMatchedQueriesAndScores().size(), equalTo(1)); assertThat(hit.getMatchedQueriesAndScores(), hasKey("wildcard")); assertThat(hit.getMatchedQueryScore("wildcard"), equalTo(1f)); @@ -305,7 +305,7 @@ public void testSpanFirstQuerySupportsName() { assertHitCount(response, 1L); for (SearchHit hit : response.getHits()) { - if (hit.getId().equals("1")) { + if ("1".equals(hit.getId())) { assertThat(hit.getMatchedQueriesAndScores().size(), equalTo(1)); assertThat(hit.getMatchedQueriesAndScores(), hasKey("span")); assertThat(hit.getMatchedQueryScore("span"), greaterThan(0f)); @@ -340,11 +340,11 @@ public void testMatchedWithShould() throws Exception { response -> { assertHitCount(response, 2L); for (SearchHit hit : response.getHits()) { - if (hit.getId().equals("1")) { + if ("1".equals(hit.getId())) { assertThat(hit.getMatchedQueriesAndScores().size(), equalTo(1)); assertThat(hit.getMatchedQueriesAndScores(), hasKey("dolor")); assertThat(hit.getMatchedQueryScore("dolor"), greaterThan(0f)); - } else if (hit.getId().equals("2")) { + } else if ("2".equals(hit.getId())) { assertThat(hit.getMatchedQueriesAndScores().size(), equalTo(1)); assertThat(hit.getMatchedQueriesAndScores(), hasKey("elit")); assertThat(hit.getMatchedQueryScore("elit"), greaterThan(0f)); diff --git a/server/src/internalClusterTest/java/org/elasticsearch/search/functionscore/ExplainableScriptIT.java b/server/src/internalClusterTest/java/org/elasticsearch/search/functionscore/ExplainableScriptIT.java index ee60888d7a0a8..12eceb5fbe95d 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/search/functionscore/ExplainableScriptIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/search/functionscore/ExplainableScriptIT.java @@ -65,7 +65,7 @@ public String getType() { @Override public T compile(String scriptName, String scriptSource, ScriptContext context, Map params) { - assert scriptSource.equals("explainable_script"); + assert "explainable_script".equals(scriptSource); assert context == ScoreScript.CONTEXT; ScoreScript.Factory factory = (params1, lookup) -> new ScoreScript.LeafFactory() { @Override diff --git a/server/src/internalClusterTest/java/org/elasticsearch/search/morelikethis/MoreLikeThisIT.java b/server/src/internalClusterTest/java/org/elasticsearch/search/morelikethis/MoreLikeThisIT.java index d79bb903bdb6a..768a7c29ce319 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/search/morelikethis/MoreLikeThisIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/search/morelikethis/MoreLikeThisIT.java @@ -632,7 +632,7 @@ public void testMinimumShouldMatch() throws ExecutionException, InterruptedExcep logger.info("Testing with minimum_should_match = {}", minimumShouldMatch); final int finalI = i; assertNoFailuresAndResponse(prepareSearch("test").setQuery(mltQuery), response -> { - if (minimumShouldMatch.equals("0%")) { + if ("0%".equals(minimumShouldMatch)) { assertHitCount(response, 10); } else { assertHitCount(response, 11 - finalI); diff --git a/server/src/internalClusterTest/java/org/elasticsearch/search/sort/FieldSortIT.java b/server/src/internalClusterTest/java/org/elasticsearch/search/sort/FieldSortIT.java index 2cd68398e211f..0340f4b07cc2b 100644 --- a/server/src/internalClusterTest/java/org/elasticsearch/search/sort/FieldSortIT.java +++ b/server/src/internalClusterTest/java/org/elasticsearch/search/sort/FieldSortIT.java @@ -954,7 +954,7 @@ public void testSortMissingDates() throws IOException { for (boolean withFormat : List.of(true, false)) { String format = null; if (withFormat) { - format = type.equals("date") ? "strict_date_optional_time" : "strict_date_optional_time_nanos"; + format = "date".equals(type) ? "strict_date_optional_time" : "strict_date_optional_time_nanos"; } assertResponse( diff --git a/server/src/main/java/org/elasticsearch/Version.java b/server/src/main/java/org/elasticsearch/Version.java index 5dd9a3a055043..769d801a9c42a 100644 --- a/server/src/main/java/org/elasticsearch/Version.java +++ b/server/src/main/java/org/elasticsearch/Version.java @@ -170,7 +170,7 @@ public class Version implements VersionId, ToXContentFragment { for (final Field declaredField : Version.class.getFields()) { if (declaredField.getType().equals(Version.class)) { final String fieldName = declaredField.getName(); - if (fieldName.equals("CURRENT") || fieldName.equals("V_EMPTY")) { + if ("CURRENT".equals(fieldName) || "V_EMPTY".equals(fieldName)) { continue; } assert fieldName.matches("V_\\d+_\\d+_\\d+") : "expected Version field [" + fieldName + "] to match V_\\d+_\\d+_\\d+"; diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/repositories/put/PutRepositoryRequest.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/repositories/put/PutRepositoryRequest.java index 4402519c4eacd..f0a30fd015ca6 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/repositories/put/PutRepositoryRequest.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/repositories/put/PutRepositoryRequest.java @@ -187,9 +187,9 @@ public boolean verify() { public PutRepositoryRequest source(Map repositoryDefinition) { for (Map.Entry entry : repositoryDefinition.entrySet()) { String name = entry.getKey(); - if (name.equals("type")) { + if ("type".equals(name)) { type(entry.getValue().toString()); - } else if (name.equals("settings")) { + } else if ("settings".equals(name)) { if ((entry.getValue() instanceof Map) == false) { throw new IllegalArgumentException("Malformed settings section, should include an inner object"); } diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/restore/RestoreSnapshotRequest.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/restore/RestoreSnapshotRequest.java index 8d025653d47fe..ee9806b05452c 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/restore/RestoreSnapshotRequest.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/restore/RestoreSnapshotRequest.java @@ -517,7 +517,7 @@ public RestoreSnapshotRequest featureStates(List featureStates) { public RestoreSnapshotRequest source(Map source) { for (Map.Entry entry : source.entrySet()) { String name = entry.getKey(); - if (name.equals("indices")) { + if ("indices".equals(name)) { if (entry.getValue() instanceof String) { indices(Strings.splitStringByCommaToArray((String) entry.getValue())); } else if (entry.getValue() instanceof ArrayList) { @@ -525,36 +525,36 @@ public RestoreSnapshotRequest source(Map source) { } else { throw new IllegalArgumentException("malformed indices section, should be an array of strings"); } - } else if (name.equals("feature_states")) { + } else if ("feature_states".equals(name)) { if (entry.getValue() instanceof List) { featureStates((List) entry.getValue()); } else { throw new IllegalArgumentException("malformed feature_states section, should be an array of strings"); } - } else if (name.equals("partial")) { + } else if ("partial".equals(name)) { partial(nodeBooleanValue(entry.getValue(), "partial")); - } else if (name.equals("include_global_state")) { + } else if ("include_global_state".equals(name)) { includeGlobalState = nodeBooleanValue(entry.getValue(), "include_global_state"); - } else if (name.equals("include_aliases")) { + } else if ("include_aliases".equals(name)) { includeAliases = nodeBooleanValue(entry.getValue(), "include_aliases"); - } else if (name.equals("rename_pattern")) { + } else if ("rename_pattern".equals(name)) { if (entry.getValue() instanceof String) { renamePattern((String) entry.getValue()); } else { throw new IllegalArgumentException("malformed rename_pattern"); } - } else if (name.equals("rename_replacement")) { + } else if ("rename_replacement".equals(name)) { if (entry.getValue() instanceof String) { renameReplacement((String) entry.getValue()); } else { throw new IllegalArgumentException("malformed rename_replacement"); } - } else if (name.equals("index_settings")) { + } else if ("index_settings".equals(name)) { if ((entry.getValue() instanceof Map) == false) { throw new IllegalArgumentException("malformed index_settings section"); } indexSettings((Map) entry.getValue()); - } else if (name.equals("ignore_index_settings")) { + } else if ("ignore_index_settings".equals(name)) { if (entry.getValue() instanceof String) { ignoreIndexSettings(Strings.splitStringByCommaToArray((String) entry.getValue())); } else if (entry.getValue() instanceof List) { diff --git a/server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/status/SnapshotStats.java b/server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/status/SnapshotStats.java index 4fe0c48831dd5..7cf711235a7ee 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/status/SnapshotStats.java +++ b/server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/status/SnapshotStats.java @@ -211,16 +211,16 @@ public static SnapshotStats fromXContent(XContentParser parser) throws IOExcepti XContentParserUtils.ensureExpectedToken(XContentParser.Token.FIELD_NAME, token, parser); String currentName = parser.currentName(); token = parser.nextToken(); - if (currentName.equals(Fields.INCREMENTAL)) { + if (Fields.INCREMENTAL.equals(currentName)) { XContentParserUtils.ensureExpectedToken(XContentParser.Token.START_OBJECT, token, parser); while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { XContentParserUtils.ensureExpectedToken(XContentParser.Token.FIELD_NAME, token, parser); String innerName = parser.currentName(); token = parser.nextToken(); - if (innerName.equals(Fields.FILE_COUNT)) { + if (Fields.FILE_COUNT.equals(innerName)) { XContentParserUtils.ensureExpectedToken(XContentParser.Token.VALUE_NUMBER, token, parser); incrementalFileCount = parser.intValue(); - } else if (innerName.equals(Fields.SIZE_IN_BYTES)) { + } else if (Fields.SIZE_IN_BYTES.equals(innerName)) { XContentParserUtils.ensureExpectedToken(XContentParser.Token.VALUE_NUMBER, token, parser); incrementalSize = parser.longValue(); } else { @@ -230,16 +230,16 @@ public static SnapshotStats fromXContent(XContentParser parser) throws IOExcepti } } } - } else if (currentName.equals(Fields.PROCESSED)) { + } else if (Fields.PROCESSED.equals(currentName)) { XContentParserUtils.ensureExpectedToken(XContentParser.Token.START_OBJECT, token, parser); while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { XContentParserUtils.ensureExpectedToken(XContentParser.Token.FIELD_NAME, token, parser); String innerName = parser.currentName(); token = parser.nextToken(); - if (innerName.equals(Fields.FILE_COUNT)) { + if (Fields.FILE_COUNT.equals(innerName)) { XContentParserUtils.ensureExpectedToken(XContentParser.Token.VALUE_NUMBER, token, parser); processedFileCount = parser.intValue(); - } else if (innerName.equals(Fields.SIZE_IN_BYTES)) { + } else if (Fields.SIZE_IN_BYTES.equals(innerName)) { XContentParserUtils.ensureExpectedToken(XContentParser.Token.VALUE_NUMBER, token, parser); processedSize = parser.longValue(); } else { @@ -249,16 +249,16 @@ public static SnapshotStats fromXContent(XContentParser parser) throws IOExcepti } } } - } else if (currentName.equals(Fields.TOTAL)) { + } else if (Fields.TOTAL.equals(currentName)) { XContentParserUtils.ensureExpectedToken(XContentParser.Token.START_OBJECT, token, parser); while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { XContentParserUtils.ensureExpectedToken(XContentParser.Token.FIELD_NAME, token, parser); String innerName = parser.currentName(); token = parser.nextToken(); - if (innerName.equals(Fields.FILE_COUNT)) { + if (Fields.FILE_COUNT.equals(innerName)) { XContentParserUtils.ensureExpectedToken(XContentParser.Token.VALUE_NUMBER, token, parser); totalFileCount = parser.intValue(); - } else if (innerName.equals(Fields.SIZE_IN_BYTES)) { + } else if (Fields.SIZE_IN_BYTES.equals(innerName)) { XContentParserUtils.ensureExpectedToken(XContentParser.Token.VALUE_NUMBER, token, parser); totalSize = parser.longValue(); } else { @@ -268,10 +268,10 @@ public static SnapshotStats fromXContent(XContentParser parser) throws IOExcepti } } } - } else if (currentName.equals(Fields.START_TIME_IN_MILLIS)) { + } else if (Fields.START_TIME_IN_MILLIS.equals(currentName)) { XContentParserUtils.ensureExpectedToken(XContentParser.Token.VALUE_NUMBER, token, parser); startTime = parser.longValue(); - } else if (currentName.equals(Fields.TIME_IN_MILLIS)) { + } else if (Fields.TIME_IN_MILLIS.equals(currentName)) { XContentParserUtils.ensureExpectedToken(XContentParser.Token.VALUE_NUMBER, token, parser); time = parser.longValue(); } else { diff --git a/server/src/main/java/org/elasticsearch/action/admin/indices/rollover/MetadataRolloverService.java b/server/src/main/java/org/elasticsearch/action/admin/indices/rollover/MetadataRolloverService.java index 1ba249aff8538..1e50f06309022 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/indices/rollover/MetadataRolloverService.java +++ b/server/src/main/java/org/elasticsearch/action/admin/indices/rollover/MetadataRolloverService.java @@ -530,7 +530,7 @@ static void validate(Metadata metadata, String rolloverTarget, String newIndexNa } if ((request.settings().equals(Settings.EMPTY) == false) || (request.aliases().size() > 0) - || (request.mappings().equals("{}") == false)) { + || ("{}".equals(request.mappings()) == false)) { throw new IllegalArgumentException( "aliases, mappings, and index settings may not be specified when rolling over a data stream" ); diff --git a/server/src/main/java/org/elasticsearch/action/admin/indices/template/put/PutIndexTemplateRequest.java b/server/src/main/java/org/elasticsearch/action/admin/indices/template/put/PutIndexTemplateRequest.java index 10c9a5e7205b0..69e9dfb4ca50e 100644 --- a/server/src/main/java/org/elasticsearch/action/admin/indices/template/put/PutIndexTemplateRequest.java +++ b/server/src/main/java/org/elasticsearch/action/admin/indices/template/put/PutIndexTemplateRequest.java @@ -298,7 +298,7 @@ public PutIndexTemplateRequest source(Map templateSource) { Map source = templateSource; for (Map.Entry entry : source.entrySet()) { String name = entry.getKey(); - if (name.equals("index_patterns")) { + if ("index_patterns".equals(name)) { if (entry.getValue() instanceof String) { patterns(Collections.singletonList((String) entry.getValue())); } else if (entry.getValue() instanceof List) { @@ -307,19 +307,19 @@ public PutIndexTemplateRequest source(Map templateSource) { } else { throw new IllegalArgumentException("Malformed [index_patterns] value, should be a string or a list of strings"); } - } else if (name.equals("order")) { + } else if ("order".equals(name)) { order(XContentMapValues.nodeIntegerValue(entry.getValue(), order())); } else if ("version".equals(name)) { if ((entry.getValue() instanceof Integer) == false) { throw new IllegalArgumentException("Malformed [version] value, should be an integer"); } version((Integer) entry.getValue()); - } else if (name.equals("settings")) { + } else if ("settings".equals(name)) { if ((entry.getValue() instanceof Map) == false) { throw new IllegalArgumentException("Malformed [settings] section, should include an inner object"); } settings((Map) entry.getValue()); - } else if (name.equals("mappings")) { + } else if ("mappings".equals(name)) { Map mappings = (Map) entry.getValue(); for (Map.Entry entry1 : mappings.entrySet()) { if ((entry1.getValue() instanceof Map) == false) { @@ -331,7 +331,7 @@ public PutIndexTemplateRequest source(Map templateSource) { } mapping((Map) entry1.getValue()); } - } else if (name.equals("aliases")) { + } else if ("aliases".equals(name)) { aliases((Map) entry.getValue()); } else { throw new ElasticsearchParseException("unknown key [{}] in the template ", name); diff --git a/server/src/main/java/org/elasticsearch/action/index/IndexRequest.java b/server/src/main/java/org/elasticsearch/action/index/IndexRequest.java index 8b5e077fd85b8..703412a82a977 100644 --- a/server/src/main/java/org/elasticsearch/action/index/IndexRequest.java +++ b/server/src/main/java/org/elasticsearch/action/index/IndexRequest.java @@ -530,9 +530,9 @@ public IndexRequest opType(OpType opType) { */ public IndexRequest opType(String opType) { String op = opType.toLowerCase(Locale.ROOT); - if (op.equals("create")) { + if ("create".equals(op)) { opType(OpType.CREATE); - } else if (op.equals("index")) { + } else if ("index".equals(op)) { opType(OpType.INDEX); } else { throw new IllegalArgumentException("opType must be 'create' or 'index', found: [" + opType + "]"); 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 34f0ce1a2fe2e..96f7c6b36188e 100644 --- a/server/src/main/java/org/elasticsearch/action/support/ActiveShardCount.java +++ b/server/src/main/java/org/elasticsearch/action/support/ActiveShardCount.java @@ -89,7 +89,7 @@ public static ActiveShardCount readFrom(final StreamInput in) throws IOException public static ActiveShardCount parseString(final String str) { if (str == null) { return ActiveShardCount.DEFAULT; - } else if (str.equals("all")) { + } else if ("all".equals(str)) { return ActiveShardCount.ALL; } else { int val; diff --git a/server/src/main/java/org/elasticsearch/action/termvectors/TermVectorsFields.java b/server/src/main/java/org/elasticsearch/action/termvectors/TermVectorsFields.java index 805bd055c97d7..ca0f27c0e7592 100644 --- a/server/src/main/java/org/elasticsearch/action/termvectors/TermVectorsFields.java +++ b/server/src/main/java/org/elasticsearch/action/termvectors/TermVectorsFields.java @@ -125,7 +125,7 @@ public TermVectorsFields(BytesReference headerRef, BytesReference termVectors) t try (StreamInput header = headerRef.streamInput()) { // here we read the header to fill the field offset map String headerString = header.readString(); - assert headerString.equals("TV"); + assert "TV".equals(headerString); int version = header.readInt(); assert version == -1; hasTermStatistic = header.readBoolean(); diff --git a/server/src/main/java/org/elasticsearch/cluster/coordination/ElasticsearchNodeCommand.java b/server/src/main/java/org/elasticsearch/cluster/coordination/ElasticsearchNodeCommand.java index 82abf4b4c7d5d..84391460e8cfc 100644 --- a/server/src/main/java/org/elasticsearch/cluster/coordination/ElasticsearchNodeCommand.java +++ b/server/src/main/java/org/elasticsearch/cluster/coordination/ElasticsearchNodeCommand.java @@ -151,7 +151,7 @@ protected void processDataPaths(Terminal terminal, OptionSet options, Environmen protected static void confirm(Terminal terminal, String msg) { terminal.println(msg); String text = terminal.readText("Confirm [y/N] "); - if (text.equalsIgnoreCase("y") == false) { + if ("y".equalsIgnoreCase(text) == false) { throw new ElasticsearchException(ABORTED_BY_USER_MSG); } } diff --git a/server/src/main/java/org/elasticsearch/cluster/health/ClusterHealthStatus.java b/server/src/main/java/org/elasticsearch/cluster/health/ClusterHealthStatus.java index d025ddab26af6..1cb5a21f98203 100644 --- a/server/src/main/java/org/elasticsearch/cluster/health/ClusterHealthStatus.java +++ b/server/src/main/java/org/elasticsearch/cluster/health/ClusterHealthStatus.java @@ -50,11 +50,11 @@ public static ClusterHealthStatus readFrom(StreamInput in) throws IOException { } public static ClusterHealthStatus fromString(String status) { - if (status.equalsIgnoreCase("green")) { + if ("green".equalsIgnoreCase(status)) { return GREEN; - } else if (status.equalsIgnoreCase("yellow")) { + } else if ("yellow".equalsIgnoreCase(status)) { return YELLOW; - } else if (status.equalsIgnoreCase("red")) { + } else if ("red".equalsIgnoreCase(status)) { return RED; } else { throw new IllegalArgumentException("unknown cluster health status [" + status + "]"); diff --git a/server/src/main/java/org/elasticsearch/cluster/metadata/AutoExpandReplicas.java b/server/src/main/java/org/elasticsearch/cluster/metadata/AutoExpandReplicas.java index fe6efda67df29..d9807694dd5ed 100644 --- a/server/src/main/java/org/elasticsearch/cluster/metadata/AutoExpandReplicas.java +++ b/server/src/main/java/org/elasticsearch/cluster/metadata/AutoExpandReplicas.java @@ -64,7 +64,7 @@ private static AutoExpandReplicas parse(String value) { ); } String sMax = value.substring(dash + 1); - if (sMax.equals(ALL_NODES_VALUE)) { + if (ALL_NODES_VALUE.equals(sMax)) { max = Integer.MAX_VALUE; } else { try { diff --git a/server/src/main/java/org/elasticsearch/cluster/metadata/MappingMetadata.java b/server/src/main/java/org/elasticsearch/cluster/metadata/MappingMetadata.java index b629ab5d5f710..4506c3963e304 100644 --- a/server/src/main/java/org/elasticsearch/cluster/metadata/MappingMetadata.java +++ b/server/src/main/java/org/elasticsearch/cluster/metadata/MappingMetadata.java @@ -97,7 +97,7 @@ private boolean routingRequired(Map withoutType) { for (Map.Entry entry : routingNode.entrySet()) { String fieldName = entry.getKey(); Object fieldNode = entry.getValue(); - if (fieldName.equals("required")) { + if ("required".equals(fieldName)) { try { required = nodeBooleanValue(fieldNode); } catch (IllegalArgumentException ex) { diff --git a/server/src/main/java/org/elasticsearch/cluster/metadata/Metadata.java b/server/src/main/java/org/elasticsearch/cluster/metadata/Metadata.java index 64b234c8f5d2b..a1177de2f0c0a 100644 --- a/server/src/main/java/org/elasticsearch/cluster/metadata/Metadata.java +++ b/server/src/main/java/org/elasticsearch/cluster/metadata/Metadata.java @@ -2244,7 +2244,7 @@ public Builder clusterUUIDCommitted(boolean clusterUUIDCommitted) { } public Builder generateClusterUuidIfNeeded() { - if (clusterUUID.equals(UNKNOWN_CLUSTER_UUID)) { + if (UNKNOWN_CLUSTER_UUID.equals(clusterUUID)) { clusterUUID = UUIDs.randomBase64UUID(); } return this; diff --git a/server/src/main/java/org/elasticsearch/cluster/metadata/MetadataCreateIndexService.java b/server/src/main/java/org/elasticsearch/cluster/metadata/MetadataCreateIndexService.java index da24f0b9d0dc5..8e84b17027c67 100644 --- a/server/src/main/java/org/elasticsearch/cluster/metadata/MetadataCreateIndexService.java +++ b/server/src/main/java/org/elasticsearch/cluster/metadata/MetadataCreateIndexService.java @@ -235,7 +235,7 @@ public static void validateIndexOrAliasName(String index, BiFunction MAX_INDEX_NAME_BYTES) { throw exceptionCtor.apply(index, "index name is too long, (" + byteCount + " > " + MAX_INDEX_NAME_BYTES + ")"); } - if (index.equals(".") || index.equals("..")) { + if (".".equals(index) || "..".equals(index)) { throw exceptionCtor.apply(index, "must not be '.' or '..'"); } } @@ -1572,7 +1572,7 @@ static void prepareResizeIndexSettings( final Predicate sourceSettingsPredicate = (s) -> (s.startsWith("index.similarity.") || s.startsWith("index.analysis.") || s.startsWith("index.sort.") - || s.equals("index.soft_deletes.enabled")) && indexSettingsBuilder.keys().contains(s) == false; + || "index.soft_deletes.enabled".equals(s)) && indexSettingsBuilder.keys().contains(s) == false; builder.put(sourceMetadata.getSettings().filter(sourceSettingsPredicate)); } diff --git a/server/src/main/java/org/elasticsearch/cluster/routing/UnassignedInfo.java b/server/src/main/java/org/elasticsearch/cluster/routing/UnassignedInfo.java index 59b344080c054..1f66e9f0deb6e 100644 --- a/server/src/main/java/org/elasticsearch/cluster/routing/UnassignedInfo.java +++ b/server/src/main/java/org/elasticsearch/cluster/routing/UnassignedInfo.java @@ -57,7 +57,7 @@ public final class UnassignedInfo implements ToXContentFragment, Writeable { public static final Setting INDEX_DELAYED_NODE_LEFT_TIMEOUT_SETTING = Setting.timeSetting( "index.unassigned.node_left.delayed_timeout", - settings -> EXISTING_SHARDS_ALLOCATOR_SETTING.get(settings).equals("stateless") + settings -> "stateless".equals(EXISTING_SHARDS_ALLOCATOR_SETTING.get(settings)) ? TimeValue.timeValueSeconds(10) : TimeValue.timeValueMinutes(1), TimeValue.timeValueMillis(0), diff --git a/server/src/main/java/org/elasticsearch/cluster/routing/allocation/DataTier.java b/server/src/main/java/org/elasticsearch/cluster/routing/allocation/DataTier.java index ebdf6e4b3d8ee..4c9c396e10179 100644 --- a/server/src/main/java/org/elasticsearch/cluster/routing/allocation/DataTier.java +++ b/server/src/main/java/org/elasticsearch/cluster/routing/allocation/DataTier.java @@ -80,7 +80,7 @@ public class DataTier { static { for (String tier : ALL_DATA_TIERS) { - assert tier.equals(DATA_FROZEN) || tier.contains(DATA_FROZEN) == false + assert DATA_FROZEN.equals(tier) || tier.contains(DATA_FROZEN) == false : "can't have two tier names containing [" + DATA_FROZEN + "] because it would break setting validation optimizations" @@ -100,7 +100,7 @@ public class DataTier { final Map tmpSettings = new HashMap<>(); for (int i = 0, ordered_frozen_to_hot_tiersSize = ORDERED_FROZEN_TO_HOT_TIERS.size(); i < ordered_frozen_to_hot_tiersSize; i++) { String tier = ORDERED_FROZEN_TO_HOT_TIERS.get(i); - if (tier.equals(DATA_FROZEN)) { + if (DATA_FROZEN.equals(tier)) { tmp.put(tier, DATA_FROZEN); tmpSettings.put(DATA_FROZEN, Settings.builder().put(DataTier.TIER_PREFERENCE, DATA_FROZEN).build()); } else { @@ -192,10 +192,10 @@ public static List parseTierList(String tiers) { * If invalid tier names are passed the result is non-deterministic. */ public static int compare(String tier1, String tier2) { - if (tier1.equals(DATA_CONTENT)) { + if (DATA_CONTENT.equals(tier1)) { tier1 = DATA_HOT; } - if (tier2.equals(DATA_CONTENT)) { + if (DATA_CONTENT.equals(tier2)) { tier2 = DATA_HOT; } int indexOfTier1 = ORDERED_FROZEN_TO_HOT_TIERS.indexOf(tier1); diff --git a/server/src/main/java/org/elasticsearch/cluster/routing/allocation/command/AllocationCommands.java b/server/src/main/java/org/elasticsearch/cluster/routing/allocation/command/AllocationCommands.java index 208be8adbe18f..be2691a7f229e 100644 --- a/server/src/main/java/org/elasticsearch/cluster/routing/allocation/command/AllocationCommands.java +++ b/server/src/main/java/org/elasticsearch/cluster/routing/allocation/command/AllocationCommands.java @@ -123,7 +123,7 @@ public static AllocationCommands fromXContent(XContentParser parser) throws IOEx throw new ElasticsearchParseException("No commands"); } if (token == XContentParser.Token.FIELD_NAME) { - if (parser.currentName().equals("commands") == false) { + if ("commands".equals(parser.currentName()) == false) { throw new ElasticsearchParseException("expected field name to be named [commands], got [{}] instead", parser.currentName()); } token = parser.nextToken(); diff --git a/server/src/main/java/org/elasticsearch/cluster/service/ClusterApplierService.java b/server/src/main/java/org/elasticsearch/cluster/service/ClusterApplierService.java index 4230838a97592..a72861781a644 100644 --- a/server/src/main/java/org/elasticsearch/cluster/service/ClusterApplierService.java +++ b/server/src/main/java/org/elasticsearch/cluster/service/ClusterApplierService.java @@ -370,7 +370,7 @@ private static boolean assertNotCalledFromClusterStateApplier() { if (className.equals(ClusterStateObserver.class.getName())) { // it's legitimate to start a ClusterStateObserver on the applier thread, since this class handles lost updates return true; - } else if (className.equals(ClusterApplierService.class.getName()) && methodName.equals("callClusterStateAppliers")) { + } else if (className.equals(ClusterApplierService.class.getName()) && "callClusterStateAppliers".equals(methodName)) { throw new AssertionError(""" On the cluster applier thread you must use ClusterChangedEvent#state() and ClusterChangedEvent#previousState() \ instead of ClusterApplierService#state(). It is almost certainly a bug to read the latest-applied state from \ diff --git a/server/src/main/java/org/elasticsearch/common/geo/GenericPointParser.java b/server/src/main/java/org/elasticsearch/common/geo/GenericPointParser.java index 681849a9851ec..041adceb821e3 100644 --- a/server/src/main/java/org/elasticsearch/common/geo/GenericPointParser.java +++ b/server/src/main/java/org/elasticsearch/common/geo/GenericPointParser.java @@ -186,7 +186,7 @@ public T parsePoint(XContentParser parser, boolean ignoreZValue, Function() { @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { - if (file.getFileName().toString().equals("log4j2.properties")) { + if ("log4j2.properties".equals(file.getFileName().toString())) { configurations.add((PropertiesConfiguration) factory.getConfiguration(context, file.toString(), file.toUri())); } return FileVisitResult.CONTINUE; diff --git a/server/src/main/java/org/elasticsearch/common/lucene/LoggerInfoStream.java b/server/src/main/java/org/elasticsearch/common/lucene/LoggerInfoStream.java index c4a467bd41a68..7744fadc09106 100644 --- a/server/src/main/java/org/elasticsearch/common/lucene/LoggerInfoStream.java +++ b/server/src/main/java/org/elasticsearch/common/lucene/LoggerInfoStream.java @@ -36,7 +36,7 @@ public void message(String component, String message) { public boolean isEnabled(String component) { // TP is a special "test point" component; we don't want // to log it: - return getLogger(component).isTraceEnabled() && component.equals("TP") == false; + return getLogger(component).isTraceEnabled() && "TP".equals(component) == false; } private Logger getLogger(String component) { diff --git a/server/src/main/java/org/elasticsearch/common/network/NetworkUtils.java b/server/src/main/java/org/elasticsearch/common/network/NetworkUtils.java index f7cfff8402304..98262a0bee9e9 100644 --- a/server/src/main/java/org/elasticsearch/common/network/NetworkUtils.java +++ b/server/src/main/java/org/elasticsearch/common/network/NetworkUtils.java @@ -158,7 +158,7 @@ private static boolean isUp(final NetworkInterface intf) throws IOException { return intf.isUp(); } catch (final SocketException e) { // virtual ethernet devices come and go, we will treat such a device that disappeared as not being up - if (intf.getName().startsWith("veth") && e.getMessage().equals("No such device (getFlags() failed)")) { + if (intf.getName().startsWith("veth") && "No such device (getFlags() failed)".equals(e.getMessage())) { return false; } throw new IOException("failed to check if interface [" + intf.getName() + "] is up", e); diff --git a/server/src/main/java/org/elasticsearch/common/regex/Regex.java b/server/src/main/java/org/elasticsearch/common/regex/Regex.java index 1b60a5dce9038..ff15a25302878 100644 --- a/server/src/main/java/org/elasticsearch/common/regex/Regex.java +++ b/server/src/main/java/org/elasticsearch/common/regex/Regex.java @@ -40,7 +40,7 @@ public static boolean isSimpleMatchPattern(String str) { } public static boolean isMatchAllPattern(String str) { - return str.equals("*"); + return "*".equals(str); } public static boolean isSuffixMatchPattern(String str) { diff --git a/server/src/main/java/org/elasticsearch/common/settings/SettingsModule.java b/server/src/main/java/org/elasticsearch/common/settings/SettingsModule.java index 2f2e4367e1930..d16727a558f18 100644 --- a/server/src/main/java/org/elasticsearch/common/settings/SettingsModule.java +++ b/server/src/main/java/org/elasticsearch/common/settings/SettingsModule.java @@ -195,7 +195,7 @@ private void registerSetting(Setting setting) { // module private static boolean isS3InsecureCredentials(Setting setting) { final String settingKey = setting.getKey(); - return settingKey.equals("access_key") || settingKey.equals("secret_key"); + return "access_key".equals(settingKey) || "secret_key".equals(settingKey); } /** diff --git a/server/src/main/java/org/elasticsearch/common/unit/Fuzziness.java b/server/src/main/java/org/elasticsearch/common/unit/Fuzziness.java index 735a750a69c69..9b3efbd0aabc7 100644 --- a/server/src/main/java/org/elasticsearch/common/unit/Fuzziness.java +++ b/server/src/main/java/org/elasticsearch/common/unit/Fuzziness.java @@ -78,7 +78,7 @@ public static Fuzziness fromString(String fuzzinessString) { } String upperCase = fuzzinessString.toUpperCase(Locale.ROOT); // check if it is one of the "AUTO" variants - if (upperCase.equals("AUTO")) { + if ("AUTO".equals(upperCase)) { return Fuzziness.AUTO; } else if (upperCase.startsWith("AUTO:")) { return parseCustomAuto(upperCase); @@ -199,7 +199,7 @@ public String asString() { } private boolean isAutoWithCustomValues() { - return fuzziness.equals("AUTO") && (lowDistance != DEFAULT_LOW_DISTANCE || highDistance != DEFAULT_HIGH_DISTANCE); + return "AUTO".equals(fuzziness) && (lowDistance != DEFAULT_LOW_DISTANCE || highDistance != DEFAULT_HIGH_DISTANCE); } @Override diff --git a/server/src/main/java/org/elasticsearch/common/util/concurrent/ThreadContext.java b/server/src/main/java/org/elasticsearch/common/util/concurrent/ThreadContext.java index 7bfba1ebdb176..4fed5b332d373 100644 --- a/server/src/main/java/org/elasticsearch/common/util/concurrent/ThreadContext.java +++ b/server/src/main/java/org/elasticsearch/common/util/concurrent/ThreadContext.java @@ -668,9 +668,9 @@ public void sanitizeHeaders() { newRequestHeaders.entrySet() .removeIf( - entry -> entry.getKey().equalsIgnoreCase("authorization") - || entry.getKey().equalsIgnoreCase("es-secondary-authorization") - || entry.getKey().equalsIgnoreCase("ES-Client-Authentication") + entry -> "authorization".equalsIgnoreCase(entry.getKey()) + || "es-secondary-authorization".equalsIgnoreCase(entry.getKey()) + || "ES-Client-Authentication".equalsIgnoreCase(entry.getKey()) ); final ThreadContextStruct newContext = new ThreadContextStruct( @@ -807,7 +807,7 @@ private ThreadContextStruct putResponse( assert value != null; long newWarningHeaderSize = warningHeadersSize; // check if we can add another warning header - if max size within limits - if (key.equals("Warning") && (maxWarningHeaderSize != -1)) { // if size is NOT unbounded, check its limits + if ("Warning".equals(key) && (maxWarningHeaderSize != -1)) { // if size is NOT unbounded, check its limits if (warningHeadersSize > maxWarningHeaderSize) { // if max size has already been reached before logger.warn( "Dropping a warning header, as their total size reached the maximum allowed of [" diff --git a/server/src/main/java/org/elasticsearch/http/CorsHandler.java b/server/src/main/java/org/elasticsearch/http/CorsHandler.java index 100079cfa38f6..e880fd51a45fd 100644 --- a/server/src/main/java/org/elasticsearch/http/CorsHandler.java +++ b/server/src/main/java/org/elasticsearch/http/CorsHandler.java @@ -421,7 +421,7 @@ public static Config buildConfig(Settings settings) { final CorsHandler.Config.Builder builder; if (Strings.isNullOrEmpty(origin)) { builder = CorsHandler.Config.Builder.forOrigins(); - } else if (origin.equals(CorsHandler.ANY_ORIGIN)) { + } else if (CorsHandler.ANY_ORIGIN.equals(origin)) { builder = CorsHandler.Config.Builder.forAnyOrigin(); } else { try { diff --git a/server/src/main/java/org/elasticsearch/index/IndexSettings.java b/server/src/main/java/org/elasticsearch/index/IndexSettings.java index 83a6d9319c75a..98b8e58ffd151 100644 --- a/server/src/main/java/org/elasticsearch/index/IndexSettings.java +++ b/server/src/main/java/org/elasticsearch/index/IndexSettings.java @@ -286,7 +286,7 @@ public final class IndexSettings { public static TimeValue STATELESS_DEFAULT_REFRESH_INTERVAL = TimeValue.timeValueSeconds(15); // TODO: this value is still not final public static TimeValue STATELESS_MIN_NON_FAST_REFRESH_INTERVAL = TimeValue.timeValueSeconds(5); public static final Setting INDEX_REFRESH_INTERVAL_SETTING = Setting.timeSetting("index.refresh_interval", (settings) -> { - if (EXISTING_SHARDS_ALLOCATOR_SETTING.get(settings).equals("stateless") && INDEX_FAST_REFRESH_SETTING.get(settings) == false) { + if ("stateless".equals(EXISTING_SHARDS_ALLOCATOR_SETTING.get(settings)) && INDEX_FAST_REFRESH_SETTING.get(settings) == false) { return STATELESS_DEFAULT_REFRESH_INTERVAL; } return DEFAULT_REFRESH_INTERVAL; @@ -302,7 +302,7 @@ public void validate(final TimeValue value, final Map, Object> settin final Boolean fastRefresh = (Boolean) settings.get(INDEX_FAST_REFRESH_SETTING); final IndexVersion indexVersion = (IndexVersion) settings.get(SETTING_INDEX_VERSION_CREATED); - if (existingShardsAllocator.equals("stateless") + if ("stateless".equals(existingShardsAllocator) && fastRefresh == false && value.compareTo(TimeValue.ZERO) > 0 && value.compareTo(STATELESS_MIN_NON_FAST_REFRESH_INTERVAL) < 0 diff --git a/server/src/main/java/org/elasticsearch/index/MergePolicyConfig.java b/server/src/main/java/org/elasticsearch/index/MergePolicyConfig.java index e6b2a861458d0..0868bc274ee97 100644 --- a/server/src/main/java/org/elasticsearch/index/MergePolicyConfig.java +++ b/server/src/main/java/org/elasticsearch/index/MergePolicyConfig.java @@ -393,9 +393,9 @@ MergePolicy getMergePolicy(boolean isTimeBasedIndex) { private static CompoundFileThreshold parseCompoundFormat(String noCFSRatio) { noCFSRatio = noCFSRatio.trim(); - if (noCFSRatio.equalsIgnoreCase("true")) { + if ("true".equalsIgnoreCase(noCFSRatio)) { return new CompoundFileThreshold(1.0d); - } else if (noCFSRatio.equalsIgnoreCase("false")) { + } else if ("false".equalsIgnoreCase(noCFSRatio)) { return new CompoundFileThreshold(0.0d); } else { try { diff --git a/server/src/main/java/org/elasticsearch/index/analysis/AnalysisRegistry.java b/server/src/main/java/org/elasticsearch/index/analysis/AnalysisRegistry.java index 90a983be610ea..bdb437c5fd37f 100644 --- a/server/src/main/java/org/elasticsearch/index/analysis/AnalysisRegistry.java +++ b/server/src/main/java/org/elasticsearch/index/analysis/AnalysisRegistry.java @@ -479,7 +479,7 @@ private Map buildMapping( component + " [" + name + "] " + "must specify either an analyzer type, or a tokenizer" ); } - } else if (typeName.equals("custom")) { + } else if ("custom".equals(typeName)) { factory = (T) new CustomAnalyzerProvider(settings, name, currentSettings); } if (factory != null) { @@ -487,7 +487,7 @@ private Map buildMapping( continue; } } else if (component == Component.NORMALIZER) { - if (typeName == null || typeName.equals("custom")) { + if (typeName == null || "custom".equals(typeName)) { T factory = (T) new CustomNormalizerProvider(settings, name, currentSettings); factories.put(name, factory); continue; diff --git a/server/src/main/java/org/elasticsearch/index/mapper/MapperService.java b/server/src/main/java/org/elasticsearch/index/mapper/MapperService.java index cbf2dd872da2f..33de0b269233b 100644 --- a/server/src/main/java/org/elasticsearch/index/mapper/MapperService.java +++ b/server/src/main/java/org/elasticsearch/index/mapper/MapperService.java @@ -468,7 +468,7 @@ public Object merge(String parent, String key, Object oldValue, Object newValue) // field mapping entries of Map type (like "fields" and "meta") are handled above and should never reach here return null; } else { - if (key.equals("required")) { + if ("required".equals(key)) { // we look for explicit `_routing.required` settings because we use them to detect contradictions of this setting // that comes from mappings with such that comes from the optional `data_stream` configuration of composable index // templates @@ -677,7 +677,7 @@ public static boolean isMetadataFieldStatic(String fieldName) { return true; } // if a node had Size Plugin installed, _size field should also be considered a meta-field - return fieldName.equals("_size"); + return "_size".equals(fieldName); } /** diff --git a/server/src/main/java/org/elasticsearch/index/mapper/ObjectMapper.java b/server/src/main/java/org/elasticsearch/index/mapper/ObjectMapper.java index d67763879433f..3c3fe0114b669 100644 --- a/server/src/main/java/org/elasticsearch/index/mapper/ObjectMapper.java +++ b/server/src/main/java/org/elasticsearch/index/mapper/ObjectMapper.java @@ -222,21 +222,21 @@ protected static boolean parseObjectOrDocumentTypeProperties( MappingParserContext parserContext, ObjectMapper.Builder builder ) { - if (fieldName.equals("dynamic")) { + if ("dynamic".equals(fieldName)) { String value = fieldNode.toString(); - if (value.equalsIgnoreCase("strict")) { + if ("strict".equalsIgnoreCase(value)) { builder.dynamic(Dynamic.STRICT); - } else if (value.equalsIgnoreCase("runtime")) { + } else if ("runtime".equalsIgnoreCase(value)) { builder.dynamic(Dynamic.RUNTIME); } else { boolean dynamic = XContentMapValues.nodeBooleanValue(fieldNode, fieldName + ".dynamic"); builder.dynamic(dynamic ? Dynamic.TRUE : Dynamic.FALSE); } return true; - } else if (fieldName.equals("enabled")) { + } else if ("enabled".equals(fieldName)) { builder.enabled(XContentMapValues.nodeBooleanValue(fieldNode, fieldName + ".enabled")); return true; - } else if (fieldName.equals("properties")) { + } else if ("properties".equals(fieldName)) { if (fieldNode instanceof Collection && ((Collection) fieldNode).isEmpty()) { // nothing to do here, empty (to support "properties: []" case) } else if ((fieldNode instanceof Map) == false) { @@ -245,7 +245,7 @@ protected static boolean parseObjectOrDocumentTypeProperties( parseProperties(builder, (Map) fieldNode, parserContext); } return true; - } else if (fieldName.equals("include_in_all")) { + } else if ("include_in_all".equals(fieldName)) { deprecationLogger.warn( DeprecationCategory.MAPPINGS, "include_in_all", @@ -300,7 +300,7 @@ protected static void parseProperties( } } - if (objBuilder.subobjects.value() == false && type.equals(ObjectMapper.CONTENT_TYPE)) { + if (objBuilder.subobjects.value() == false && ObjectMapper.CONTENT_TYPE.equals(type)) { throw new MapperParsingException( "Tried to add subobject [" + fieldName diff --git a/server/src/main/java/org/elasticsearch/index/mapper/TypeParsers.java b/server/src/main/java/org/elasticsearch/index/mapper/TypeParsers.java index 84c2e11b1beaa..5e89f30b04cb2 100644 --- a/server/src/main/java/org/elasticsearch/index/mapper/TypeParsers.java +++ b/server/src/main/java/org/elasticsearch/index/mapper/TypeParsers.java @@ -93,7 +93,7 @@ public static boolean parseMultiField( String propName, Object propNode ) { - if (propName.equals("fields")) { + if ("fields".equals(propName)) { if (parserContext.isWithinMultiField()) { // For indices created prior to 8.0, we only emit a deprecation warning and do not fail type parsing. This is to // maintain the backwards-compatibility guarantee that we can always load indexes from the previous major version. diff --git a/server/src/main/java/org/elasticsearch/index/mapper/vectors/DenseVectorFieldMapper.java b/server/src/main/java/org/elasticsearch/index/mapper/vectors/DenseVectorFieldMapper.java index 6aaea1dd32285..e43da2d78f993 100644 --- a/server/src/main/java/org/elasticsearch/index/mapper/vectors/DenseVectorFieldMapper.java +++ b/server/src/main/java/org/elasticsearch/index/mapper/vectors/DenseVectorFieldMapper.java @@ -1069,7 +1069,7 @@ private static IndexOptions parseIndexOptions(String fieldName, Object propNode) throw new MapperParsingException("[index_options] requires field [type] to be configured"); } String type = XContentMapValues.nodeStringValue(typeNode); - if (type.equals("hnsw")) { + if ("hnsw".equals(type)) { return HnswIndexOptions.parseIndexOptions(fieldName, indexOptionsMap); } else { throw new MapperParsingException("Unknown vector index options type [" + type + "] for field [" + fieldName + "]"); diff --git a/server/src/main/java/org/elasticsearch/index/query/GeoDistanceQueryBuilder.java b/server/src/main/java/org/elasticsearch/index/query/GeoDistanceQueryBuilder.java index 763eb4fd5f3bf..46bff87c742d3 100644 --- a/server/src/main/java/org/elasticsearch/index/query/GeoDistanceQueryBuilder.java +++ b/server/src/main/java/org/elasticsearch/index/query/GeoDistanceQueryBuilder.java @@ -289,11 +289,11 @@ public static GeoDistanceQueryBuilder fromXContent(XContentParser parser) throws if (token == XContentParser.Token.FIELD_NAME) { currentName = parser.currentName(); } else if (token.isValue()) { - if (currentName.equals("lat")) { + if ("lat".equals(currentName)) { point.resetLat(parser.doubleValue()); - } else if (currentName.equals("lon")) { + } else if ("lon".equals(currentName)) { point.resetLon(parser.doubleValue()); - } else if (currentName.equals("geohash")) { + } else if ("geohash".equals(currentName)) { point.resetFromGeoHash(parser.text()); } else { throw new ParsingException( diff --git a/server/src/main/java/org/elasticsearch/index/query/MoreLikeThisQueryBuilder.java b/server/src/main/java/org/elasticsearch/index/query/MoreLikeThisQueryBuilder.java index acf4893de5280..99f96bbd86298 100644 --- a/server/src/main/java/org/elasticsearch/index/query/MoreLikeThisQueryBuilder.java +++ b/server/src/main/java/org/elasticsearch/index/query/MoreLikeThisQueryBuilder.java @@ -979,7 +979,7 @@ protected Query doToQuery(SearchExecutionContext context) throws IOException { List moreLikeFields = new ArrayList<>(); if (useDefaultField) { moreLikeFields = context.defaultFields(); - if (moreLikeFields.size() == 1 && moreLikeFields.get(0).equals("*") && (likeTexts.length > 0 || unlikeTexts.length > 0)) { + if (moreLikeFields.size() == 1 && "*".equals(moreLikeFields.get(0)) && (likeTexts.length > 0 || unlikeTexts.length > 0)) { throw new IllegalArgumentException( "[more_like_this] query cannot infer the field to analyze the free text, " + "you should update the [index.query.default_field] index setting to a field that exists in the mapping or " diff --git a/server/src/main/java/org/elasticsearch/index/reindex/BulkByScrollTask.java b/server/src/main/java/org/elasticsearch/index/reindex/BulkByScrollTask.java index 150948b4e5822..364f9ab3043f9 100644 --- a/server/src/main/java/org/elasticsearch/index/reindex/BulkByScrollTask.java +++ b/server/src/main/java/org/elasticsearch/index/reindex/BulkByScrollTask.java @@ -639,13 +639,13 @@ public static Status innerFromXContent(XContentParser parser) throws IOException if (token == Token.FIELD_NAME) { fieldName = parser.currentName(); } else if (token == Token.START_OBJECT) { - if (fieldName.equals(Status.RETRIES_FIELD)) { + if (Status.RETRIES_FIELD.equals(fieldName)) { builder.setRetries(Status.RETRIES_PARSER.parse(parser, null)); } else { parser.skipChildren(); } } else if (token == Token.START_ARRAY) { - if (fieldName.equals(Status.SLICES_FIELD)) { + if (Status.SLICES_FIELD.equals(fieldName)) { while ((token = parser.nextToken()) != Token.END_ARRAY) { builder.addToSliceStatuses(StatusOrException.fromXContent(parser)); } diff --git a/server/src/main/java/org/elasticsearch/index/search/QueryStringQueryParser.java b/server/src/main/java/org/elasticsearch/index/search/QueryStringQueryParser.java index 89fc7be8d0fd2..752370e97131b 100644 --- a/server/src/main/java/org/elasticsearch/index/search/QueryStringQueryParser.java +++ b/server/src/main/java/org/elasticsearch/index/search/QueryStringQueryParser.java @@ -660,7 +660,7 @@ private Query existsQuery(String fieldName) { @Override protected Query getWildcardQuery(String field, String termStr) throws ParseException { String actualField = field != null ? field : this.field; - if (termStr.equals("*") && actualField != null) { + if ("*".equals(termStr) && actualField != null) { if (Regex.isMatchAllPattern(actualField)) { return newMatchAllDocsQuery(); } diff --git a/server/src/main/java/org/elasticsearch/index/search/stats/ShardSearchStats.java b/server/src/main/java/org/elasticsearch/index/search/stats/ShardSearchStats.java index 0fa9100a9a0b0..9497a8a19a67d 100644 --- a/server/src/main/java/org/elasticsearch/index/search/stats/ShardSearchStats.java +++ b/server/src/main/java/org/elasticsearch/index/search/stats/ShardSearchStats.java @@ -39,7 +39,7 @@ public SearchStats stats(String... groups) { Map groupsSt = null; if (CollectionUtils.isEmpty(groups) == false) { groupsSt = Maps.newMapWithExpectedSize(groupsStats.size()); - if (groups.length == 1 && groups[0].equals("_all")) { + if (groups.length == 1 && "_all".equals(groups[0])) { for (Map.Entry entry : groupsStats.entrySet()) { groupsSt.put(entry.getKey(), entry.getValue().stats()); } diff --git a/server/src/main/java/org/elasticsearch/index/seqno/SequenceNumbers.java b/server/src/main/java/org/elasticsearch/index/seqno/SequenceNumbers.java index 0cd451f6be2cf..7eeb9758a5572 100644 --- a/server/src/main/java/org/elasticsearch/index/seqno/SequenceNumbers.java +++ b/server/src/main/java/org/elasticsearch/index/seqno/SequenceNumbers.java @@ -43,10 +43,10 @@ public static CommitInfo loadSeqNoInfoFromLuceneCommit(final Iterable entry : commitData) { final String key = entry.getKey(); - if (key.equals(SequenceNumbers.LOCAL_CHECKPOINT_KEY)) { + if (SequenceNumbers.LOCAL_CHECKPOINT_KEY.equals(key)) { assert localCheckpoint == NO_OPS_PERFORMED : localCheckpoint; localCheckpoint = Long.parseLong(entry.getValue()); - } else if (key.equals(SequenceNumbers.MAX_SEQ_NO)) { + } else if (SequenceNumbers.MAX_SEQ_NO.equals(key)) { assert maxSeqNo == NO_OPS_PERFORMED : maxSeqNo; maxSeqNo = Long.parseLong(entry.getValue()); } diff --git a/server/src/main/java/org/elasticsearch/index/translog/Translog.java b/server/src/main/java/org/elasticsearch/index/translog/Translog.java index 38f44f453bedc..cdce5d0d1380a 100644 --- a/server/src/main/java/org/elasticsearch/index/translog/Translog.java +++ b/server/src/main/java/org/elasticsearch/index/translog/Translog.java @@ -377,7 +377,7 @@ private static boolean calledFromOutsideOrViaTragedyClose() { }). // find all inner callers including Translog subclasses toList(); // the list of inner callers should be either empty or should contain closeOnTragicEvent method - return frames.isEmpty() || frames.stream().anyMatch(f -> f.getMethodName().equals("closeOnTragicEvent")); + return frames.isEmpty() || frames.stream().anyMatch(f -> "closeOnTragicEvent".equals(f.getMethodName())); } @Override diff --git a/server/src/main/java/org/elasticsearch/indices/SystemIndexDescriptor.java b/server/src/main/java/org/elasticsearch/indices/SystemIndexDescriptor.java index 9f814183c825b..e7e5941e9bed3 100644 --- a/server/src/main/java/org/elasticsearch/indices/SystemIndexDescriptor.java +++ b/server/src/main/java/org/elasticsearch/indices/SystemIndexDescriptor.java @@ -920,7 +920,7 @@ static boolean findDynamicMapping(Map map) { for (Map.Entry entry : map.entrySet()) { final String key = entry.getKey(); final Object value = entry.getValue(); - if (key.equals("dynamic") && (value instanceof Boolean) && ((Boolean) value)) { + if ("dynamic".equals(key) && (value instanceof Boolean) && ((Boolean) value)) { return true; } diff --git a/server/src/main/java/org/elasticsearch/indices/breaker/HierarchyCircuitBreakerService.java b/server/src/main/java/org/elasticsearch/indices/breaker/HierarchyCircuitBreakerService.java index 9e995c084a555..ab701bd871216 100644 --- a/server/src/main/java/org/elasticsearch/indices/breaker/HierarchyCircuitBreakerService.java +++ b/server/src/main/java/org/elasticsearch/indices/breaker/HierarchyCircuitBreakerService.java @@ -506,7 +506,7 @@ private CircuitBreaker validateAndCreateBreaker(LongCounter trippedCountMeter, B static OverLimitStrategy createOverLimitStrategy(boolean trackRealMemoryUsage) { JvmInfo jvmInfo = JvmInfo.jvmInfo(); - if (trackRealMemoryUsage && jvmInfo.useG1GC().equals("true") + if (trackRealMemoryUsage && "true".equals(jvmInfo.useG1GC()) // messing with GC is "dangerous" so we apply an escape hatch. Not intended to be used. && Booleans.parseBoolean(System.getProperty("es.real_memory_circuit_breaker.g1_over_limit_strategy.enabled"), true)) { TimeValue lockTimeout = TimeValue.timeValueMillis( diff --git a/server/src/main/java/org/elasticsearch/monitor/os/OsProbe.java b/server/src/main/java/org/elasticsearch/monitor/os/OsProbe.java index 64fcc2f8ff684..41b2273804c0c 100644 --- a/server/src/main/java/org/elasticsearch/monitor/os/OsProbe.java +++ b/server/src/main/java/org/elasticsearch/monitor/os/OsProbe.java @@ -882,7 +882,7 @@ long getTotalMemFromProcMeminfo() throws IOException { } boolean isDebian8() throws IOException { - return Constants.LINUX && getPrettyName().equals("Debian GNU/Linux 8 (jessie)"); + return Constants.LINUX && "Debian GNU/Linux 8 (jessie)".equals(getPrettyName()); } OsStats.Cgroup getCgroup(boolean isLinux) { diff --git a/server/src/main/java/org/elasticsearch/plugins/ModuleSupport.java b/server/src/main/java/org/elasticsearch/plugins/ModuleSupport.java index e5f0004431b0e..f138f30323366 100644 --- a/server/src/main/java/org/elasticsearch/plugins/ModuleSupport.java +++ b/server/src/main/java/org/elasticsearch/plugins/ModuleSupport.java @@ -188,7 +188,7 @@ static Optional toPackageName(String name, String separator) { assert name.endsWith(separator) == false; int index = name.lastIndexOf(separator); if (index == -1) { - if (name.endsWith(".class") && name.equals(MODULE_INFO) == false) { + if (name.endsWith(".class") && MODULE_INFO.equals(name) == false) { String msg = name + " found in top-level directory (unnamed package not allowed in module)"; throw new InvalidModuleDescriptorException(msg); } diff --git a/server/src/main/java/org/elasticsearch/plugins/Platforms.java b/server/src/main/java/org/elasticsearch/plugins/Platforms.java index a4ab2c161c9f2..5cb42c1852497 100644 --- a/server/src/main/java/org/elasticsearch/plugins/Platforms.java +++ b/server/src/main/java/org/elasticsearch/plugins/Platforms.java @@ -53,7 +53,7 @@ public static String platformName(final String osName, final String osArch) { final String normalizedOs; if (lowerCaseOs.startsWith("windows")) { normalizedOs = "windows"; - } else if (lowerCaseOs.equals("mac os x")) { + } else if ("mac os x".equals(lowerCaseOs)) { normalizedOs = "darwin"; } else { normalizedOs = lowerCaseOs; @@ -61,9 +61,9 @@ public static String platformName(final String osName, final String osArch) { final String lowerCaseArch = osArch.toLowerCase(Locale.ROOT); final String normalizedArch; - if (lowerCaseArch.equals("amd64")) { + if ("amd64".equals(lowerCaseArch)) { normalizedArch = "x86_64"; - } else if (lowerCaseArch.equals("i386")) { + } else if ("i386".equals(lowerCaseArch)) { normalizedArch = "x86"; } else { normalizedArch = lowerCaseArch; diff --git a/server/src/main/java/org/elasticsearch/plugins/PluginsUtils.java b/server/src/main/java/org/elasticsearch/plugins/PluginsUtils.java index 0533f535a19f1..8161536a5841e 100644 --- a/server/src/main/java/org/elasticsearch/plugins/PluginsUtils.java +++ b/server/src/main/java/org/elasticsearch/plugins/PluginsUtils.java @@ -62,7 +62,7 @@ public static List findPluginDirs(final Path rootPath) throws IOException final String filename = plugin.getFileName().toString(); if (FileSystemUtils.isDesktopServicesStore(plugin) || filename.startsWith(".removing-") - || filename.equals(".elasticsearch-plugins.yml.cache")) { + || ".elasticsearch-plugins.yml.cache".equals(filename)) { continue; } if (seen.add(filename) == false) { @@ -238,7 +238,7 @@ private static Set findBundles(final Path directory, String type) if (bundles.add(bundle) == false) { throw new IllegalStateException("duplicate " + type + ": " + bundle.plugin); } - if (type.equals("module") && bundle.plugin.getName().startsWith("test-") && Build.current().isSnapshot() == false) { + if ("module".equals(type) && bundle.plugin.getName().startsWith("test-") && Build.current().isSnapshot() == false) { throw new IllegalStateException("external test module [" + plugin.getFileName() + "] found in non-snapshot build"); } } diff --git a/server/src/main/java/org/elasticsearch/repositories/RepositoryData.java b/server/src/main/java/org/elasticsearch/repositories/RepositoryData.java index 17ac4ef38f1b6..421e9b9dc1b2f 100644 --- a/server/src/main/java/org/elasticsearch/repositories/RepositoryData.java +++ b/server/src/main/java/org/elasticsearch/repositories/RepositoryData.java @@ -175,7 +175,7 @@ private RepositoryData( this.shardGenerations = shardGenerations; this.indexMetaDataGenerations = indexMetaDataGenerations; this.clusterUUID = Objects.requireNonNull(clusterUUID); - assert uuid.equals(MISSING_UUID) == clusterUUID.equals(MISSING_UUID) + assert MISSING_UUID.equals(uuid) == MISSING_UUID.equals(clusterUUID) : "Either repository- and cluster UUID must both be missing" + " or neither of them must be missing but saw [" + uuid @@ -498,9 +498,9 @@ public RepositoryData withoutUUIDs() { } public RepositoryData withClusterUuid(String clusterUUID) { - assert clusterUUID.equals(MISSING_UUID) == false; + assert MISSING_UUID.equals(clusterUUID) == false; return new RepositoryData( - uuid.equals(MISSING_UUID) ? UUIDs.randomBase64UUID() : uuid, + MISSING_UUID.equals(uuid) ? UUIDs.randomBase64UUID() : uuid, genId, snapshotIds, snapshotsDetails, @@ -725,7 +725,7 @@ public XContentBuilder snapshotsToXContent(final XContentBuilder builder, final } if (shouldWriteUUIDS) { - if (uuid.equals(MISSING_UUID)) { + if (MISSING_UUID.equals(uuid)) { if (permitMissingUuid == false) { assert false : "missing uuid"; throw new IllegalStateException("missing uuid"); @@ -733,7 +733,7 @@ public XContentBuilder snapshotsToXContent(final XContentBuilder builder, final } else { builder.field(UUID, uuid); } - if (clusterUUID.equals(MISSING_UUID)) { + if (MISSING_UUID.equals(clusterUUID)) { if (permitMissingUuid == false) { assert false : "missing clusterUUID"; throw new IllegalStateException("missing clusterUUID"); @@ -742,12 +742,12 @@ public XContentBuilder snapshotsToXContent(final XContentBuilder builder, final builder.field(CLUSTER_UUID, clusterUUID); } } else { - if (uuid.equals(MISSING_UUID) == false) { + if (MISSING_UUID.equals(uuid) == false) { final IllegalStateException e = new IllegalStateException("lost uuid + [" + uuid + "]"); assert false : e; throw e; } - if (clusterUUID.equals(MISSING_UUID) == false) { + if (MISSING_UUID.equals(clusterUUID) == false) { final IllegalStateException e = new IllegalStateException("lost clusterUUID + [" + uuid + "]"); assert false : e; throw e; @@ -900,12 +900,12 @@ public static RepositoryData snapshotsFromXContent(XContentParser parser, long g case UUID -> { XContentParserUtils.ensureExpectedToken(XContentParser.Token.VALUE_STRING, parser.nextToken(), parser); uuid = parser.text(); - assert uuid.equals(MISSING_UUID) == false; + assert MISSING_UUID.equals(uuid) == false; } case CLUSTER_UUID -> { XContentParserUtils.ensureExpectedToken(XContentParser.Token.VALUE_STRING, parser.nextToken(), parser); clusterUUID = parser.text(); - assert clusterUUID.equals(MISSING_UUID) == false; + assert MISSING_UUID.equals(clusterUUID) == false; } default -> XContentParserUtils.throwUnknownField(field, parser); } diff --git a/server/src/main/java/org/elasticsearch/rest/action/cat/RestTable.java b/server/src/main/java/org/elasticsearch/rest/action/cat/RestTable.java index 8ce001f7a1a77..7ea39c3e9e793 100644 --- a/server/src/main/java/org/elasticsearch/rest/action/cat/RestTable.java +++ b/server/src/main/java/org/elasticsearch/rest/action/cat/RestTable.java @@ -329,7 +329,7 @@ public static void pad(Table.Cell cell, int width, RestRequest request, Writer o if (textAlign == null) { textAlign = "left"; } - if (leftOver > 0 && textAlign.equals("right")) { + if (leftOver > 0 && "right".equals(textAlign)) { for (byte i = 0; i < leftOver; i++) { out.append(" "); } diff --git a/server/src/main/java/org/elasticsearch/script/ScriptContextInfo.java b/server/src/main/java/org/elasticsearch/script/ScriptContextInfo.java index 59454dd8af7d1..4cd0de4850791 100644 --- a/server/src/main/java/org/elasticsearch/script/ScriptContextInfo.java +++ b/server/src/main/java/org/elasticsearch/script/ScriptContextInfo.java @@ -396,7 +396,7 @@ static Set gettersFromContext(Class clazz) { for (java.lang.reflect.Method m : clazz.getMethods()) { if (m.isDefault() == false && m.getName().startsWith("get") - && m.getName().equals("getClass") == false + && "getClass".equals(m.getName()) == false && Modifier.isStatic(m.getModifiers()) == false && m.getParameters().length == 0) { getters.add(new ScriptMethodInfo(m.getName(), m.getReturnType().getTypeName(), new ArrayList<>())); diff --git a/server/src/main/java/org/elasticsearch/script/ScriptService.java b/server/src/main/java/org/elasticsearch/script/ScriptService.java index 43c7cbb78f869..6c6ea99b13d3c 100644 --- a/server/src/main/java/org/elasticsearch/script/ScriptService.java +++ b/server/src/main/java/org/elasticsearch/script/ScriptService.java @@ -88,7 +88,7 @@ public class ScriptService implements Closeable, ClusterStateApplier, ScriptComp public static final Setting SCRIPT_GENERAL_MAX_COMPILATIONS_RATE_SETTING = new Setting<>( "script.max_compilations_rate", "150/5m", - (String value) -> value.equals(USE_CONTEXT_RATE_KEY) ? USE_CONTEXT_RATE_VALUE : new ScriptCache.CompilationRate(value), + (String value) -> USE_CONTEXT_RATE_KEY.equals(value) ? USE_CONTEXT_RATE_VALUE : new ScriptCache.CompilationRate(value), Property.Dynamic, Property.NodeScope ); @@ -143,7 +143,7 @@ public class ScriptService implements Closeable, ClusterStateApplier, ScriptComp key -> new Setting( key, "75/5m", - (String value) -> value.equals(UNLIMITED_COMPILATION_RATE_KEY) + (String value) -> UNLIMITED_COMPILATION_RATE_KEY.equals(value) ? ScriptCache.UNLIMITED_COMPILATION_RATE : new ScriptCache.CompilationRate(value), Property.NodeScope, 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 7b7c41165b51e..d0297bf71672c 100644 --- a/server/src/main/java/org/elasticsearch/search/aggregations/AggregatorFactories.java +++ b/server/src/main/java/org/elasticsearch/search/aggregations/AggregatorFactories.java @@ -459,14 +459,14 @@ private static void resolvePipelineAggregatorOrder( for (String bucketsPath : bucketsPaths) { List bucketsPathElements = AggregationPath.parse(bucketsPath).getPathElements(); String firstAggName = bucketsPathElements.get(0).name(); - if (bucketsPath.equals("_count") || bucketsPath.equals("_key")) { + if ("_count".equals(bucketsPath) || "_key".equals(bucketsPath)) { 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(); - if ((i == bucketsPathElements.size() - 1) && (aggName.equalsIgnoreCase("_key") || aggName.equals("_count"))) { + if ((i == bucketsPathElements.size() - 1) && ("_key".equalsIgnoreCase(aggName) || "_count".equals(aggName))) { break; } else { // Check the non-pipeline sub-aggregator diff --git a/server/src/main/java/org/elasticsearch/search/aggregations/InternalMultiBucketAggregation.java b/server/src/main/java/org/elasticsearch/search/aggregations/InternalMultiBucketAggregation.java index ff1ca58d351e3..fb2963ef445e9 100644 --- a/server/src/main/java/org/elasticsearch/search/aggregations/InternalMultiBucketAggregation.java +++ b/server/src/main/java/org/elasticsearch/search/aggregations/InternalMultiBucketAggregation.java @@ -90,7 +90,7 @@ public Object getProperty(List path) { static Object resolvePropertyFromPath(List path, List buckets, String name) { String aggName = path.get(0); - if (aggName.equals("_bucket_count")) { + if ("_bucket_count".equals(aggName)) { return buckets.size(); } @@ -213,12 +213,12 @@ public Object getProperty(String containingAggName, List path) { } Aggregations aggregations = getAggregations(); String aggName = path.get(0); - if (aggName.equals("_count")) { + if ("_count".equals(aggName)) { if (path.size() > 1) { throw new InvalidAggregationPathException("_count must be the last element in the path"); } return getDocCount(); - } else if (aggName.equals("_key")) { + } else if ("_key".equals(aggName)) { if (path.size() > 1) { throw new InvalidAggregationPathException("_key must be the last element in the path"); } diff --git a/server/src/main/java/org/elasticsearch/search/aggregations/bucket/InternalSingleBucketAggregation.java b/server/src/main/java/org/elasticsearch/search/aggregations/bucket/InternalSingleBucketAggregation.java index ddb4b3db403e3..1158b9cd30f49 100644 --- a/server/src/main/java/org/elasticsearch/search/aggregations/bucket/InternalSingleBucketAggregation.java +++ b/server/src/main/java/org/elasticsearch/search/aggregations/bucket/InternalSingleBucketAggregation.java @@ -133,7 +133,7 @@ public Object getProperty(List path) { return this; } else { String aggName = path.get(0); - if (aggName.equals("_count")) { + if ("_count".equals(aggName)) { if (path.size() > 1) { throw new IllegalArgumentException("_count must be the last element in the path"); } diff --git a/server/src/main/java/org/elasticsearch/search/fetch/subphase/FieldAndFormat.java b/server/src/main/java/org/elasticsearch/search/fetch/subphase/FieldAndFormat.java index 82b16a9aad03a..a610739a23725 100644 --- a/server/src/main/java/org/elasticsearch/search/fetch/subphase/FieldAndFormat.java +++ b/server/src/main/java/org/elasticsearch/search/fetch/subphase/FieldAndFormat.java @@ -68,7 +68,7 @@ private static CheckedFunction ignoreUseFie return null; } else { String text = p.text(); - if (text.equals(USE_DEFAULT_FORMAT)) { + if (USE_DEFAULT_FORMAT.equals(text)) { DEPRECATION_LOGGER.compatibleCritical( "explicit_default_format", "[" diff --git a/server/src/main/java/org/elasticsearch/search/fetch/subphase/highlight/DefaultHighlighter.java b/server/src/main/java/org/elasticsearch/search/fetch/subphase/highlight/DefaultHighlighter.java index e77436ba61423..63905ea02ef7a 100644 --- a/server/src/main/java/org/elasticsearch/search/fetch/subphase/highlight/DefaultHighlighter.java +++ b/server/src/main/java/org/elasticsearch/search/fetch/subphase/highlight/DefaultHighlighter.java @@ -107,7 +107,7 @@ public HighlightField highlight(FieldHighlightContext fieldContext) throws IOExc CustomUnifiedHighlighter buildHighlighter(FieldHighlightContext fieldContext) { IndexSettings indexSettings = fieldContext.context.getSearchExecutionContext().getIndexSettings(); - Encoder encoder = fieldContext.field.fieldOptions().encoder().equals("html") + Encoder encoder = "html".equals(fieldContext.field.fieldOptions().encoder()) ? HighlightUtils.Encoders.HTML : HighlightUtils.Encoders.DEFAULT; diff --git a/server/src/main/java/org/elasticsearch/search/fetch/subphase/highlight/FastVectorHighlighter.java b/server/src/main/java/org/elasticsearch/search/fetch/subphase/highlight/FastVectorHighlighter.java index 8417c9d747981..b084839385e3f 100644 --- a/server/src/main/java/org/elasticsearch/search/fetch/subphase/highlight/FastVectorHighlighter.java +++ b/server/src/main/java/org/elasticsearch/search/fetch/subphase/highlight/FastVectorHighlighter.java @@ -78,7 +78,7 @@ public HighlightField highlight(FieldHighlightContext fieldContext) throws IOExc ); } - Encoder encoder = field.fieldOptions().encoder().equals("html") ? HighlightUtils.Encoders.HTML : HighlightUtils.Encoders.DEFAULT; + Encoder encoder = "html".equals(field.fieldOptions().encoder()) ? HighlightUtils.Encoders.HTML : HighlightUtils.Encoders.DEFAULT; if (fieldContext.cache.containsKey(CACHE_KEY) == false) { fieldContext.cache.put(CACHE_KEY, new HighlighterEntry()); diff --git a/server/src/main/java/org/elasticsearch/search/fetch/subphase/highlight/HighlightPhase.java b/server/src/main/java/org/elasticsearch/search/fetch/subphase/highlight/HighlightPhase.java index aa6e909ff0cae..f6553f5116d42 100644 --- a/server/src/main/java/org/elasticsearch/search/fetch/subphase/highlight/HighlightPhase.java +++ b/server/src/main/java/org/elasticsearch/search/fetch/subphase/highlight/HighlightPhase.java @@ -124,7 +124,7 @@ private FieldContext contextBuilders( if (fieldNameContainsWildcards) { if (fieldType.typeName().equals(TextFieldMapper.CONTENT_TYPE) == false && fieldType.typeName().equals(KeywordFieldMapper.CONTENT_TYPE) == false - && fieldType.typeName().equals("match_only_text") == false) { + && "match_only_text".equals(fieldType.typeName()) == false) { continue; } if (highlighter.canHighlight(fieldType) == false) { diff --git a/server/src/main/java/org/elasticsearch/search/fetch/subphase/highlight/PlainHighlighter.java b/server/src/main/java/org/elasticsearch/search/fetch/subphase/highlight/PlainHighlighter.java index e7fa0e67cb453..27e612175221b 100644 --- a/server/src/main/java/org/elasticsearch/search/fetch/subphase/highlight/PlainHighlighter.java +++ b/server/src/main/java/org/elasticsearch/search/fetch/subphase/highlight/PlainHighlighter.java @@ -60,7 +60,7 @@ public HighlightField highlight(FieldHighlightContext fieldContext) throws IOExc FetchSubPhase.HitContext hitContext = fieldContext.hitContext; MappedFieldType fieldType = fieldContext.fieldType; - Encoder encoder = field.fieldOptions().encoder().equals("html") ? HighlightUtils.Encoders.HTML : HighlightUtils.Encoders.DEFAULT; + Encoder encoder = "html".equals(field.fieldOptions().encoder()) ? HighlightUtils.Encoders.HTML : HighlightUtils.Encoders.DEFAULT; if (fieldContext.cache.containsKey(CACHE_KEY) == false) { fieldContext.cache.put(CACHE_KEY, new HashMap<>()); diff --git a/server/src/main/java/org/elasticsearch/search/profile/query/InternalProfileCollector.java b/server/src/main/java/org/elasticsearch/search/profile/query/InternalProfileCollector.java index 65a8463afab73..0245053ab29b9 100644 --- a/server/src/main/java/org/elasticsearch/search/profile/query/InternalProfileCollector.java +++ b/server/src/main/java/org/elasticsearch/search/profile/query/InternalProfileCollector.java @@ -57,7 +57,7 @@ protected String deriveCollectorName(Collector c) { // MultiCollector which wraps multiple BucketCollectors is generated // via an anonymous class, so this corrects the lack of a name by // asking the enclosingClass - if (s.equals("")) { + if ("".equals(s)) { s = c.getClass().getEnclosingClass().getSimpleName(); } diff --git a/server/src/main/java/org/elasticsearch/search/suggest/completion/context/ContextMapping.java b/server/src/main/java/org/elasticsearch/search/suggest/completion/context/ContextMapping.java index d2edd460b926d..a1f84a4f29e96 100644 --- a/server/src/main/java/org/elasticsearch/search/suggest/completion/context/ContextMapping.java +++ b/server/src/main/java/org/elasticsearch/search/suggest/completion/context/ContextMapping.java @@ -47,9 +47,9 @@ public enum Type { GEO; public static Type fromString(String type) { - if (type.equalsIgnoreCase("category")) { + if ("category".equalsIgnoreCase(type)) { return CATEGORY; - } else if (type.equalsIgnoreCase("geo")) { + } else if ("geo".equalsIgnoreCase(type)) { return GEO; } else { throw new IllegalArgumentException("No context type for [" + type + "]"); diff --git a/server/src/main/java/org/elasticsearch/threadpool/ExecutorBuilder.java b/server/src/main/java/org/elasticsearch/threadpool/ExecutorBuilder.java index fd9b56d73518d..3047329b2e61c 100644 --- a/server/src/main/java/org/elasticsearch/threadpool/ExecutorBuilder.java +++ b/server/src/main/java/org/elasticsearch/threadpool/ExecutorBuilder.java @@ -37,7 +37,7 @@ protected static String settingsKey(final String prefix, final String key) { } protected static int applyHardSizeLimit(final Settings settings, final String name) { - if (name.equals("bulk") + if ("bulk".equals(name) || name.equals(ThreadPool.Names.WRITE) || name.equals(ThreadPool.Names.SYSTEM_WRITE) || name.equals(ThreadPool.Names.SYSTEM_CRITICAL_WRITE)) { diff --git a/server/src/main/java/org/elasticsearch/threadpool/ThreadPool.java b/server/src/main/java/org/elasticsearch/threadpool/ThreadPool.java index bfcd8c8a396f5..ffb66598e075e 100644 --- a/server/src/main/java/org/elasticsearch/threadpool/ThreadPool.java +++ b/server/src/main/java/org/elasticsearch/threadpool/ThreadPool.java @@ -307,7 +307,7 @@ public ThreadPool(final Settings settings, final ExecutorBuilder... customBui final List infos = executors.values() .stream() - .filter(holder -> holder.info.getName().equals("same") == false) + .filter(holder -> "same".equals(holder.info.getName()) == false) .map(holder -> holder.info) .toList(); this.threadPoolInfo = new ThreadPoolInfo(infos); @@ -992,8 +992,8 @@ public static boolean assertInSystemContext(ThreadPool threadPool) { public static boolean assertCurrentMethodIsNotCalledRecursively() { final StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); assert stackTraceElements.length >= 3 : stackTraceElements.length; - assert stackTraceElements[0].getMethodName().equals("getStackTrace") : stackTraceElements[0]; - assert stackTraceElements[1].getMethodName().equals("assertCurrentMethodIsNotCalledRecursively") : stackTraceElements[1]; + assert "getStackTrace".equals(stackTraceElements[0].getMethodName()) : stackTraceElements[0]; + assert "assertCurrentMethodIsNotCalledRecursively".equals(stackTraceElements[1].getMethodName()) : stackTraceElements[1]; final StackTraceElement testingMethod = stackTraceElements[2]; for (int i = 3; i < stackTraceElements.length; i++) { assert stackTraceElements[i].getClassName().equals(testingMethod.getClassName()) == false diff --git a/test/fixtures/gcs-fixture/src/main/java/fixture/gcs/GoogleCloudStorageHttpHandler.java b/test/fixtures/gcs-fixture/src/main/java/fixture/gcs/GoogleCloudStorageHttpHandler.java index 964cb178b386f..d56beb3847d05 100644 --- a/test/fixtures/gcs-fixture/src/main/java/fixture/gcs/GoogleCloudStorageHttpHandler.java +++ b/test/fixtures/gcs-fixture/src/main/java/fixture/gcs/GoogleCloudStorageHttpHandler.java @@ -77,7 +77,7 @@ public void handle(final HttpExchange exchange) throws IOException { try { // Request body is closed in the finally block final BytesReference requestBody = Streams.readFully(Streams.noCloseStream(exchange.getRequestBody())); - if (request.equals("GET /") && "Google".equals(exchange.getRequestHeaders().getFirst("Metadata-Flavor"))) { + if ("GET /".equals(request) && "Google".equals(exchange.getRequestHeaders().getFirst("Metadata-Flavor"))) { // the SDK checks this endpoint to determine if it's running within Google Compute Engine exchange.getResponseHeaders().add("Metadata-Flavor", "Google"); exchange.sendResponseHeaders(RestStatus.OK.getStatus(), 0); diff --git a/test/fixtures/s3-fixture/src/main/java/fixture/s3/S3HttpFixtureWithEC2.java b/test/fixtures/s3-fixture/src/main/java/fixture/s3/S3HttpFixtureWithEC2.java index 0d8cf9c3e4513..18dd890f4272a 100644 --- a/test/fixtures/s3-fixture/src/main/java/fixture/s3/S3HttpFixtureWithEC2.java +++ b/test/fixtures/s3-fixture/src/main/java/fixture/s3/S3HttpFixtureWithEC2.java @@ -41,7 +41,7 @@ protected HttpHandler createHandler() { final String path = exchange.getRequestURI().getPath(); // http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html if ("GET".equals(exchange.getRequestMethod()) && path.startsWith(EC2_PATH)) { - if (path.equals(EC2_PATH)) { + if (EC2_PATH.equals(path)) { final byte[] response = EC2_PROFILE.getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().add("Content-Type", "text/plain"); exchange.sendResponseHeaders(RestStatus.OK.getStatus(), response.length); diff --git a/test/fixtures/s3-fixture/src/main/java/fixture/s3/S3HttpHandler.java b/test/fixtures/s3-fixture/src/main/java/fixture/s3/S3HttpHandler.java index 09dfdc991b82c..a5efef0b91cf1 100644 --- a/test/fixtures/s3-fixture/src/main/java/fixture/s3/S3HttpHandler.java +++ b/test/fixtures/s3-fixture/src/main/java/fixture/s3/S3HttpHandler.java @@ -404,9 +404,9 @@ static List extractPartEtags(BytesReference completeMultipartUploadBody) for (int childIndex = 0; childIndex < childNodes.getLength(); childIndex++) { final var childNode = childNodes.item(childIndex); if (childNode.getNodeType() == ELEMENT_NODE) { - if (childNode.getNodeName().equals("ETag")) { + if ("ETag".equals(childNode.getNodeName())) { etag = childNode.getTextContent(); - } else if (childNode.getNodeName().equals("PartNumber")) { + } else if ("PartNumber".equals(childNode.getNodeName())) { partNumber = Integer.parseInt(childNode.getTextContent()) - 1; } } diff --git a/test/framework/src/main/java/org/elasticsearch/cluster/DiskUsageIntegTestCase.java b/test/framework/src/main/java/org/elasticsearch/cluster/DiskUsageIntegTestCase.java index 32e6602d73fc3..aacdc001bcbbe 100644 --- a/test/framework/src/main/java/org/elasticsearch/cluster/DiskUsageIntegTestCase.java +++ b/test/framework/src/main/java/org/elasticsearch/cluster/DiskUsageIntegTestCase.java @@ -149,7 +149,7 @@ public long getUnallocatedSpace() throws IOException { private static long getTotalFileSize(Path path) throws IOException { if (Files.isRegularFile(path)) { - if (path.getFileName().toString().equals("nodes") + if ("nodes".equals(path.getFileName().toString()) && Files.readString(path, StandardCharsets.UTF_8).contains("prevent a downgrade")) { return 0; } @@ -159,7 +159,7 @@ private static long getTotalFileSize(Path path) throws IOException { // probably removed (Windows sometimes throws AccessDeniedException after a file has been deleted) return 0L; } - } else if (path.getFileName().toString().equals("_state") || path.getFileName().toString().equals("translog")) { + } else if ("_state".equals(path.getFileName().toString()) || "translog".equals(path.getFileName().toString())) { // ignore metadata and translog, since the disk threshold decider only cares about the store size return 0L; } else { @@ -224,7 +224,7 @@ TestFileStore getTestFileStore(Path path) { // We check the total size available for translog in InternalEngine constructor and we allow that here, // expecting to match a unique root path. - assertTrue(path + " not tracked and not translog", path.getFileName().toString().equals("translog")); + assertTrue(path + " not tracked and not translog", "translog".equals(path.getFileName().toString())); final Set containingPaths = trackedPaths.keySet().stream().filter(path::startsWith).collect(Collectors.toSet()); assertThat(path + " not contained in a unique tracked path", containingPaths, hasSize(1)); return trackedPaths.get(containingPaths.iterator().next()); diff --git a/test/framework/src/main/java/org/elasticsearch/index/mapper/MapperScriptTestCase.java b/test/framework/src/main/java/org/elasticsearch/index/mapper/MapperScriptTestCase.java index 368de3e4d6e58..b896708f1d2bd 100644 --- a/test/framework/src/main/java/org/elasticsearch/index/mapper/MapperScriptTestCase.java +++ b/test/framework/src/main/java/org/elasticsearch/index/mapper/MapperScriptTestCase.java @@ -40,16 +40,16 @@ protected FactoryType script(String id) { @Override @SuppressWarnings("unchecked") protected T compileScript(Script script, ScriptContext context) { - if (script.getIdOrCode().equals("serializer_test")) { + if ("serializer_test".equals(script.getIdOrCode())) { return (T) serializableScript(); } - if (script.getIdOrCode().equals("throws")) { + if ("throws".equals(script.getIdOrCode())) { return (T) errorThrowingScript(); } - if (script.getIdOrCode().equals("single-valued")) { + if ("single-valued".equals(script.getIdOrCode())) { return (T) singleValueScript(); } - if (script.getIdOrCode().equals("multi-valued")) { + if ("multi-valued".equals(script.getIdOrCode())) { return (T) multipleValuesScript(); } return (T) script(script.getIdOrCode()); diff --git a/test/framework/src/main/java/org/elasticsearch/repositories/blobstore/ESBlobStoreRepositoryIntegTestCase.java b/test/framework/src/main/java/org/elasticsearch/repositories/blobstore/ESBlobStoreRepositoryIntegTestCase.java index 578a7898bcd1e..e1bea164187a8 100644 --- a/test/framework/src/main/java/org/elasticsearch/repositories/blobstore/ESBlobStoreRepositoryIntegTestCase.java +++ b/test/framework/src/main/java/org/elasticsearch/repositories/blobstore/ESBlobStoreRepositoryIntegTestCase.java @@ -487,7 +487,7 @@ public void testIndicesDeletedFromRepository() throws Exception { }); for (IndexId indexId : repositoryData.actionGet().getIndices().values()) { - if (indexId.getName().equals("test-idx-3")) { + if ("test-idx-3".equals(indexId.getName())) { assertFalse(indicesBlobContainer.get().blobExists(randomPurpose(), indexId.getId())); // deleted index } } diff --git a/x-pack/plugin/ccr/src/internalClusterTest/java/org/elasticsearch/xpack/ccr/CloseFollowerIndexIT.java b/x-pack/plugin/ccr/src/internalClusterTest/java/org/elasticsearch/xpack/ccr/CloseFollowerIndexIT.java index 8e597c3992528..7c079cfb95cf4 100644 --- a/x-pack/plugin/ccr/src/internalClusterTest/java/org/elasticsearch/xpack/ccr/CloseFollowerIndexIT.java +++ b/x-pack/plugin/ccr/src/internalClusterTest/java/org/elasticsearch/xpack/ccr/CloseFollowerIndexIT.java @@ -45,10 +45,10 @@ public void wrapUncaughtExceptionHandler() { AccessController.doPrivileged((PrivilegedAction) () -> { Thread.setDefaultUncaughtExceptionHandler((t, e) -> { if (t.getThreadGroup().getName().contains(getTestClass().getSimpleName()) - && t.getName().equals("elasticsearch-error-rethrower")) { + && "elasticsearch-error-rethrower".equals(t.getName())) { for (StackTraceElement element : e.getStackTrace()) { if (element.getClassName().equals(ReadOnlyEngine.class.getName())) { - if (element.getMethodName().equals("assertMaxSeqNoEqualsToGlobalCheckpoint")) { + if ("assertMaxSeqNoEqualsToGlobalCheckpoint".equals(element.getMethodName())) { logger.error("HACK: suppressing uncaught exception thrown from assertMaxSeqNoEqualsToGlobalCheckpoint", e); return; } diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/license/LicenseOverrides.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/license/LicenseOverrides.java index ba9829f333c93..1227de2b6ee78 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/license/LicenseOverrides.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/license/LicenseOverrides.java @@ -32,7 +32,7 @@ private LicenseOverrides() {} MessageDigests.sha256().digest("12345678-abcd-0000-0000-000000000000".getBytes(StandardCharsets.UTF_8)) ); - assert TEST_LICENSE_ID_HASH.equals("d180f3dedf21b96eea4021d373ab990cba53eeb6c44832261417e828fcb278f1"); + assert "d180f3dedf21b96eea4021d373ab990cba53eeb6c44832261417e828fcb278f1".equals(TEST_LICENSE_ID_HASH); ZonedDateTime EXPIRED = ZonedDateTime.ofStrict(LocalDateTime.of(1970, 1, 1, 0, 0, 42, 0), ZoneOffset.UTC, ZoneOffset.UTC); LICENSE_OVERRIDES = Map.ofEntries( diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/MlConfigVersion.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/MlConfigVersion.java index ffaa8489929ff..9a1d5db0cd75d 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/MlConfigVersion.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/MlConfigVersion.java @@ -316,7 +316,7 @@ public static MlConfigVersion fromString(String str) { // a result there may be DFA destination indices in the wild with metadata // containing 8.10.1, 8.10.2, 8.10.3 or 8.11.0. We can treat these as V_10 // for config version comparison purposes. - if (str.startsWith("8.10.") || str.equals("8.11.0")) { + if (str.startsWith("8.10.") || "8.11.0".equals(str)) { return V_10; } Matcher matcher = Pattern.compile("^(\\d+)\\.(\\d+)\\.(\\d+)(?:-\\w+)?$").matcher(str); diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/inference/trainedmodel/NerConfig.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/inference/trainedmodel/NerConfig.java index e7f3a66b6748f..16e51344c8dc2 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/inference/trainedmodel/NerConfig.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/inference/trainedmodel/NerConfig.java @@ -100,7 +100,7 @@ public NerConfig( badLabels ); } - if (this.classificationLabels.stream().noneMatch(l -> l.toUpperCase(Locale.ROOT).equals("O"))) { + if (this.classificationLabels.stream().noneMatch(l -> "O".equals(l.toUpperCase(Locale.ROOT)))) { throw ExceptionsHelper.badRequestException( "[{}] only allows IOB tokenization tagging for classification labels; missing outside label [O]", NAME diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/rollup/action/GetRollupCapsAction.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/rollup/action/GetRollupCapsAction.java index 200c984317d79..9d11916a50fad 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/rollup/action/GetRollupCapsAction.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/rollup/action/GetRollupCapsAction.java @@ -41,7 +41,7 @@ public static class Request extends ActionRequest implements ToXContentFragment private String indexPattern; public Request(String indexPattern) { - if (Strings.isNullOrEmpty(indexPattern) || indexPattern.equals("*")) { + if (Strings.isNullOrEmpty(indexPattern) || "*".equals(indexPattern)) { this.indexPattern = Metadata.ALL; } else { this.indexPattern = indexPattern; diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/rollup/action/GetRollupJobsAction.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/rollup/action/GetRollupJobsAction.java index c28ed47c38602..c4b15c521ae5f 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/rollup/action/GetRollupJobsAction.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/rollup/action/GetRollupJobsAction.java @@ -49,7 +49,7 @@ public static class Request extends BaseTasksRequest implements ToXCont private String id; public Request(String id) { - if (Strings.isNullOrEmpty(id) || id.equals("*")) { + if (Strings.isNullOrEmpty(id) || "*".equals(id)) { this.id = Metadata.ALL; } else { this.id = id; @@ -61,7 +61,7 @@ public Request() {} public Request(StreamInput in) throws IOException { super(in); id = in.readString(); - if (Strings.isNullOrEmpty(id) || id.equals("*")) { + if (Strings.isNullOrEmpty(id) || "*".equals(id)) { this.id = Metadata.ALL; } } diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/scheduler/Cron.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/scheduler/Cron.java index b9d39aa665848..dfbb2c97d8181 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/scheduler/Cron.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/scheduler/Cron.java @@ -874,7 +874,7 @@ private int storeExpressionVals(int pos, String s, int type) throws Elasticsearc return i; } char c = s.charAt(i); - if ((c >= 'A') && (c <= 'Z') && (s.equals("L") == false) && (s.equals("LW") == false) && (s.matches("^L-[0-9]*[W]?") == false)) { + if ((c >= 'A') && (c <= 'Z') && ("L".equals(s) == false) && ("LW".equals(s) == false) && (s.matches("^L-[0-9]*[W]?") == false)) { String sub = s.substring(i, i + 3); int sval = -1; int eval = -1; diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/Grant.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/Grant.java index 41f1f50b6f7f0..1279740b7a935 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/Grant.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/Grant.java @@ -163,14 +163,14 @@ public AuthenticationToken getAuthenticationToken() { public ActionRequestValidationException validate(ActionRequestValidationException validationException) { if (type == null) { validationException = addValidationError("[grant_type] is required", validationException); - } else if (type.equals(PASSWORD_GRANT_TYPE)) { + } else if (PASSWORD_GRANT_TYPE.equals(type)) { validationException = validateRequiredField("username", username, validationException); validationException = validateRequiredField("password", password, validationException); validationException = validateUnsupportedField("access_token", accessToken, validationException); if (clientAuthentication != null) { return addValidationError("[client_authentication] is not supported for grant_type [" + type + "]", validationException); } - } else if (type.equals(ACCESS_TOKEN_GRANT_TYPE)) { + } else if (ACCESS_TOKEN_GRANT_TYPE.equals(type)) { validationException = validateRequiredField("access_token", accessToken, validationException); validationException = validateUnsupportedField("username", username, validationException); validationException = validateUnsupportedField("password", password, validationException); diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authz/privilege/ApplicationPrivilege.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authz/privilege/ApplicationPrivilege.java index 8dbab86210f56..9dd6c1bcc44c8 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authz/privilege/ApplicationPrivilege.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authz/privilege/ApplicationPrivilege.java @@ -102,7 +102,7 @@ private static void validateApplicationName(String application, boolean allowWil if (allowWildcard == false) { throw new IllegalArgumentException("Application names may not contain '*' (found '" + application + "')"); } - if (application.equals("*")) { + if ("*".equals(application)) { // this is allowed and short-circuiting here makes the later validation simpler return; } diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/support/Automatons.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/support/Automatons.java index a364b9cdbb227..d5624023f8a88 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/support/Automatons.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/support/Automatons.java @@ -211,7 +211,7 @@ private static Automaton buildAutomaton(String pattern) { } String regex = pattern.substring(1, pattern.length() - 1); return new RegExp(regex).toAutomaton(); - } else if (pattern.equals("*")) { + } else if ("*".equals(pattern)) { return MATCH_ALL; } else { return wildcard(pattern); 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 9704335776f11..81afddcceafba 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 @@ -557,7 +557,7 @@ private static Map getSSLConfigurations(Environment en } private static Function getKeyStoreFilter(String sslContext) { - if (sslContext.equals("xpack.security.http.ssl")) { + if ("xpack.security.http.ssl".equals(sslContext)) { final Function exceptionHandler = e -> new ElasticsearchSecurityException( "Cannot process keystore for SSL configuration [" + sslContext + "] - " + e.getMessage(), e diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/transform/TransformConfigVersion.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/transform/TransformConfigVersion.java index ef65f4bca1c35..be3defeb75d6b 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/transform/TransformConfigVersion.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/transform/TransformConfigVersion.java @@ -344,7 +344,7 @@ public static TransformConfigVersion fromString(String str) { if (str == null) { return CURRENT; } - if (str.equals("8.10.0")) { + if ("8.10.0".equals(str)) { return V_10; } Matcher matcher = Pattern.compile("^(\\d+)\\.(\\d+)\\.(\\d+)(?:-\\w+)?$").matcher(str); diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/transform/action/GetTransformStatsAction.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/transform/action/GetTransformStatsAction.java index 46e844f93695e..4c4985d1acf7f 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/transform/action/GetTransformStatsAction.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/transform/action/GetTransformStatsAction.java @@ -60,7 +60,7 @@ public static final class Request extends BaseTasksRequest { public Request(String id, @Nullable TimeValue timeout) { setTimeout(timeout); - if (Strings.isNullOrEmpty(id) || id.equals("*")) { + if (Strings.isNullOrEmpty(id) || "*".equals(id)) { this.id = Metadata.ALL; } else { this.id = id; diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/support/WatcherDateTimeUtils.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/support/WatcherDateTimeUtils.java index 58b8c2391d8bd..2448bbcf87cd1 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/support/WatcherDateTimeUtils.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/support/WatcherDateTimeUtils.java @@ -194,10 +194,10 @@ public static TimeValue parseTimeValueSupportingFractional(@Nullable String sVal millis = (long) (Double.parseDouble(lowerSValue.substring(0, lowerSValue.length() - 1)) * 24 * 60 * 60 * 1000); } else if (lowerSValue.endsWith("w")) { millis = (long) (Double.parseDouble(lowerSValue.substring(0, lowerSValue.length() - 1)) * 7 * 24 * 60 * 60 * 1000); - } else if (lowerSValue.equals("-1")) { + } else if ("-1".equals(lowerSValue)) { // Allow this special value to be unit-less: millis = -1; - } else if (lowerSValue.equals("0")) { + } else if ("0".equals(lowerSValue)) { // Allow this special value to be unit-less: millis = 0; } else { diff --git a/x-pack/plugin/eql/src/main/java/org/elasticsearch/xpack/eql/plugin/RestEqlSearchAction.java b/x-pack/plugin/eql/src/main/java/org/elasticsearch/xpack/eql/plugin/RestEqlSearchAction.java index e24a4749f45cd..b434f8ed79964 100644 --- a/x-pack/plugin/eql/src/main/java/org/elasticsearch/xpack/eql/plugin/RestEqlSearchAction.java +++ b/x-pack/plugin/eql/src/main/java/org/elasticsearch/xpack/eql/plugin/RestEqlSearchAction.java @@ -90,7 +90,7 @@ public void onFailure(Exception e) { * pattern that failed resolving. More details here https://github.com/elastic/elasticsearch/issues/63529 */ if (e instanceof IndexNotFoundException infe) { - if (infe.getIndex() != null && infe.getIndex().getName().equals("Unknown index [*,-*]")) { + if (infe.getIndex() != null && "Unknown index [*,-*]".equals(infe.getIndex().getName())) { finalException = new IndexNotFoundException(indices, infe.getCause()); } } diff --git a/x-pack/plugin/esql/compute/gen/src/main/java/org/elasticsearch/compute/gen/AggregatorProcessor.java b/x-pack/plugin/esql/compute/gen/src/main/java/org/elasticsearch/compute/gen/AggregatorProcessor.java index b724ee9152ca8..fb88e21c1a651 100644 --- a/x-pack/plugin/esql/compute/gen/src/main/java/org/elasticsearch/compute/gen/AggregatorProcessor.java +++ b/x-pack/plugin/esql/compute/gen/src/main/java/org/elasticsearch/compute/gen/AggregatorProcessor.java @@ -118,7 +118,7 @@ public static void write(Object origination, String what, JavaFile file, Process JavaFileObject filerSourceFile = env.getFiler() .createSourceFile(fileName, file.typeSpec.originatingElements.toArray(Element[]::new)); try (Writer w = filerSourceFile.openWriter()) { - if (System.getProperty("line.separator").equals("\n")) { + if ("\n".equals(System.getProperty("line.separator"))) { file.writeTo(w); } else { w.write(file.toString().replace("\n", System.getProperty("line.separator"))); diff --git a/x-pack/plugin/esql/compute/gen/src/main/java/org/elasticsearch/compute/gen/EvaluatorProcessor.java b/x-pack/plugin/esql/compute/gen/src/main/java/org/elasticsearch/compute/gen/EvaluatorProcessor.java index ea3ee938298de..4960b424efa15 100644 --- a/x-pack/plugin/esql/compute/gen/src/main/java/org/elasticsearch/compute/gen/EvaluatorProcessor.java +++ b/x-pack/plugin/esql/compute/gen/src/main/java/org/elasticsearch/compute/gen/EvaluatorProcessor.java @@ -144,7 +144,7 @@ private static List warnExceptions(Element evaluatorMethod) { || annotationType.equals(ConvertEvaluator.class.getName())) { for (var e : mirror.getElementValues().entrySet()) { - if (false == e.getKey().getSimpleName().toString().equals("warnExceptions")) { + if (false == "warnExceptions".equals(e.getKey().getSimpleName().toString())) { continue; } for (var v : (List) e.getValue().getValue()) { diff --git a/x-pack/plugin/esql/compute/gen/src/main/java/org/elasticsearch/compute/gen/MvEvaluatorImplementer.java b/x-pack/plugin/esql/compute/gen/src/main/java/org/elasticsearch/compute/gen/MvEvaluatorImplementer.java index 0e794d6fa533f..fe8ed094cd1f6 100644 --- a/x-pack/plugin/esql/compute/gen/src/main/java/org/elasticsearch/compute/gen/MvEvaluatorImplementer.java +++ b/x-pack/plugin/esql/compute/gen/src/main/java/org/elasticsearch/compute/gen/MvEvaluatorImplementer.java @@ -400,7 +400,7 @@ private MethodSpec factoryToString() { */ private static class FinishFunction { static FinishFunction from(TypeElement declarationType, String name, TypeName workType, TypeName fieldType) { - if (name.equals("")) { + if ("".equals(name)) { if (false == workType.equals(fieldType)) { throw new IllegalArgumentException( "the [finish] enum value is required because the first and second arguments differ in type" @@ -441,7 +441,7 @@ private FinishFunction(TypeElement declarationType, ExecutableElement fn, TypeNa } continue; } - if (param.getSimpleName().toString().equals("valueCount")) { + if ("valueCount".equals(param.getSimpleName().toString())) { if (param.asType().getKind() != TypeKind.INT) { throw new IllegalArgumentException("count argument must have type [int]"); } @@ -463,7 +463,7 @@ private void call(MethodSpec.Builder builder, String workName) { */ private static class SingleValueFunction { static SingleValueFunction from(TypeElement declarationType, String name, TypeName resultType, TypeName fieldType) { - if (name.equals("")) { + if ("".equals(name)) { return null; } ExecutableElement fn = findMethod( @@ -495,7 +495,7 @@ private void call(MethodSpec.Builder builder) { */ private class AscendingFunction { static AscendingFunction from(MvEvaluatorImplementer impl, TypeElement declarationType, String name) { - if (name.equals("")) { + if ("".equals(name)) { return null; } diff --git a/x-pack/plugin/esql/compute/gen/src/main/java/org/elasticsearch/compute/gen/Types.java b/x-pack/plugin/esql/compute/gen/src/main/java/org/elasticsearch/compute/gen/Types.java index 1a09160dae3cd..fb30a34efa391 100644 --- a/x-pack/plugin/esql/compute/gen/src/main/java/org/elasticsearch/compute/gen/Types.java +++ b/x-pack/plugin/esql/compute/gen/src/main/java/org/elasticsearch/compute/gen/Types.java @@ -155,7 +155,7 @@ static ClassName blockType(String elementType) { if (elementType.equalsIgnoreCase(TypeName.BOOLEAN.toString())) { return BOOLEAN_BLOCK; } - if (elementType.equalsIgnoreCase("BYTES_REF")) { + if ("BYTES_REF".equalsIgnoreCase(elementType)) { return BYTES_REF_BLOCK; } if (elementType.equalsIgnoreCase(TypeName.INT.toString())) { @@ -193,7 +193,7 @@ static ClassName vectorType(String elementType) { if (elementType.equalsIgnoreCase(TypeName.BOOLEAN.toString())) { return BOOLEAN_VECTOR; } - if (elementType.equalsIgnoreCase("BYTES_REF")) { + if ("BYTES_REF".equalsIgnoreCase(elementType)) { return BYTES_REF_VECTOR; } if (elementType.equalsIgnoreCase(TypeName.INT.toString())) { diff --git a/x-pack/plugin/esql/qa/server/src/main/java/org/elasticsearch/xpack/esql/qa/rest/RestEsqlTestCase.java b/x-pack/plugin/esql/qa/server/src/main/java/org/elasticsearch/xpack/esql/qa/rest/RestEsqlTestCase.java index 3693f0b0c2bb9..1a4101425ca13 100644 --- a/x-pack/plugin/esql/qa/server/src/main/java/org/elasticsearch/xpack/esql/qa/rest/RestEsqlTestCase.java +++ b/x-pack/plugin/esql/qa/server/src/main/java/org/elasticsearch/xpack/esql/qa/rest/RestEsqlTestCase.java @@ -417,10 +417,10 @@ private static String expectedTextBody(String format, int count, @Nullable Chara case "tsv" -> sb.append('\t'); } sb.append(i); - if (format.equals("txt")) { + if ("txt".equals(format)) { sb.append(" ".repeat(15 - iLen)); } - sb.append(format.equals("csv") ? "\r\n" : "\n"); + sb.append("csv".equals(format) ? "\r\n" : "\n"); } return sb.toString(); } diff --git a/x-pack/plugin/esql/src/internalClusterTest/java/org/elasticsearch/xpack/esql/action/EsqlActionTaskIT.java b/x-pack/plugin/esql/src/internalClusterTest/java/org/elasticsearch/xpack/esql/action/EsqlActionTaskIT.java index d85d600b4a259..b4b5789bf90f0 100644 --- a/x-pack/plugin/esql/src/internalClusterTest/java/org/elasticsearch/xpack/esql/action/EsqlActionTaskIT.java +++ b/x-pack/plugin/esql/src/internalClusterTest/java/org/elasticsearch/xpack/esql/action/EsqlActionTaskIT.java @@ -175,7 +175,7 @@ public void testTaskContents() throws Exception { luceneSources++; continue; } - if (o.operator().equals("ValuesSourceReaderOperator[field = pause_me]")) { + if ("ValuesSourceReaderOperator[field = pause_me]".equals(o.operator())) { ValuesSourceReaderOperator.Status oStatus = (ValuesSourceReaderOperator.Status) o.status(); assertMap( oStatus.readersBuilt(), @@ -185,14 +185,14 @@ public void testTaskContents() throws Exception { valuesSourceReaders++; continue; } - if (o.operator().equals("ExchangeSourceOperator")) { + if ("ExchangeSourceOperator".equals(o.operator())) { ExchangeSourceOperator.Status oStatus = (ExchangeSourceOperator.Status) o.status(); assertThat(oStatus.pagesWaiting(), greaterThanOrEqualTo(0)); assertThat(oStatus.pagesEmitted(), greaterThanOrEqualTo(0)); exchangeSources++; continue; } - if (o.operator().equals("ExchangeSinkOperator")) { + if ("ExchangeSinkOperator".equals(o.operator())) { ExchangeSinkOperator.Status oStatus = (ExchangeSinkOperator.Status) o.status(); assertThat(oStatus.pagesAccepted(), greaterThanOrEqualTo(0)); exchangeSinks++; diff --git a/x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/parser/LogicalPlanBuilder.java b/x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/parser/LogicalPlanBuilder.java index d5763f28f6394..808bfd527977b 100644 --- a/x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/parser/LogicalPlanBuilder.java +++ b/x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/parser/LogicalPlanBuilder.java @@ -110,7 +110,7 @@ public PlanFactory visitDissectCommand(EsqlBaseParser.DissectCommandContext ctx) Map options = visitCommandOptions(ctx.commandOptions()); String appendSeparator = ""; for (Map.Entry item : options.entrySet()) { - if (item.getKey().equalsIgnoreCase("append_separator") == false) { + if ("append_separator".equalsIgnoreCase(item.getKey()) == false) { throw new ParsingException(source(ctx), "Invalid option for dissect: [{}]", item.getKey()); } if (item.getValue() instanceof String == false) { diff --git a/x-pack/plugin/identity-provider/src/main/java/org/elasticsearch/xpack/idp/action/PutSamlServiceProviderRequest.java b/x-pack/plugin/identity-provider/src/main/java/org/elasticsearch/xpack/idp/action/PutSamlServiceProviderRequest.java index 930bfc512e736..5f1c01a54c1e2 100644 --- a/x-pack/plugin/identity-provider/src/main/java/org/elasticsearch/xpack/idp/action/PutSamlServiceProviderRequest.java +++ b/x-pack/plugin/identity-provider/src/main/java/org/elasticsearch/xpack/idp/action/PutSamlServiceProviderRequest.java @@ -101,7 +101,7 @@ public ActionRequestValidationException validate() { if (Strings.hasText(document.acs)) { // if this is blank the document validation will fail try { final URL url = new URL(document.acs); - if (url.getProtocol().equals("https") == false) { + if ("https".equals(url.getProtocol()) == false) { validationException = addValidationError( "[" + SamlServiceProviderDocument.Fields.ACS + "] must use the [https] protocol", validationException diff --git a/x-pack/plugin/identity-provider/src/main/java/org/elasticsearch/xpack/idp/saml/idp/SamlIdentityProviderBuilder.java b/x-pack/plugin/identity-provider/src/main/java/org/elasticsearch/xpack/idp/saml/idp/SamlIdentityProviderBuilder.java index 8051b08c78a86..485c78d976660 100644 --- a/x-pack/plugin/identity-provider/src/main/java/org/elasticsearch/xpack/idp/saml/idp/SamlIdentityProviderBuilder.java +++ b/x-pack/plugin/identity-provider/src/main/java/org/elasticsearch/xpack/idp/saml/idp/SamlIdentityProviderBuilder.java @@ -394,7 +394,7 @@ private static void validateSigningKey(PrivateKey privateKey) { throw new ElasticsearchSecurityException("There is no private key available for this credential"); } final String keyType = privateKey.getAlgorithm(); - if (keyType.equals("RSA") == false && keyType.equals("EC") == false) { + if ("RSA".equals(keyType) == false && "EC".equals(keyType) == false) { throw new ElasticsearchSecurityException( "The private key uses unsupported key algorithm type [" + keyType + "], only RSA and EC are supported" ); diff --git a/x-pack/plugin/ilm/src/internalClusterTest/java/org/elasticsearch/xpack/ilm/UpdateSettingsStepTests.java b/x-pack/plugin/ilm/src/internalClusterTest/java/org/elasticsearch/xpack/ilm/UpdateSettingsStepTests.java index 4e8df685a25a7..5917f82c41e7f 100644 --- a/x-pack/plugin/ilm/src/internalClusterTest/java/org/elasticsearch/xpack/ilm/UpdateSettingsStepTests.java +++ b/x-pack/plugin/ilm/src/internalClusterTest/java/org/elasticsearch/xpack/ilm/UpdateSettingsStepTests.java @@ -81,7 +81,7 @@ void setValue(String value) { } void validate(String valueToCheck) { - if (valueToCheck.equals(INVALID_VALUE)) { + if (INVALID_VALUE.equals(valueToCheck)) { throw new IllegalArgumentException("[" + INVALID_VALUE + "] is not supported"); } } diff --git a/x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/elser/ElserMlNodeService.java b/x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/elser/ElserMlNodeService.java index f1fab447ec757..dfd600a154a73 100644 --- a/x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/elser/ElserMlNodeService.java +++ b/x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/elser/ElserMlNodeService.java @@ -73,7 +73,7 @@ public ElserMlNodeModel parseRequestConfig( // choose a default model version based on the cluster architecture if (serviceSettingsBuilder.getModelVariant() == null) { boolean homogenous = modelArchitectures.size() == 1; - if (homogenous && modelArchitectures.iterator().next().equals("linux-x86_64")) { + if (homogenous && "linux-x86_64".equals(modelArchitectures.iterator().next())) { // Use the hardware optimized model serviceSettingsBuilder.setModelVariant(ELSER_V2_MODEL_LINUX_X86); } else { diff --git a/x-pack/plugin/ml-package-loader/src/main/java/org/elasticsearch/xpack/ml/packageloader/MachineLearningPackageLoader.java b/x-pack/plugin/ml-package-loader/src/main/java/org/elasticsearch/xpack/ml/packageloader/MachineLearningPackageLoader.java index d13d910613d31..3a49942b8716b 100644 --- a/x-pack/plugin/ml-package-loader/src/main/java/org/elasticsearch/xpack/ml/packageloader/MachineLearningPackageLoader.java +++ b/x-pack/plugin/ml-package-loader/src/main/java/org/elasticsearch/xpack/ml/packageloader/MachineLearningPackageLoader.java @@ -115,7 +115,7 @@ static void validateModelRepository(String repository, Path configPath) throws U ); } - if (scheme.equals("file") && (baseUri.getPath().startsWith(normalizedConfigUri.getPath()) == false)) { + if ("file".equals(scheme) && (baseUri.getPath().startsWith(normalizedConfigUri.getPath()) == false)) { throw new IllegalArgumentException( "If xpack.ml.model_repository is a file location, it must be placed below the configuration: " + normalizedConfigUri ); diff --git a/x-pack/plugin/ml/qa/native-multi-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/ml/integration/ClassificationIT.java b/x-pack/plugin/ml/qa/native-multi-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/ml/integration/ClassificationIT.java index b610ac60dab00..ac2488f506826 100644 --- a/x-pack/plugin/ml/qa/native-multi-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/ml/integration/ClassificationIT.java +++ b/x-pack/plugin/ml/qa/native-multi-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/ml/integration/ClassificationIT.java @@ -565,7 +565,7 @@ public void testStopAndRestart() throws Exception { response = startAnalytics(jobId); assertThat(response.getNode(), not(emptyString())); } catch (Exception e) { - if (e.getMessage().equals("Cannot start because the job has already finished")) { + if ("Cannot start because the job has already finished".equals(e.getMessage())) { // That means the job had managed to complete } else { throw e; diff --git a/x-pack/plugin/ml/qa/native-multi-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/ml/integration/MlNativeIntegTestCase.java b/x-pack/plugin/ml/qa/native-multi-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/ml/integration/MlNativeIntegTestCase.java index 209f12c2e90ce..eacf1772bf77a 100644 --- a/x-pack/plugin/ml/qa/native-multi-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/ml/integration/MlNativeIntegTestCase.java +++ b/x-pack/plugin/ml/qa/native-multi-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/ml/integration/MlNativeIntegTestCase.java @@ -476,7 +476,7 @@ public T compile(String name, String script, ScriptContext context, Map 0.0))); } - if (context.name.equals("ingest")) { + if ("ingest".equals(context.name)) { IngestScript.Factory factory = (params, ctx) -> new IngestScript(params, ctx) { @Override public void execute() {} diff --git a/x-pack/plugin/ml/qa/native-multi-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/ml/integration/RegressionIT.java b/x-pack/plugin/ml/qa/native-multi-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/ml/integration/RegressionIT.java index ed7cfad8bf195..33bda9ede1b85 100644 --- a/x-pack/plugin/ml/qa/native-multi-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/ml/integration/RegressionIT.java +++ b/x-pack/plugin/ml/qa/native-multi-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/ml/integration/RegressionIT.java @@ -337,7 +337,7 @@ public void testStopAndRestart() throws Exception { response = startAnalytics(jobId); assertThat(response.getNode(), not(emptyString())); } catch (Exception e) { - if (e.getMessage().equals("Cannot start because the job has already finished")) { + if ("Cannot start because the job has already finished".equals(e.getMessage())) { // That means the job had managed to complete } else { throw e; diff --git a/x-pack/plugin/ml/qa/native-multi-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/ml/integration/RunDataFrameAnalyticsIT.java b/x-pack/plugin/ml/qa/native-multi-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/ml/integration/RunDataFrameAnalyticsIT.java index 2ab5ecb00aa00..2d17f651d7966 100644 --- a/x-pack/plugin/ml/qa/native-multi-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/ml/integration/RunDataFrameAnalyticsIT.java +++ b/x-pack/plugin/ml/qa/native-multi-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/ml/integration/RunDataFrameAnalyticsIT.java @@ -123,7 +123,7 @@ public void testOutlierDetectionWithFewDocuments() throws Exception { assertThat(resultsObject.containsKey("outlier_score"), is(true)); double outlierScore = (double) resultsObject.get("outlier_score"); assertThat(outlierScore, allOf(greaterThanOrEqualTo(0.0), lessThanOrEqualTo(1.0))); - if (hit.getId().equals("outlier")) { + if ("outlier".equals(hit.getId())) { scoreOfOutlier = outlierScore; } else { if (scoreOfNonOutlier < 0) { @@ -677,7 +677,7 @@ public void testOutlierDetectionStopAndRestart() throws Exception { response = startAnalytics(id); assertThat(response.getNode(), not(emptyString())); } catch (Exception e) { - if (e.getMessage().equals("Cannot start because the job has already finished")) { + if ("Cannot start because the job has already finished".equals(e.getMessage())) { // That means the job had managed to complete } else { throw e; @@ -768,7 +768,7 @@ public void testOutlierDetectionWithCustomParams() throws Exception { double outlierScore = (double) resultsObject.get("outlier_score"); assertThat(outlierScore, allOf(greaterThanOrEqualTo(0.0), lessThanOrEqualTo(1.0))); - if (hit.getId().equals("outlier")) { + if ("outlier".equals(hit.getId())) { scoreOfOutlier = outlierScore; } else { if (scoreOfNonOutlier < 0) { @@ -876,7 +876,7 @@ public void testOutlierDetection_GivenIndexWithRuntimeFields() throws Exception assertThat(resultsObject.containsKey("outlier_score"), is(true)); double outlierScore = (double) resultsObject.get("outlier_score"); assertThat(outlierScore, allOf(greaterThanOrEqualTo(0.0), lessThanOrEqualTo(1.0))); - if (hit.getId().equals("outlier")) { + if ("outlier".equals(hit.getId())) { scoreOfOutlier = outlierScore; @SuppressWarnings("unchecked") @@ -982,7 +982,7 @@ public void testOutlierDetection_GivenSearchRuntimeMappings() throws Exception { assertThat(resultsObject.containsKey("outlier_score"), is(true)); double outlierScore = (double) resultsObject.get("outlier_score"); assertThat(outlierScore, allOf(greaterThanOrEqualTo(0.0), lessThanOrEqualTo(1.0))); - if (hit.getId().equals("outlier")) { + if ("outlier".equals(hit.getId())) { scoreOfOutlier = outlierScore; @SuppressWarnings("unchecked") diff --git a/x-pack/plugin/ml/qa/native-multi-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/ml/integration/TextEmbeddingQueryIT.java b/x-pack/plugin/ml/qa/native-multi-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/ml/integration/TextEmbeddingQueryIT.java index 8e425ea071879..edc824db358c2 100644 --- a/x-pack/plugin/ml/qa/native-multi-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/ml/integration/TextEmbeddingQueryIT.java +++ b/x-pack/plugin/ml/qa/native-multi-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/ml/integration/TextEmbeddingQueryIT.java @@ -274,7 +274,7 @@ public void testHybridSearch() throws IOException { boolean found = false; for (var hit : hits) { String source = (String) MapHelper.dig("_source.source_text", hit); - if (source.equals("my words")) { + if ("my words".equals(source)) { assertThat((Double) MapHelper.dig("_score", hit), closeTo(10.0, 0.01)); found = true; } diff --git a/x-pack/plugin/ml/src/internalClusterTest/java/org/elasticsearch/xpack/ml/integration/JobResultsProviderIT.java b/x-pack/plugin/ml/src/internalClusterTest/java/org/elasticsearch/xpack/ml/integration/JobResultsProviderIT.java index 891779e28439b..adc4e0b31e21e 100644 --- a/x-pack/plugin/ml/src/internalClusterTest/java/org/elasticsearch/xpack/ml/integration/JobResultsProviderIT.java +++ b/x-pack/plugin/ml/src/internalClusterTest/java/org/elasticsearch/xpack/ml/integration/JobResultsProviderIT.java @@ -286,7 +286,7 @@ public void testGetCalandarByJobId() throws Exception { queryResult = getCalendars(CalendarQueryBuilder.builder().jobId("foo")); assertThat(queryResult, hasSize(3)); Long matchedCount = queryResult.stream() - .filter(c -> c.getId().equals("foo calendar") || c.getId().equals("foo bar calendar") || c.getId().equals("cat foo calendar")) + .filter(c -> "foo calendar".equals(c.getId()) || "foo bar calendar".equals(c.getId()) || "cat foo calendar".equals(c.getId())) .count(); assertEquals(Long.valueOf(3), matchedCount); diff --git a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/aggs/changepoint/InternalChangePointAggregation.java b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/aggs/changepoint/InternalChangePointAggregation.java index e9713497cb148..dc198ef28f3ef 100644 --- a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/aggs/changepoint/InternalChangePointAggregation.java +++ b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/aggs/changepoint/InternalChangePointAggregation.java @@ -77,16 +77,16 @@ protected boolean mustReduceOnSingleInternalAgg() { public Object getProperty(List path) { if (path.size() == 1) { String property = path.get(0); - if (property.equals("p_value")) { + if ("p_value".equals(property)) { return changeType.pValue(); } - if (property.equals("type")) { + if ("type".equals(property)) { return changeType.getName(); } - if (property.equals("change_point")) { + if ("change_point".equals(property)) { return changeType.changePoint(); } - } else if (path.size() > 1 && path.get(0).equals("bucket") && bucket != null) { + } else if (path.size() > 1 && "bucket".equals(path.get(0)) && bucket != null) { return bucket.getProperty(name, path.subList(1, path.size())); } return null; diff --git a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/inference/nlp/NerProcessor.java b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/inference/nlp/NerProcessor.java index 599b3c90204ef..49042f84971bd 100644 --- a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/inference/nlp/NerProcessor.java +++ b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/inference/nlp/NerProcessor.java @@ -38,7 +38,7 @@ static IobTag fromTag(String tag) { if (entity.startsWith("B-") || entity.startsWith("I-") || entity.startsWith("B_") || entity.startsWith("I_")) { entity = entity.substring(2); return new IobTag(tag, entity); - } else if (entity.equals("O")) { + } else if ("O".equals(entity)) { return new IobTag(tag, entity); } else { throw new IllegalArgumentException("classification label [" + tag + "] is not an entity I-O-B tag.");