diff --git a/.github/workflows/precommit.yml b/.github/workflows/precommit.yml index b4e9853ab7fb6..ff9fbfb3bed65 100644 --- a/.github/workflows/precommit.yml +++ b/.github/workflows/precommit.yml @@ -1,4 +1,4 @@ -name: Gradle Precommit +name: Gradle PreCommit on: [pull_request] jobs: @@ -21,8 +21,11 @@ jobs: java-version: ${{ matrix.java }} distribution: temurin cache: gradle - - name: Run Gradle (precommit) + - name: Run Gradle (pre-commit) continue-on-error: ${{ matrix.experimental }} shell: bash - run: | - ./gradlew javadoc precommit --parallel + run: ./gradlew javadoc precommit --parallel + - name: Run Gradle (sanity-check) + continue-on-error: ${{ matrix.experimental }} + shell: bash + run: ./gradlew rewriteDryRun -Dorg.gradle.jvmargs=-Xmx8G diff --git a/CHANGELOG.md b/CHANGELOG.md index c75677224ac94..a61af60ba69b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - Add build-tooling to run in FIPS environment ([#18921](https://github.com/opensearch-project/OpenSearch/pull/18921)) - Add SMILE/CBOR/YAML document format support to Bulk GRPC endpoint ([#19744](https://github.com/opensearch-project/OpenSearch/pull/19744)) - Implement GRPC ConstantScoreQuery, FuzzyQuery, MatchBoolPrefixQuery, MatchPhrasePrefix, PrefixQuery, MatchQuery ([#19854](https://github.com/opensearch-project/OpenSearch/pull/19854)) +- [rewrite] Add `GradleBestPractices` ([#19885](https://github.com/opensearch-project/OpenSearch/pull/19885)) +- [prone] Add `error-prone.picnic.tech` featuring `RedundantStringConversion` ([#18791](https://github.com/opensearch-project/OpenSearch/pull/18791)) ### Changed - Faster `terms` query creation for `keyword` field with index and docValues enabled ([#19350](https://github.com/opensearch-project/OpenSearch/pull/19350)) diff --git a/build.gradle b/build.gradle index 5746a824e8f44..068fc27ca1501 100644 --- a/build.gradle +++ b/build.gradle @@ -59,6 +59,8 @@ plugins { id "org.gradle.test-retry" version "1.6.2" apply false id "test-report-aggregation" id 'jacoco-report-aggregation' + id 'org.openrewrite.rewrite' version '7.19.0' apply false + id 'net.ltgt.errorprone' version '4.3.0' apply false } apply from: 'gradle/build-complete.gradle' @@ -70,14 +72,12 @@ apply from: 'gradle/local-distribution.gradle' apply from: 'gradle/run.gradle' apply from: 'gradle/missing-javadoc.gradle' apply from: 'gradle/code-coverage.gradle' +apply from: 'gradle/rewrite.gradle' -// Apply FIPS configuration to all projects allprojects { + apply from: "$rootDir/gradle/error-prone.gradle" apply from: "$rootDir/gradle/fips.gradle" -} - -// common maven publishing configuration -allprojects { + // common maven publishing configuration group = 'org.opensearch' version = VersionProperties.getOpenSearch() description = "OpenSearch subproject ${project.path}" diff --git a/buildSrc/src/integTest/java/org/opensearch/gradle/tar/SymbolicLinkPreservingTarIT.java b/buildSrc/src/integTest/java/org/opensearch/gradle/tar/SymbolicLinkPreservingTarIT.java index 61aa55b9c6b53..ab5c9dc3d2db9 100644 --- a/buildSrc/src/integTest/java/org/opensearch/gradle/tar/SymbolicLinkPreservingTarIT.java +++ b/buildSrc/src/integTest/java/org/opensearch/gradle/tar/SymbolicLinkPreservingTarIT.java @@ -167,7 +167,7 @@ private void runBuild(final String task, final boolean preserveFileTimestamps) { .withProjectDir(getProjectDir()) .withArguments( task, - "-Dtests.symbolic_link_preserving_tar_source=" + temporaryFolder.getRoot().toString(), + "-Dtests.symbolic_link_preserving_tar_source=" + temporaryFolder.getRoot(), "-Dtests.symbolic_link_preserving_tar_preserve_file_timestamps=" + preserveFileTimestamps, "-i" ) diff --git a/buildSrc/src/main/java/org/opensearch/gradle/ReaperService.java b/buildSrc/src/main/java/org/opensearch/gradle/ReaperService.java index 498bd68ca2a91..3be430276f252 100644 --- a/buildSrc/src/main/java/org/opensearch/gradle/ReaperService.java +++ b/buildSrc/src/main/java/org/opensearch/gradle/ReaperService.java @@ -190,7 +190,7 @@ private Path locateReaperJar() { private void ensureReaperAlive() { if (reaperProcess.isAlive() == false) { - throw new IllegalStateException("Reaper process died unexpectedly! Check the log at " + logFile.toString()); + throw new IllegalStateException("Reaper process died unexpectedly! Check the log at " + logFile); } } } diff --git a/buildSrc/src/main/java/org/opensearch/gradle/Version.java b/buildSrc/src/main/java/org/opensearch/gradle/Version.java index 4c184f908e5d2..57806c5fd7673 100644 --- a/buildSrc/src/main/java/org/opensearch/gradle/Version.java +++ b/buildSrc/src/main/java/org/opensearch/gradle/Version.java @@ -106,7 +106,7 @@ public static Version fromString(final String s, final Mode mode) { @Override public String toString() { - return String.valueOf(getMajor()) + "." + String.valueOf(getMinor()) + "." + String.valueOf(getRevision()); + return getMajor() + "." + getMinor() + "." + getRevision(); } public boolean before(Version compareTo) { diff --git a/buildSrc/src/main/java/org/opensearch/gradle/internal/InternalDistributionDownloadPlugin.java b/buildSrc/src/main/java/org/opensearch/gradle/internal/InternalDistributionDownloadPlugin.java index 6a54612320c6c..98f9c17175ddf 100644 --- a/buildSrc/src/main/java/org/opensearch/gradle/internal/InternalDistributionDownloadPlugin.java +++ b/buildSrc/src/main/java/org/opensearch/gradle/internal/InternalDistributionDownloadPlugin.java @@ -176,9 +176,7 @@ private static String distributionProjectName(OpenSearchDistribution distributio switch (distribution.getType()) { case ARCHIVE: if (Version.fromString(distribution.getVersion()).onOrAfter("7.0.0")) { - projectName += platform.toString() + archString + (platform == OpenSearchDistribution.Platform.WINDOWS - ? "-zip" - : "-tar"); + projectName += platform + archString + (platform == OpenSearchDistribution.Platform.WINDOWS ? "-zip" : "-tar"); } else { projectName = "zip"; } diff --git a/buildSrc/src/main/java/org/opensearch/gradle/pluginzip/Publish.java b/buildSrc/src/main/java/org/opensearch/gradle/pluginzip/Publish.java index 599beb8649fcd..f37d3be229c08 100644 --- a/buildSrc/src/main/java/org/opensearch/gradle/pluginzip/Publish.java +++ b/buildSrc/src/main/java/org/opensearch/gradle/pluginzip/Publish.java @@ -39,7 +39,7 @@ private void addLocalMavenRepo(Project project) { publishing.repositories(repositories -> { repositories.maven(maven -> { maven.setName(STAGING_REPO); - maven.setUrl(buildDirectory.toString() + LOCAL_STAGING_REPO_PATH); + maven.setUrl(buildDirectory + LOCAL_STAGING_REPO_PATH); }); }); }); diff --git a/buildSrc/src/main/java/org/opensearch/gradle/precommit/ForbiddenPatternsTask.java b/buildSrc/src/main/java/org/opensearch/gradle/precommit/ForbiddenPatternsTask.java index fbf96483443ee..9ee28ea5908c5 100644 --- a/buildSrc/src/main/java/org/opensearch/gradle/precommit/ForbiddenPatternsTask.java +++ b/buildSrc/src/main/java/org/opensearch/gradle/precommit/ForbiddenPatternsTask.java @@ -189,7 +189,7 @@ public void rule(Map props) { throw new InvalidUserDataException("Missing [pattern] for invalid pattern rule"); } if (props.isEmpty() == false) { - throw new InvalidUserDataException("Unknown arguments for ForbiddenPatterns rule mapping: " + props.keySet().toString()); + throw new InvalidUserDataException("Unknown arguments for ForbiddenPatterns rule mapping: " + props.keySet()); } // TODO: fail if pattern contains a newline, it won't work (currently) patterns.put(name, pattern); diff --git a/buildSrc/src/main/java/org/opensearch/gradle/precommit/ValidateJsonAgainstSchemaTask.java b/buildSrc/src/main/java/org/opensearch/gradle/precommit/ValidateJsonAgainstSchemaTask.java index d829071c07e3c..10b6546e56c1a 100644 --- a/buildSrc/src/main/java/org/opensearch/gradle/precommit/ValidateJsonAgainstSchemaTask.java +++ b/buildSrc/src/main/java/org/opensearch/gradle/precommit/ValidateJsonAgainstSchemaTask.java @@ -148,9 +148,8 @@ public void validate(InputChanges inputChanges) throws IOException { private void maybeLogAndCollectError(Set messages, Map> errors, File file) { for (ValidationMessage message : messages) { - getLogger().error("[validate JSON][ERROR][{}][{}]", file.getName(), message.toString()); - errors.computeIfAbsent(file, k -> new LinkedHashSet<>()) - .add(String.format("%s: %s", file.getAbsolutePath(), message.toString())); + getLogger().error("[validate JSON][ERROR][{}][{}]", file.getName(), message); + errors.computeIfAbsent(file, k -> new LinkedHashSet<>()).add(String.format("%s: %s", file.getAbsolutePath(), message)); } } } diff --git a/buildSrc/src/main/java/org/opensearch/gradle/testclusters/OpenSearchNode.java b/buildSrc/src/main/java/org/opensearch/gradle/testclusters/OpenSearchNode.java index 47781f4ed5de7..9fbdfc6c15185 100644 --- a/buildSrc/src/main/java/org/opensearch/gradle/testclusters/OpenSearchNode.java +++ b/buildSrc/src/main/java/org/opensearch/gradle/testclusters/OpenSearchNode.java @@ -600,7 +600,7 @@ private void logToProcessStdout(String message) { } Files.write( stdoutFile, - ("[" + Instant.now().toString() + "] [BUILD] " + message + "\n").getBytes(StandardCharsets.UTF_8), + ("[" + Instant.now() + "] [BUILD] " + message + "\n").getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.APPEND ); @@ -707,7 +707,7 @@ public void extraConfigFile(String destination, File from, PropertyNormalization @Override public void extraJarFile(File from) { if (from.toString().endsWith(".jar") == false) { - throw new IllegalArgumentException("extra jar file " + from.toString() + " doesn't appear to be a JAR"); + throw new IllegalArgumentException("extra jar file " + from + " doesn't appear to be a JAR"); } extraJarFiles.add(from); } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/TasksRequestConverters.java b/client/rest-high-level/src/main/java/org/opensearch/client/TasksRequestConverters.java index 78a74ca04ff9b..6416b398d0a94 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/TasksRequestConverters.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/TasksRequestConverters.java @@ -76,7 +76,7 @@ static Request listTasks(ListTasksRequest listTaskRequest) { static Request getTask(GetTaskRequest getTaskRequest) { String endpoint = new EndpointBuilder().addPathPartAsIs("_tasks") - .addPathPartAsIs(getTaskRequest.getNodeId() + ":" + Long.toString(getTaskRequest.getTaskId())) + .addPathPartAsIs(getTaskRequest.getNodeId() + ":" + getTaskRequest.getTaskId()) .build(); Request request = new Request(HttpGet.METHOD_NAME, endpoint); RequestConverters.Params params = new RequestConverters.Params(); diff --git a/client/rest/src/main/java/org/opensearch/client/RequestOptions.java b/client/rest/src/main/java/org/opensearch/client/RequestOptions.java index bbc1f8bc85fcb..5396df5269648 100644 --- a/client/rest/src/main/java/org/opensearch/client/RequestOptions.java +++ b/client/rest/src/main/java/org/opensearch/client/RequestOptions.java @@ -153,7 +153,7 @@ public String toString() { if (h != 0) { b.append(','); } - b.append(headers.get(h).toString()); + b.append(headers.get(h)); } } if (parameters.size() > 0) { diff --git a/client/rest/src/main/java/org/opensearch/client/ResponseException.java b/client/rest/src/main/java/org/opensearch/client/ResponseException.java index ed816c7e1177e..265bca6c03869 100644 --- a/client/rest/src/main/java/org/opensearch/client/ResponseException.java +++ b/client/rest/src/main/java/org/opensearch/client/ResponseException.java @@ -65,7 +65,7 @@ static String buildMessage(Response response) throws IOException { response.getRequestLine().getMethod(), response.getHost(), response.getRequestLine().getUri(), - response.getStatusLine().toString() + response.getStatusLine() ); if (response.hasWarnings()) { diff --git a/client/rest/src/test/java/org/opensearch/client/RequestLoggerTests.java b/client/rest/src/test/java/org/opensearch/client/RequestLoggerTests.java index 8dea2ad922bd6..6415402b819d2 100644 --- a/client/rest/src/test/java/org/opensearch/client/RequestLoggerTests.java +++ b/client/rest/src/test/java/org/opensearch/client/RequestLoggerTests.java @@ -123,7 +123,7 @@ public void testTraceResponse() throws IOException, ParseException { int statusCode = randomIntBetween(200, 599); String reasonPhrase = "REASON"; StatusLine statusLine = new StatusLine(protocolVersion, statusCode, reasonPhrase); - String expected = "# " + statusLine.toString(); + String expected = "# " + statusLine; ClassicHttpResponse httpResponse = new BasicClassicHttpResponse(statusCode, reasonPhrase); int numHeaders = randomIntBetween(0, 3); for (int i = 0; i < numHeaders; i++) { diff --git a/client/rest/src/test/java/org/opensearch/client/ResponseExceptionTests.java b/client/rest/src/test/java/org/opensearch/client/ResponseExceptionTests.java index dfbf105637962..6f25539bbd473 100644 --- a/client/rest/src/test/java/org/opensearch/client/ResponseExceptionTests.java +++ b/client/rest/src/test/java/org/opensearch/client/ResponseExceptionTests.java @@ -93,7 +93,7 @@ public void testResponseException() throws IOException, ParseException { response.getRequestLine().getMethod(), response.getHost(), response.getRequestLine().getUri(), - response.getStatusLine().toString() + response.getStatusLine() ); if (hasBody) { diff --git a/distribution/archives/build.gradle b/distribution/archives/build.gradle index b6cb165cb6333..ff18c12959053 100644 --- a/distribution/archives/build.gradle +++ b/distribution/archives/build.gradle @@ -28,7 +28,7 @@ * under the License. */ -import org.opensearch.gradle.JavaPackageType +import org.opensearch.gradle.JavaPackageType apply plugin: 'opensearch.internal-distribution-archive-setup' @@ -193,7 +193,7 @@ distribution_archives { } } - + linuxPpc64leTar { archiveClassifier = 'linux-ppc64le' content { diff --git a/distribution/tools/keystore-cli/src/main/java/org/opensearch/tools/cli/keystore/AddFileKeyStoreCommand.java b/distribution/tools/keystore-cli/src/main/java/org/opensearch/tools/cli/keystore/AddFileKeyStoreCommand.java index c6725815efc4c..1c834192fc10a 100644 --- a/distribution/tools/keystore-cli/src/main/java/org/opensearch/tools/cli/keystore/AddFileKeyStoreCommand.java +++ b/distribution/tools/keystore-cli/src/main/java/org/opensearch/tools/cli/keystore/AddFileKeyStoreCommand.java @@ -90,7 +90,7 @@ protected void executeCommand(Terminal terminal, OptionSet options, Environment final Path file = getPath(argumentValues.get(i + 1)); if (Files.exists(file) == false) { - throw new UserException(ExitCodes.IO_ERROR, "File [" + file.toString() + "] does not exist"); + throw new UserException(ExitCodes.IO_ERROR, "File [" + file + "] does not exist"); } keyStore.setFile(setting, Files.readAllBytes(file)); diff --git a/distribution/tools/plugin-cli/src/main/java/org/opensearch/tools/cli/plugin/InstallPluginCommand.java b/distribution/tools/plugin-cli/src/main/java/org/opensearch/tools/cli/plugin/InstallPluginCommand.java index 4f69157545a22..cefbca8cc4aa3 100644 --- a/distribution/tools/plugin-cli/src/main/java/org/opensearch/tools/cli/plugin/InstallPluginCommand.java +++ b/distribution/tools/plugin-cli/src/main/java/org/opensearch/tools/cli/plugin/InstallPluginCommand.java @@ -327,7 +327,7 @@ private Path download(Terminal terminal, String pluginId, Path tmpDir, boolean i List plugins = checkMisspelledPlugin(pluginId); String msg = "Unknown plugin " + pluginId; if (plugins.isEmpty() == false) { - msg += ", did you mean " + (plugins.size() == 1 ? "[" + plugins.get(0) + "]" : "any of " + plugins.toString()) + "?"; + msg += ", did you mean " + (plugins.size() == 1 ? "[" + plugins.get(0) + "]" : "any of " + plugins) + "?"; } throw new UserException(ExitCodes.USAGE, msg); } diff --git a/gradle/error-prone.gradle b/gradle/error-prone.gradle new file mode 100644 index 0000000000000..2350a63736d47 --- /dev/null +++ b/gradle/error-prone.gradle @@ -0,0 +1,42 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + */ + +apply plugin: 'net.ltgt.errorprone' + +repositories { + mavenCentral() +} + +configurations.all { // remove once in sync (collision resolved) + resolutionStrategy { + force 'com.google.code.findbugs:jsr305:3.0.2' + force 'com.google.errorprone:error_prone_annotations:2.42.0' + force 'com.google.errorprone:error_prone_core:2.42.0' + force 'com.google.guava:guava:33.4.0-jre' + force 'org.checkerframework:checker-qual:3.43.0' + } +} + +dependencies { + errorprone('com.google.errorprone:error_prone_core:2.42.0') + errorprone('tech.picnic.error-prone-support:error-prone-contrib:0.25.0') +} + +tasks.withType(JavaCompile).configureEach { + options.errorprone { + disableAllChecks = true // remove once complain. + disableWarningsInGeneratedCode = true + error('RedundantStringConversion') + if (!System.getenv().containsKey('CI') && System.getenv('IN_PLACE')?.toBoolean()) { // remove once complain. + errorproneArgs.addAll( + '-XepPatchLocation:IN_PLACE', + '-XepPatchChecks:RedundantStringConversion' + ) + } + } +} diff --git a/gradle/rewrite.gradle b/gradle/rewrite.gradle new file mode 100644 index 0000000000000..60a6f485e09bb --- /dev/null +++ b/gradle/rewrite.gradle @@ -0,0 +1,28 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + */ + +project.apply plugin: 'org.openrewrite.rewrite' + +rewrite { + activeRecipe('org.opensearch.openrewrite.SanityCheck') + exclusion('**ActionListener.java') + exclusion('**SearchAfterIT.java') + exclusion('**StarTreeMapper.java') + exclusion('**package-info.java') + setExportDatatables(true) + setFailOnDryRunResults(true) +} + +dependencies { + rewrite(platform('org.openrewrite.recipe:rewrite-recipe-bom:3.17.0')) + rewrite('org.openrewrite.recipe:rewrite-migrate-java:3.20.0') + rewrite('org.openrewrite.recipe:rewrite-java-security:3.19.2') + rewrite('org.openrewrite.recipe:rewrite-rewrite:0.14.1') + rewrite('org.openrewrite.recipe:rewrite-static-analysis:2.20.0') + rewrite('org.openrewrite.recipe:rewrite-third-party:0.30.0') +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 1b33c55baabb5..f8e1ee3125fe0 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 7e324494c4c00..a8eccb6a331e8 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,8 +1,8 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.0-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.0-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionSha256Sum=16f2b95838c1ddcf7242b1c39e7bbbb43c842f1f1a1a0dc4959b6d4d68abcac3 +distributionSha256Sum=df67a32e86e3276d011735facb1535f64d0d88df84fa87521e90becc2d735444 diff --git a/gradlew b/gradlew index 23d15a9367071..cd69147b477bb 100755 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ #!/bin/sh # -# Copyright © 2015-2021 the original authors. +# Copyright © 2015 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -202,7 +202,7 @@ fi # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' +DEFAULT_JVM_OPTS= # Collect all arguments for the java command: # * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, diff --git a/gradlew.bat b/gradlew.bat old mode 100644 new mode 100755 index 5eed7ee845284..53c7bc8d9d39a --- a/gradlew.bat +++ b/gradlew.bat @@ -36,7 +36,7 @@ set APP_HOME=%DIRNAME% for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" +set DEFAULT_JVM_OPTS= @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome @@ -70,11 +70,10 @@ goto fail :execute @rem Setup the command line -set CLASSPATH= @rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* :end @rem End local scope for the variables with windows NT shell diff --git a/libs/common/src/main/java/org/opensearch/common/bootstrap/JarHell.java b/libs/common/src/main/java/org/opensearch/common/bootstrap/JarHell.java index 470b92aaa2fab..4546d80b560a0 100644 --- a/libs/common/src/main/java/org/opensearch/common/bootstrap/JarHell.java +++ b/libs/common/src/main/java/org/opensearch/common/bootstrap/JarHell.java @@ -275,7 +275,7 @@ public static void checkJavaVersion(String resource, String targetVersion) { Version version = Version.parse(targetVersion); if (Runtime.version().compareTo(version) < 0) { throw new IllegalStateException( - String.format(Locale.ROOT, "%s requires Java %s:, your system: %s", resource, targetVersion, Runtime.version().toString()) + String.format(Locale.ROOT, "%s requires Java %s:, your system: %s", resource, targetVersion, Runtime.version()) ); } } diff --git a/libs/core/src/main/java/org/opensearch/core/common/transport/BoundTransportAddress.java b/libs/core/src/main/java/org/opensearch/core/common/transport/BoundTransportAddress.java index e2266339c058f..74f44012590b7 100644 --- a/libs/core/src/main/java/org/opensearch/core/common/transport/BoundTransportAddress.java +++ b/libs/core/src/main/java/org/opensearch/core/common/transport/BoundTransportAddress.java @@ -94,7 +94,7 @@ public String toString() { String hostString = publishAddress.address().getHostString(); String publishAddressString = publishAddress.toString(); if (InetAddresses.isInetAddress(hostString) == false) { - publishAddressString = hostString + '/' + publishAddress.toString(); + publishAddressString = hostString + '/' + publishAddress; } builder.append(publishAddressString); builder.append("}, bound_addresses "); diff --git a/libs/core/src/main/java/org/opensearch/core/tasks/resourcetracker/ResourceUsageInfo.java b/libs/core/src/main/java/org/opensearch/core/tasks/resourcetracker/ResourceUsageInfo.java index e7b51c3389b52..4339e5f0c114b 100644 --- a/libs/core/src/main/java/org/opensearch/core/tasks/resourcetracker/ResourceUsageInfo.java +++ b/libs/core/src/main/java/org/opensearch/core/tasks/resourcetracker/ResourceUsageInfo.java @@ -43,10 +43,7 @@ public void recordResourceUsageMetrics(ResourceUsageMetric... resourceUsageMetri updateResourceUsageInfo(resourceStatsInfo, resourceUsageMetric); } else { throw new IllegalStateException( - "cannot update [" - + resourceUsageMetric.getStats().toString() - + "] entry as its not present current_stats_info:" - + statsInfo + "cannot update [" + resourceUsageMetric.getStats() + "] entry as its not present current_stats_info:" + statsInfo ); } } diff --git a/libs/core/src/main/java/org/opensearch/core/xcontent/ObjectParser.java b/libs/core/src/main/java/org/opensearch/core/xcontent/ObjectParser.java index 04d0bce27c04f..16f4dc8ab52f9 100644 --- a/libs/core/src/main/java/org/opensearch/core/xcontent/ObjectParser.java +++ b/libs/core/src/main/java/org/opensearch/core/xcontent/ObjectParser.java @@ -364,7 +364,7 @@ public Value parse(XContentParser parser, Value value, Context context) throws I StringBuilder message = new StringBuilder(); for (List fieldset : exclusiveFields) { if (fieldset.size() > 1) { - message.append("The following fields are not allowed together: ").append(fieldset.toString()).append(" "); + message.append("The following fields are not allowed together: ").append(fieldset).append(" "); } } if (message.length() > 0) { diff --git a/libs/core/src/main/java/org/opensearch/core/xcontent/XContentParseException.java b/libs/core/src/main/java/org/opensearch/core/xcontent/XContentParseException.java index 7eb4843df514f..01e8f0e0c7cc8 100644 --- a/libs/core/src/main/java/org/opensearch/core/xcontent/XContentParseException.java +++ b/libs/core/src/main/java/org/opensearch/core/xcontent/XContentParseException.java @@ -72,6 +72,6 @@ public XContentLocation getLocation() { @Override public String getMessage() { - return location.map(l -> "[" + l.toString() + "] ").orElse("") + super.getMessage(); + return location.map(l -> "[" + l + "] ").orElse("") + super.getMessage(); } } diff --git a/libs/ssl-config/src/main/java/org/opensearch/common/ssl/SslDiagnostics.java b/libs/ssl-config/src/main/java/org/opensearch/common/ssl/SslDiagnostics.java index f0a7d5bff4964..9e9b951d6024f 100644 --- a/libs/ssl-config/src/main/java/org/opensearch/common/ssl/SslDiagnostics.java +++ b/libs/ssl-config/src/main/java/org/opensearch/common/ssl/SslDiagnostics.java @@ -392,7 +392,7 @@ private static String fingerprintDescription(X509Certificate certificate) { final String fingerprint = SslUtil.calculateFingerprint(certificate); return "fingerprint [" + fingerprint + "]"; } catch (CertificateEncodingException e) { - return "invalid encoding [" + e.toString() + "]"; + return "invalid encoding [" + e + "]"; } } diff --git a/modules/aggs-matrix-stats/src/main/java/org/opensearch/search/aggregations/matrix/stats/MatrixStatsAggregatorFactory.java b/modules/aggs-matrix-stats/src/main/java/org/opensearch/search/aggregations/matrix/stats/MatrixStatsAggregatorFactory.java index 24f74f3859157..00d0d8f62eee6 100644 --- a/modules/aggs-matrix-stats/src/main/java/org/opensearch/search/aggregations/matrix/stats/MatrixStatsAggregatorFactory.java +++ b/modules/aggs-matrix-stats/src/main/java/org/opensearch/search/aggregations/matrix/stats/MatrixStatsAggregatorFactory.java @@ -81,7 +81,7 @@ protected Aggregator doCreateInternal( for (Map.Entry entry : valuesSources.entrySet()) { if (entry.getValue() instanceof ValuesSource.Numeric == false) { throw new AggregationExecutionException( - "ValuesSource type " + entry.getValue().toString() + "is not supported for aggregation " + this.name() + "ValuesSource type " + entry.getValue() + "is not supported for aggregation " + this.name() ); } // TODO: There must be a better option than this. diff --git a/modules/autotagging-commons/common/src/main/java/org/opensearch/rule/RuleUtils.java b/modules/autotagging-commons/common/src/main/java/org/opensearch/rule/RuleUtils.java index cd7a8ecf524fe..54447d4945955 100644 --- a/modules/autotagging-commons/common/src/main/java/org/opensearch/rule/RuleUtils.java +++ b/modules/autotagging-commons/common/src/main/java/org/opensearch/rule/RuleUtils.java @@ -52,7 +52,7 @@ public static String computeRuleHash( Map> attributeMap, String featureValue ) { - String combined = description + "|" + featureType.getName() + "|" + attributeMap.toString() + "|" + featureValue; + String combined = description + "|" + featureType.getName() + "|" + attributeMap + "|" + featureValue; UUID uuid = UUID.nameUUIDFromBytes(combined.getBytes(StandardCharsets.UTF_8)); return uuid.toString(); } diff --git a/modules/build.gradle b/modules/build.gradle index 0c69a43af0509..f089bcd982efe 100644 --- a/modules/build.gradle +++ b/modules/build.gradle @@ -32,7 +32,7 @@ configure(subprojects.findAll { it.parent.path == project.path }) { group = 'org.opensearch.plugin' // for modules which publish client jars apply plugin: 'opensearch.testclusters' apply plugin: 'opensearch.opensearchplugin' - + opensearchplugin { // for local OpenSearch plugins, the name of the plugin is the same as the directory name = project.name diff --git a/modules/ingest-user-agent/src/main/java/org/opensearch/ingest/useragent/UserAgentProcessor.java b/modules/ingest-user-agent/src/main/java/org/opensearch/ingest/useragent/UserAgentProcessor.java index 45d8ee60ae95c..c0711d3b05627 100644 --- a/modules/ingest-user-agent/src/main/java/org/opensearch/ingest/useragent/UserAgentProcessor.java +++ b/modules/ingest-user-agent/src/main/java/org/opensearch/ingest/useragent/UserAgentProcessor.java @@ -152,7 +152,7 @@ public IngestDocument execute(IngestDocument ingestDocument) { } } osDetails.put("version", sb.toString()); - osDetails.put("full", uaClient.operatingSystem.name + " " + sb.toString()); + osDetails.put("full", uaClient.operatingSystem.name + " " + sb); } uaDetails.put("os", osDetails); } diff --git a/modules/parent-join/src/main/java/org/opensearch/join/aggregations/ChildrenAggregatorFactory.java b/modules/parent-join/src/main/java/org/opensearch/join/aggregations/ChildrenAggregatorFactory.java index bbca89fc56820..2e7eff5d27129 100644 --- a/modules/parent-join/src/main/java/org/opensearch/join/aggregations/ChildrenAggregatorFactory.java +++ b/modules/parent-join/src/main/java/org/opensearch/join/aggregations/ChildrenAggregatorFactory.java @@ -94,7 +94,7 @@ protected Aggregator doCreateInternal( ValuesSource rawValuesSource = config.getValuesSource(); if (rawValuesSource instanceof WithOrdinals == false) { throw new AggregationExecutionException( - "ValuesSource type " + rawValuesSource.toString() + "is not supported for aggregation " + this.name() + "ValuesSource type " + rawValuesSource + "is not supported for aggregation " + this.name() ); } WithOrdinals valuesSource = (WithOrdinals) rawValuesSource; diff --git a/modules/parent-join/src/main/java/org/opensearch/join/aggregations/ParentAggregatorFactory.java b/modules/parent-join/src/main/java/org/opensearch/join/aggregations/ParentAggregatorFactory.java index 9a21cd1db3200..f9ca13ba9c802 100644 --- a/modules/parent-join/src/main/java/org/opensearch/join/aggregations/ParentAggregatorFactory.java +++ b/modules/parent-join/src/main/java/org/opensearch/join/aggregations/ParentAggregatorFactory.java @@ -94,7 +94,7 @@ protected Aggregator doCreateInternal( ValuesSource rawValuesSource = config.getValuesSource(); if (rawValuesSource instanceof WithOrdinals == false) { throw new AggregationExecutionException( - "ValuesSource type " + rawValuesSource.toString() + "is not supported for aggregation " + this.name() + "ValuesSource type " + rawValuesSource + "is not supported for aggregation " + this.name() ); } WithOrdinals valuesSource = (WithOrdinals) rawValuesSource; diff --git a/modules/parent-join/src/main/java/org/opensearch/join/mapper/ParentJoinFieldMapper.java b/modules/parent-join/src/main/java/org/opensearch/join/mapper/ParentJoinFieldMapper.java index a229d050f3b1d..69c83f73c50f4 100644 --- a/modules/parent-join/src/main/java/org/opensearch/join/mapper/ParentJoinFieldMapper.java +++ b/modules/parent-join/src/main/java/org/opensearch/join/mapper/ParentJoinFieldMapper.java @@ -142,7 +142,7 @@ private static void checkParentFields(String name, List map } } if (conflicts.isEmpty() == false) { - throw new IllegalArgumentException("invalid definition for join field [" + name + "]:\n" + conflicts.toString()); + throw new IllegalArgumentException("invalid definition for join field [" + name + "]:\n" + conflicts); } } diff --git a/modules/transport-grpc/build.gradle b/modules/transport-grpc/build.gradle index 6916a471535d9..21feb5c4748b7 100644 --- a/modules/transport-grpc/build.gradle +++ b/modules/transport-grpc/build.gradle @@ -24,7 +24,8 @@ dependencies { api project('spi') compileOnly "com.google.code.findbugs:jsr305:3.0.2" runtimeOnly "com.google.guava:guava:${versions.guava}" - implementation "com.google.errorprone:error_prone_annotations:2.24.1" + // implementation "com.google.errorprone:error_prone_annotations:${versions.errorprone}" todo: why bot working? + // implementation "com.google.errorprone:error_prone_annotations:2.42.0" implementation "com.google.guava:failureaccess:1.0.2" implementation "io.grpc:grpc-api:${versions.grpc}" implementation "io.grpc:grpc-core:${versions.grpc}" diff --git a/plugins/arrow-flight-rpc/build.gradle b/plugins/arrow-flight-rpc/build.gradle index 449f517b9b31d..249154ceb456c 100644 --- a/plugins/arrow-flight-rpc/build.gradle +++ b/plugins/arrow-flight-rpc/build.gradle @@ -27,7 +27,7 @@ dependencies { api "org.apache.arrow:arrow-vector:${versions.arrow}" api "org.apache.arrow:arrow-format:${versions.arrow}" - compileOnly 'org.checkerframework:checker-qual:3.44.0' + compileOnly 'org.checkerframework:checker-qual:3.51.1' api "com.google.flatbuffers:flatbuffers-java:${versions.flatbuffers}" api "org.slf4j:slf4j-api:${versions.slf4j}" api "com.fasterxml.jackson.core:jackson-core:${versions.jackson}" @@ -54,7 +54,7 @@ dependencies { runtimeOnly "io.grpc:grpc-core:${versions.grpc}" implementation "io.grpc:grpc-stub:${versions.grpc}" implementation "io.grpc:grpc-netty:${versions.grpc}" - implementation "com.google.errorprone:error_prone_annotations:2.31.0" + // implementation "com.google.errorprone:error_prone_annotations:2.42.0" runtimeOnly "com.google.code.findbugs:jsr305:3.0.2" annotationProcessor 'org.immutables:value:2.10.1' @@ -65,7 +65,7 @@ dependencies { runtimeOnly "io.grpc:grpc-protobuf:${versions.grpc}" runtimeOnly "com.google.guava:failureaccess:1.0.1" - runtimeOnly('com.google.guava:guava:33.3.1-jre') { + runtimeOnly("com.google.guava:guava:${versions.guava}") { attributes { attribute(Attribute.of('org.gradle.jvm.environment', String), 'standard-jvm') } diff --git a/plugins/arrow-flight-rpc/src/main/java/org/apache/arrow/flight/OSFlightClient.java b/plugins/arrow-flight-rpc/src/main/java/org/apache/arrow/flight/OSFlightClient.java index 0efafd370c651..4e6faa5d4c3cc 100644 --- a/plugins/arrow-flight-rpc/src/main/java/org/apache/arrow/flight/OSFlightClient.java +++ b/plugins/arrow-flight-rpc/src/main/java/org/apache/arrow/flight/OSFlightClient.java @@ -47,7 +47,7 @@ public final static class Builder { private ExecutorService executorService; private Class channelType; private SslContext sslContext; - + private Builder() {} Builder(BufferAllocator allocator, Location location) { @@ -131,7 +131,7 @@ public FlightClient build() { builder.channelType( Class.forName("io.netty.channel.epoll.EpollDomainSocketChannel") .asSubclass(ServerChannel.class)); - final EventLoopGroup elg = + final EventLoopGroup elg = Class.forName("io.netty.channel.epoll.EpollEventLoopGroup") .asSubclass(EventLoopGroup.class) .getDeclaredConstructor() @@ -142,7 +142,7 @@ public FlightClient build() { builder.channelType( Class.forName("io.netty.channel.kqueue.KQueueDomainSocketChannel") .asSubclass(ServerChannel.class)); - final EventLoopGroup elg = + final EventLoopGroup elg = Class.forName("io.netty.channel.kqueue.KQueueEventLoopGroup") .asSubclass(EventLoopGroup.class) .getDeclaredConstructor() @@ -179,7 +179,7 @@ public FlightClient build() { builder.sslContext(sslContext); } else { final SslContextBuilder sslContextBuilder = GrpcSslContexts.forClient(); - + if (!this.verifyServer) { sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE); } else if (this.trustedCertificates != null @@ -215,11 +215,11 @@ public FlightClient build() { if (channelType != null) { builder.channelType(channelType); } - + if (workerELG != null) { builder.eventLoopGroup(workerELG); } - + return new FlightClient(allocator, builder.build(), middleware); } @@ -232,7 +232,7 @@ public Builder channelType(Class channelType this.channelType = channelType; return this; } - + public Builder eventLoopGroup(EventLoopGroup workerELG) { this.workerELG = workerELG; return this; diff --git a/plugins/arrow-flight-rpc/src/main/java/org/apache/arrow/flight/OSFlightServer.java b/plugins/arrow-flight-rpc/src/main/java/org/apache/arrow/flight/OSFlightServer.java index 551c5a22754b9..002ed3e4fd1af 100644 --- a/plugins/arrow-flight-rpc/src/main/java/org/apache/arrow/flight/OSFlightServer.java +++ b/plugins/arrow-flight-rpc/src/main/java/org/apache/arrow/flight/OSFlightServer.java @@ -121,10 +121,10 @@ public FlightServer build() { this.middleware(FlightConstants.HEADER_KEY, new ServerHeaderMiddleware.Factory()); final NettyServerBuilder builder; - + // Use primary location for initial setup Location primaryLocation = location != null ? location : listenAddresses.get(0); - + switch (primaryLocation.getUri().getScheme()) { case LocationSchemes.GRPC_DOMAIN_SOCKET: { @@ -268,7 +268,7 @@ public FlightServer build() { builder.addListenAddress(listenAddress.toSocketAddress()); } } - + builder.intercept(new ServerInterceptorAdapter(interceptors)); try { @@ -472,7 +472,7 @@ public Builder location(Location location) { this.location = Preconditions.checkNotNull(location); return this; } - + public Builder addListenAddress(Location location) { this.listenAddresses.add(Preconditions.checkNotNull(location)); return this; diff --git a/plugins/repository-gcs/build.gradle b/plugins/repository-gcs/build.gradle index 6a0b369811f44..922ca7a87aa42 100644 --- a/plugins/repository-gcs/build.gradle +++ b/plugins/repository-gcs/build.gradle @@ -61,7 +61,7 @@ dependencies { runtimeOnly "com.google.guava:guava:${guava_version}" runtimeOnly "com.google.guava:failureaccess:1.0.2" - compileOnly "com.google.errorprone:error_prone_annotations:2.38.0" + // compileOnly "com.google.errorprone:error_prone_annotations:2.42.0" runtimeOnly "org.slf4j:slf4j-api:${versions.slf4j}" // 2.0.16 in bom runtimeOnly "commons-codec:commons-codec:${versions.commonscodec}" // 1.18.0 in bom @@ -87,7 +87,7 @@ dependencies { runtimeOnly "io.opencensus:opencensus-contrib-http-util:0.31.1" implementation "com.google.apis:google-api-services-storage:v1-rev20250718-2.0.0" - implementation "org.checkerframework:checker-qual:3.49.0" + implementation "org.checkerframework:checker-qual:3.51.1" runtimeOnly "io.opentelemetry:opentelemetry-api:1.47.0" runtimeOnly "io.opentelemetry:opentelemetry-context:1.47.0" diff --git a/qa/remote-clusters/build.gradle b/qa/remote-clusters/build.gradle index a68b970562fff..7ad4f0ce63640 100644 --- a/qa/remote-clusters/build.gradle +++ b/qa/remote-clusters/build.gradle @@ -54,8 +54,8 @@ opensearch_distributions { tasks.named("preProcessFixture").configure { dependsOn opensearch_distributions.docker // always run the task, otherwise the folders won't be created - outputs.upToDateWhen { - false + outputs.upToDateWhen { + false } doLast { // tests expect to have an empty repo diff --git a/qa/systemd-test/src/test/java/org/opensearch/systemdinteg/SystemdIntegTests.java b/qa/systemd-test/src/test/java/org/opensearch/systemdinteg/SystemdIntegTests.java index bc6c929bdf766..9ec9c80455b43 100644 --- a/qa/systemd-test/src/test/java/org/opensearch/systemdinteg/SystemdIntegTests.java +++ b/qa/systemd-test/src/test/java/org/opensearch/systemdinteg/SystemdIntegTests.java @@ -124,14 +124,14 @@ public void testReadWritePaths() throws IOException, InterruptedException { public void testMaxProcesses() throws IOException, InterruptedException { String limits = executeCommand("sudo su -c 'cat /proc/" + opensearchPid + "/limits'", "Failed to read process limits"); - assertTrue("Max processes limit should be 4096 or unlimited", + assertTrue("Max processes limit should be 4096 or unlimited", limits.contains("Max processes 4096 4096") || limits.contains("Max processes unlimited unlimited")); } public void testFileDescriptorLimit() throws IOException, InterruptedException { String limits = executeCommand("sudo su -c 'cat /proc/" + opensearchPid + "/limits'", "Failed to read process limits"); - assertTrue("File descriptor limit should be at least 65535", + assertTrue("File descriptor limit should be at least 65535", limits.contains("Max open files 65535 65535") || limits.contains("Max open files unlimited unlimited")); } diff --git a/rewrite.yml b/rewrite.yml new file mode 100644 index 0000000000000..5a673efd3702f --- /dev/null +++ b/rewrite.yml @@ -0,0 +1,69 @@ +--- +type: specs.openrewrite.org/v1beta/recipe +name: org.opensearch.openrewrite.SanityCheck +displayName: Apply all Java & Gradle best practices +description: Comprehensive code quality recipe combining modernization, security, and best practices. +tags: + - java + - gradle + - static-analysis + - cleanup +recipeList: + - org.openrewrite.gradle.EnableGradleBuildCache + - org.openrewrite.gradle.EnableGradleParallelExecution + - org.openrewrite.gradle.GradleBestPractices + - org.openrewrite.java.format.NormalizeLineBreaks + - org.openrewrite.java.format.RemoveTrailingWhitespace + - org.openrewrite.staticanalysis.RemoveUnusedPrivateMethods + # TBD + # - org.openrewrite.java.RemoveUnusedImports + # - org.openrewrite.java.format.NormalizeFormat + # - org.openrewrite.java.migrate.UpgradeToJava17 + # - org.openrewrite.java.migrate.lang.FindVirtualThreadOpportunities # don't want to use: https://github.com/diffplug/spotless/pull/2684#discussion_r2433831887 + # - org.openrewrite.java.migrate.lang.StringRulesRecipes + # - org.openrewrite.java.migrate.util.JavaLangAPIs + # - org.openrewrite.java.migrate.util.JavaUtilAPIs + # - org.openrewrite.java.migrate.util.MigrateInflaterDeflaterToClose + # - org.openrewrite.java.migrate.util.ReplaceStreamCollectWithToList + # - org.openrewrite.java.migrate.util.SequencedCollection + # - org.openrewrite.java.recipes.JavaRecipeBestPractices + # - org.openrewrite.java.recipes.RecipeTestingBestPractices + # - org.openrewrite.java.security.JavaSecurityBestPractices + # - org.openrewrite.staticanalysis.BufferedWriterCreationRecipes + # - org.openrewrite.staticanalysis.CommonStaticAnalysis + # - org.openrewrite.staticanalysis.EqualsAvoidsNull + # - org.openrewrite.staticanalysis.JavaApiBestPractices + # - org.openrewrite.staticanalysis.LowercasePackage + # - org.openrewrite.staticanalysis.MissingOverrideAnnotation + # - org.openrewrite.staticanalysis.ModifierOrder + # - org.openrewrite.staticanalysis.NoFinalizer + # - org.openrewrite.staticanalysis.NoToStringOnStringType + # - org.openrewrite.staticanalysis.NoValueOfOnStringType + # - org.openrewrite.staticanalysis.RemoveUnusedLocalVariables + # - org.openrewrite.staticanalysis.RemoveUnusedPrivateFields + # - org.openrewrite.staticanalysis.ReplaceApacheCommonsLang3ValidateNotNullWithObjectsRequireNonNull + # - org.openrewrite.staticanalysis.SimplifyTernaryRecipes + # - org.openrewrite.staticanalysis.URLEqualsHashCodeRecipes + # - org.openrewrite.staticanalysis.UnnecessaryCloseInTryWithResources + # - org.openrewrite.staticanalysis.UnnecessaryExplicitTypeArguments + # - org.openrewrite.staticanalysis.UnnecessaryParentheses + # - org.openrewrite.staticanalysis.UnnecessaryReturnAsLastStatement + # - tech.picnic.errorprone.refasterrules.BigDecimalRulesRecipes + # - tech.picnic.errorprone.refasterrules.CharSequenceRulesRecipes + # - tech.picnic.errorprone.refasterrules.ClassRulesRecipes + # - tech.picnic.errorprone.refasterrules.CollectionRulesRecipes + # - tech.picnic.errorprone.refasterrules.ComparatorRulesRecipes + # - tech.picnic.errorprone.refasterrules.EqualityRulesRecipes + # - tech.picnic.errorprone.refasterrules.FileRulesRecipes + # - tech.picnic.errorprone.refasterrules.MapRulesRecipes + # - tech.picnic.errorprone.refasterrules.MicrometerRulesRecipes + # - tech.picnic.errorprone.refasterrules.MockitoRulesRecipes + # - tech.picnic.errorprone.refasterrules.NullRulesRecipes + # - tech.picnic.errorprone.refasterrules.OptionalRulesRecipes + # - tech.picnic.errorprone.refasterrules.PatternRulesRecipes + # - tech.picnic.errorprone.refasterrules.PreconditionsRulesRecipes + # - tech.picnic.errorprone.refasterrules.PrimitiveRulesRecipes + # - tech.picnic.errorprone.refasterrules.StreamRulesRecipes + # - tech.picnic.errorprone.refasterrules.StringRulesRecipes + # - tech.picnic.errorprone.refasterrules.TimeRulesRecipes +--- diff --git a/server/src/main/java/org/opensearch/action/admin/cluster/shards/routing/weighted/put/ClusterPutWeightedRoutingRequest.java b/server/src/main/java/org/opensearch/action/admin/cluster/shards/routing/weighted/put/ClusterPutWeightedRoutingRequest.java index c310e28610184..a816351a47a26 100644 --- a/server/src/main/java/org/opensearch/action/admin/cluster/shards/routing/weighted/put/ClusterPutWeightedRoutingRequest.java +++ b/server/src/main/java/org/opensearch/action/admin/cluster/shards/routing/weighted/put/ClusterPutWeightedRoutingRequest.java @@ -200,7 +200,7 @@ public ActionRequestValidationException validate() { (String.format( Locale.ROOT, "There are too many attribute values [%s] given zero weight [%d]. Maximum expected number of routing weights having zero weight is [%d]", - weightedRouting.weights().toString(), + weightedRouting.weights(), countValueWithZeroWeights, weightedRouting.weights().size() / 2 )), @@ -228,7 +228,7 @@ public void writeTo(StreamOutput out) throws IOException { @Override public String toString() { - return "ClusterPutWeightedRoutingRequest{" + "weightedRouting= " + weightedRouting.toString() + "version= " + version + "}"; + return "ClusterPutWeightedRoutingRequest{" + "weightedRouting= " + weightedRouting + "version= " + version + "}"; } } diff --git a/server/src/main/java/org/opensearch/action/index/IndexRequest.java b/server/src/main/java/org/opensearch/action/index/IndexRequest.java index 5c97b625b5269..7827030a583c9 100644 --- a/server/src/main/java/org/opensearch/action/index/IndexRequest.java +++ b/server/src/main/java/org/opensearch/action/index/IndexRequest.java @@ -714,9 +714,9 @@ public String toString() { try { if (source.length() > MAX_SOURCE_LENGTH_IN_TOSTRING) { sSource = "n/a, actual length: [" - + new ByteSizeValue(source.length()).toString() + + new ByteSizeValue(source.length()) + "], max length: " - + new ByteSizeValue(MAX_SOURCE_LENGTH_IN_TOSTRING).toString(); + + new ByteSizeValue(MAX_SOURCE_LENGTH_IN_TOSTRING); } else { sSource = XContentHelper.convertToJson(source, false); } diff --git a/server/src/main/java/org/opensearch/action/search/SearchRequestContext.java b/server/src/main/java/org/opensearch/action/search/SearchRequestContext.java index 398896734280e..3c087378925e8 100644 --- a/server/src/main/java/org/opensearch/action/search/SearchRequestContext.java +++ b/server/src/main/java/org/opensearch/action/search/SearchRequestContext.java @@ -115,13 +115,13 @@ String formattedShardStats() { return String.format( Locale.ROOT, "{%s:%s, %s:%s, %s:%s, %s:%s}", - ShardStatsFieldNames.SEARCH_REQUEST_SLOWLOG_SHARD_TOTAL.toString(), + ShardStatsFieldNames.SEARCH_REQUEST_SLOWLOG_SHARD_TOTAL, shardStats.get(ShardStatsFieldNames.SEARCH_REQUEST_SLOWLOG_SHARD_TOTAL), - ShardStatsFieldNames.SEARCH_REQUEST_SLOWLOG_SHARD_SUCCESSFUL.toString(), + ShardStatsFieldNames.SEARCH_REQUEST_SLOWLOG_SHARD_SUCCESSFUL, shardStats.get(ShardStatsFieldNames.SEARCH_REQUEST_SLOWLOG_SHARD_SUCCESSFUL), - ShardStatsFieldNames.SEARCH_REQUEST_SLOWLOG_SHARD_SKIPPED.toString(), + ShardStatsFieldNames.SEARCH_REQUEST_SLOWLOG_SHARD_SKIPPED, shardStats.get(ShardStatsFieldNames.SEARCH_REQUEST_SLOWLOG_SHARD_SKIPPED), - ShardStatsFieldNames.SEARCH_REQUEST_SLOWLOG_SHARD_FAILED.toString(), + ShardStatsFieldNames.SEARCH_REQUEST_SLOWLOG_SHARD_FAILED, shardStats.get(ShardStatsFieldNames.SEARCH_REQUEST_SLOWLOG_SHARD_FAILED) ); } diff --git a/server/src/main/java/org/opensearch/action/search/SearchRequestSlowLog.java b/server/src/main/java/org/opensearch/action/search/SearchRequestSlowLog.java index a9a07c6aca7f4..861a15c2edb76 100644 --- a/server/src/main/java/org/opensearch/action/search/SearchRequestSlowLog.java +++ b/server/src/main/java/org/opensearch/action/search/SearchRequestSlowLog.java @@ -204,7 +204,7 @@ private static String message(SearchPhaseContext context, long tookInNanos, Sear final StringBuilder sb = new StringBuilder(); sb.append("took[").append(TimeValue.timeValueNanos(tookInNanos)).append("], "); sb.append("took_millis[").append(TimeUnit.NANOSECONDS.toMillis(tookInNanos)).append("], "); - sb.append("phase_took_millis[").append(searchRequestContext.phaseTookMap().toString()).append("], "); + sb.append("phase_took_millis[").append(searchRequestContext.phaseTookMap()).append("], "); if (searchRequestContext.totalHits() != null) { sb.append("total_hits[").append(searchRequestContext.totalHits()).append("], "); } else { diff --git a/server/src/main/java/org/opensearch/action/support/ContextPreservingActionListener.java b/server/src/main/java/org/opensearch/action/support/ContextPreservingActionListener.java index a59c7fb45ca27..65bd4a205d9d8 100644 --- a/server/src/main/java/org/opensearch/action/support/ContextPreservingActionListener.java +++ b/server/src/main/java/org/opensearch/action/support/ContextPreservingActionListener.java @@ -68,7 +68,7 @@ public void onFailure(Exception e) { @Override public String toString() { - return getClass().getName() + "/" + delegate.toString(); + return getClass().getName() + "/" + delegate; } /** diff --git a/server/src/main/java/org/opensearch/action/support/broadcast/node/TransportBroadcastByNodeAction.java b/server/src/main/java/org/opensearch/action/support/broadcast/node/TransportBroadcastByNodeAction.java index 379e46377ec66..4ad08ea3dd687 100644 --- a/server/src/main/java/org/opensearch/action/support/broadcast/node/TransportBroadcastByNodeAction.java +++ b/server/src/main/java/org/opensearch/action/support/broadcast/node/TransportBroadcastByNodeAction.java @@ -348,7 +348,7 @@ protected AsyncAction(Task task, Request request, ActionListener liste unavailableShardExceptions.add( new NoShardAvailableActionException( shard.shardId(), - " no shards available for shard " + shard.toString() + " while executing " + actionName + " no shards available for shard " + shard + " while executing " + actionName ) ); } diff --git a/server/src/main/java/org/opensearch/bootstrap/FilePermissionUtils.java b/server/src/main/java/org/opensearch/bootstrap/FilePermissionUtils.java index 18ff013b1e8cb..31c6fee0a3fc9 100644 --- a/server/src/main/java/org/opensearch/bootstrap/FilePermissionUtils.java +++ b/server/src/main/java/org/opensearch/bootstrap/FilePermissionUtils.java @@ -101,7 +101,7 @@ public static void addDirectoryPath( // add access for path itself policy.add(new FilePermission(path.toString(), permissions)); } - policy.add(new FilePermission(path.toString() + path.getFileSystem().getSeparator() + "-", permissions)); + policy.add(new FilePermission(path + path.getFileSystem().getSeparator() + "-", permissions)); /* * The file permission model since JDK 9 requires this due to the removal of pathname canonicalization. See also * https://github.com/elastic/elasticsearch/issues/21534. @@ -113,7 +113,7 @@ public static void addDirectoryPath( policy.add(new FilePermission(realPath.toString(), permissions)); } // add access for files underneath - policy.add(new FilePermission(realPath.toString() + realPath.getFileSystem().getSeparator() + "-", permissions)); + policy.add(new FilePermission(realPath + realPath.getFileSystem().getSeparator() + "-", permissions)); } } } diff --git a/server/src/main/java/org/opensearch/bootstrap/Security.java b/server/src/main/java/org/opensearch/bootstrap/Security.java index a8652dffa6910..a2d7725e87540 100644 --- a/server/src/main/java/org/opensearch/bootstrap/Security.java +++ b/server/src/main/java/org/opensearch/bootstrap/Security.java @@ -303,16 +303,14 @@ private static void addCodebaseToSystemProperties(List propertiesSet, fi String previous = System.setProperty(aliasProperty, url.toString()); if (previous != null) { throw new IllegalStateException( - "codebase property already set: " + aliasProperty + " -> " + previous + ", cannot set to " + url.toString() + "codebase property already set: " + aliasProperty + " -> " + previous + ", cannot set to " + url ); } } propertiesSet.add(property); String previous = System.setProperty(property, url.toString()); if (previous != null) { - throw new IllegalStateException( - "codebase property already set: " + property + " -> " + previous + ", cannot set to " + url.toString() - ); + throw new IllegalStateException("codebase property already set: " + property + " -> " + previous + ", cannot set to " + url); } } diff --git a/server/src/main/java/org/opensearch/cluster/ClusterInfo.java b/server/src/main/java/org/opensearch/cluster/ClusterInfo.java index fd20ff5e77b83..dde9bee61eb33 100644 --- a/server/src/main/java/org/opensearch/cluster/ClusterInfo.java +++ b/server/src/main/java/org/opensearch/cluster/ClusterInfo.java @@ -330,7 +330,7 @@ public ReservedSpace getReservedSpace(String nodeId, String dataPath) { * includes a 'p' or 'r' depending on whether the shard is a primary. */ static String shardIdentifierFromRouting(ShardRouting shardRouting) { - return shardRouting.shardId().toString() + "[" + (shardRouting.primary() ? "p" : "r") + "]"; + return shardRouting.shardId() + "[" + (shardRouting.primary() ? "p" : "r") + "]"; } /** diff --git a/server/src/main/java/org/opensearch/cluster/decommission/DecommissionService.java b/server/src/main/java/org/opensearch/cluster/decommission/DecommissionService.java index 7ff894afa21a7..6422273478f83 100644 --- a/server/src/main/java/org/opensearch/cluster/decommission/DecommissionService.java +++ b/server/src/main/java/org/opensearch/cluster/decommission/DecommissionService.java @@ -259,7 +259,7 @@ public void onNewClusterState(ClusterState state) { listener.onFailure( new NotClusterManagerException( "node [" - + transportService.getLocalNode().toString() + + transportService.getLocalNode() + "] not eligible to execute decommission request. Will retry until timeout." ) ); @@ -276,9 +276,9 @@ public void onClusterServiceClose() { @Override public void onTimeout(TimeValue timeout) { String errorMsg = "timed out [" - + timeout.toString() + + timeout + "] while removing to-be-decommissioned cluster manager eligible nodes [" - + nodeIdsToBeExcluded.toString() + + nodeIdsToBeExcluded + "] from voting config"; logger.error(errorMsg); listener.onFailure(new OpenSearchTimeoutException(errorMsg)); @@ -424,7 +424,7 @@ private static void validateAwarenessAttribute( } else if (awarenessAttributes.contains(decommissionAttribute.attributeName()) == false) { msg = "invalid awareness attribute requested for decommissioning"; } else if (forcedAwarenessAttributes.containsKey(decommissionAttribute.attributeName()) == false) { - msg = "forced awareness attribute [" + forcedAwarenessAttributes.toString() + "] doesn't have the decommissioning attribute"; + msg = "forced awareness attribute [" + forcedAwarenessAttributes + "] doesn't have the decommissioning attribute"; } // we don't need to check for attributes presence in forced awareness attribute because, weights API ensures that weights are set // for all discovered routing attributes and forced attributes. @@ -501,7 +501,7 @@ private static void ensureEligibleRequest( case SUCCESSFUL: // one awareness attribute is already decommissioned. We will reject the new request msg = "one awareness attribute [" - + decommissionAttributeMetadata.decommissionAttribute().toString() + + decommissionAttributeMetadata.decommissionAttribute() + "] already successfully decommissioned, recommission before triggering another decommission"; throw new DecommissioningFailedException(requestedDecommissionAttribute, msg); case DRAINING: @@ -509,7 +509,7 @@ private static void ensureEligibleRequest( case INIT: // it means the decommission has been initiated or is inflight. In that case, will fail new request msg = "there's an inflight decommission request for attribute [" - + decommissionAttributeMetadata.decommissionAttribute().toString() + + decommissionAttributeMetadata.decommissionAttribute() + "] is in progress, cannot process this request"; throw new DecommissioningFailedException(requestedDecommissionAttribute, msg); case FAILED: diff --git a/server/src/main/java/org/opensearch/cluster/node/DiscoveryNodeFilters.java b/server/src/main/java/org/opensearch/cluster/node/DiscoveryNodeFilters.java index fa63180fb1547..e7f971c7dccac 100644 --- a/server/src/main/java/org/opensearch/cluster/node/DiscoveryNodeFilters.java +++ b/server/src/main/java/org/opensearch/cluster/node/DiscoveryNodeFilters.java @@ -294,7 +294,7 @@ public String toString() { for (String value : values) { sb.append(value); if (valueCount > 1) { - sb.append(" ").append(opType.toString()).append(" "); + sb.append(" ").append(opType).append(" "); } valueCount--; } diff --git a/server/src/main/java/org/opensearch/cluster/routing/ShardRouting.java b/server/src/main/java/org/opensearch/cluster/routing/ShardRouting.java index 81558d00aa697..18d5398ba8d1b 100644 --- a/server/src/main/java/org/opensearch/cluster/routing/ShardRouting.java +++ b/server/src/main/java/org/opensearch/cluster/routing/ShardRouting.java @@ -900,7 +900,7 @@ public String shortSummary() { sb.append(", a").append(allocationId); } if (this.unassignedInfo != null) { - sb.append(", ").append(unassignedInfo.toString()); + sb.append(", ").append(unassignedInfo); } if (expectedShardSize != UNAVAILABLE_EXPECTED_SHARD_SIZE) { sb.append(", expected_shard_size[").append(expectedShardSize).append("]"); diff --git a/server/src/main/java/org/opensearch/cluster/routing/WeightedRouting.java b/server/src/main/java/org/opensearch/cluster/routing/WeightedRouting.java index 6f0e4fe90cfff..663c9a3fba43b 100644 --- a/server/src/main/java/org/opensearch/cluster/routing/WeightedRouting.java +++ b/server/src/main/java/org/opensearch/cluster/routing/WeightedRouting.java @@ -75,7 +75,7 @@ public int hashCode() { @Override public String toString() { - return "WeightedRouting{" + attributeName + "}{" + weights().toString() + "}"; + return "WeightedRouting{" + attributeName + "}{" + weights() + "}"; } public Map weights() { diff --git a/server/src/main/java/org/opensearch/cluster/routing/WeightedRoutingService.java b/server/src/main/java/org/opensearch/cluster/routing/WeightedRoutingService.java index c613a630806dd..8259ed06d3488 100644 --- a/server/src/main/java/org/opensearch/cluster/routing/WeightedRoutingService.java +++ b/server/src/main/java/org/opensearch/cluster/routing/WeightedRoutingService.java @@ -242,7 +242,7 @@ private void ensureWeightsSetForAllDiscoveredAndForcedAwarenessValues(ClusterSta (String.format( Locale.ROOT, "There are too many discovered attribute values [%s] given zero weight [%d]. Maximum expected number of routing weights having zero weight is [%d]", - request.getWeightedRouting().weights().toString(), + request.getWeightedRouting().weights(), countWithZeroWeight.get(), allAwarenessValues.size() / 2 )), diff --git a/server/src/main/java/org/opensearch/cluster/routing/allocation/decider/Decision.java b/server/src/main/java/org/opensearch/cluster/routing/allocation/decider/Decision.java index 938c457606c79..292604478961e 100644 --- a/server/src/main/java/org/opensearch/cluster/routing/allocation/decider/Decision.java +++ b/server/src/main/java/org/opensearch/cluster/routing/allocation/decider/Decision.java @@ -367,7 +367,7 @@ public int hashCode() { public String toString() { StringBuilder sb = new StringBuilder(); for (Decision decision : decisions) { - sb.append("[").append(decision.toString()).append("]"); + sb.append("[").append(decision).append("]"); } return sb.toString(); } diff --git a/server/src/main/java/org/opensearch/cluster/routing/remote/InternalRemoteRoutingTableService.java b/server/src/main/java/org/opensearch/cluster/routing/remote/InternalRemoteRoutingTableService.java index eafbe05faf76f..00e5cfd36e418 100644 --- a/server/src/main/java/org/opensearch/cluster/routing/remote/InternalRemoteRoutingTableService.java +++ b/server/src/main/java/org/opensearch/cluster/routing/remote/InternalRemoteRoutingTableService.java @@ -122,7 +122,7 @@ public void getAsyncIndexRoutingWriteAction( ActionListener completionListener = ActionListener.wrap( resp -> latchedActionListener.onResponse(remoteIndexRoutingTable.getUploadedMetadata()), ex -> latchedActionListener.onFailure( - new RemoteStateTransferException("Exception in writing index to remote store: " + indexRouting.getIndex().toString(), ex) + new RemoteStateTransferException("Exception in writing index to remote store: " + indexRouting.getIndex(), ex) ) ); diff --git a/server/src/main/java/org/opensearch/common/Rounding.java b/server/src/main/java/org/opensearch/common/Rounding.java index 4a7fed99fabe8..d6b7dc902435f 100644 --- a/server/src/main/java/org/opensearch/common/Rounding.java +++ b/server/src/main/java/org/opensearch/common/Rounding.java @@ -1230,7 +1230,7 @@ public long nextRoundingValue(long utcMillis) { Locale.ROOT, "Expected to find the rounding in 100 iterations but didn't for [%d] with [%s]", utcMillis, - TimeIntervalRounding.this.toString() + TimeIntervalRounding.this ); logger.debug( "Expected to find the rounding in 100 iterations but didn't for {} using {}", diff --git a/server/src/main/java/org/opensearch/common/inject/assistedinject/Parameter.java b/server/src/main/java/org/opensearch/common/inject/assistedinject/Parameter.java index 960fc079e6438..71e707015edaa 100644 --- a/server/src/main/java/org/opensearch/common/inject/assistedinject/Parameter.java +++ b/server/src/main/java/org/opensearch/common/inject/assistedinject/Parameter.java @@ -76,10 +76,10 @@ public String toString() { result.append(" "); } if (bindingAnnotation != null) { - result.append(bindingAnnotation.toString()); + result.append(bindingAnnotation); result.append(" "); } - result.append(type.toString()); + result.append(type); return result.toString(); } diff --git a/server/src/main/java/org/opensearch/common/logging/HeaderWarning.java b/server/src/main/java/org/opensearch/common/logging/HeaderWarning.java index c027ba1d1b9d5..3ce871b5e5de6 100644 --- a/server/src/main/java/org/opensearch/common/logging/HeaderWarning.java +++ b/server/src/main/java/org/opensearch/common/logging/HeaderWarning.java @@ -86,7 +86,7 @@ public class HeaderWarning { private static final String WARNING_PREFIX = String.format( Locale.ROOT, "299 OpenSearch-%s%s-%s", - Version.CURRENT.toString(), + Version.CURRENT, Build.CURRENT.isSnapshot() ? "-SNAPSHOT" : "", Build.CURRENT.hash() ); diff --git a/server/src/main/java/org/opensearch/common/logging/OpenSearchJsonLayout.java b/server/src/main/java/org/opensearch/common/logging/OpenSearchJsonLayout.java index 60df94036cc6b..1c2c1a9739543 100644 --- a/server/src/main/java/org/opensearch/common/logging/OpenSearchJsonLayout.java +++ b/server/src/main/java/org/opensearch/common/logging/OpenSearchJsonLayout.java @@ -120,7 +120,7 @@ private String pattern(String type, String[] opensearchMessageFields, int maxMes if (maxMessageLength < 0) { throw new IllegalArgumentException("layout parameter 'maxmessagelength' cannot be a negative number"); } else if (maxMessageLength > 0) { - messageFormat = "%.-" + Integer.toString(maxMessageLength) + "m"; + messageFormat = "%.-" + maxMessageLength + "m"; } Map map = new LinkedHashMap<>(); @@ -166,7 +166,7 @@ private String createPattern(Map map, Set opensearchMess private void appendField(StringBuilder sb, Map.Entry entry) { sb.append(jsonKey(entry.getKey())); - sb.append(entry.getValue().toString()); + sb.append(entry.getValue()); } private String notEmpty(String value) { diff --git a/server/src/main/java/org/opensearch/common/lucene/search/SpanBooleanQueryRewriteWithMaxClause.java b/server/src/main/java/org/opensearch/common/lucene/search/SpanBooleanQueryRewriteWithMaxClause.java index 6bafd50420edc..1e034f08f7cd3 100644 --- a/server/src/main/java/org/opensearch/common/lucene/search/SpanBooleanQueryRewriteWithMaxClause.java +++ b/server/src/main/java/org/opensearch/common/lucene/search/SpanBooleanQueryRewriteWithMaxClause.java @@ -90,7 +90,7 @@ public SpanQuery rewrite(IndexSearcher searcher, MultiTermQuery query) throws IO public Query rewrite(IndexSearcher searcher, MultiTermQuery query) throws IOException { Collection queries = collectTerms(searcher.getIndexReader(), query); if (queries.size() == 0) { - return new SpanMatchNoDocsQuery(query.getField(), "no expansion found for " + query.toString()); + return new SpanMatchNoDocsQuery(query.getField(), "no expansion found for " + query); } else if (queries.size() == 1) { return queries.iterator().next(); } else { @@ -121,7 +121,7 @@ private Collection collectTerms(IndexReader reader, MultiTermQuery qu if (hardLimit) { throw new RuntimeException( "[" - + query.toString() + + query + " ] " + "exceeds maxClauseCount [ Boolean maxClauseCount is set to " + IndexSearcher.getMaxClauseCount() diff --git a/server/src/main/java/org/opensearch/common/lucene/search/function/FunctionScoreQuery.java b/server/src/main/java/org/opensearch/common/lucene/search/function/FunctionScoreQuery.java index 4e6ddc0375130..d2655970c1d99 100644 --- a/server/src/main/java/org/opensearch/common/lucene/search/function/FunctionScoreQuery.java +++ b/server/src/main/java/org/opensearch/common/lucene/search/function/FunctionScoreQuery.java @@ -456,7 +456,7 @@ public Explanation explain(LeafReaderContext context, int doc) throws IOExceptio "function score, product of:", Explanation.match( 1.0f, - "match filter" + Functions.nameOrEmptyFunc(filterScoreFunction.queryName) + ": " + filterQuery.toString() + "match filter" + Functions.nameOrEmptyFunc(filterScoreFunction.queryName) + ": " + filterQuery ), functionExplanation ); diff --git a/server/src/main/java/org/opensearch/common/lucene/search/function/ScriptScoreFunction.java b/server/src/main/java/org/opensearch/common/lucene/search/function/ScriptScoreFunction.java index 54299e15de92a..1c2be74746b56 100644 --- a/server/src/main/java/org/opensearch/common/lucene/search/function/ScriptScoreFunction.java +++ b/server/src/main/java/org/opensearch/common/lucene/search/function/ScriptScoreFunction.java @@ -136,7 +136,7 @@ public boolean needsScores() { @Override public String toString() { - return "script" + sScript.toString(); + return "script" + sScript; } @Override diff --git a/server/src/main/java/org/opensearch/common/lucene/search/function/ScriptScoreQuery.java b/server/src/main/java/org/opensearch/common/lucene/search/function/ScriptScoreQuery.java index 6a2b7ded93b4f..5b37c573c676c 100644 --- a/server/src/main/java/org/opensearch/common/lucene/search/function/ScriptScoreQuery.java +++ b/server/src/main/java/org/opensearch/common/lucene/search/function/ScriptScoreQuery.java @@ -268,7 +268,7 @@ public String toString(String field) { StringBuilder sb = new StringBuilder(); sb.append("script_score (").append(subQuery.toString(field)); sb.append(Functions.nameOrEmptyArg(queryName)).append(", script: "); - sb.append("{" + script.toString() + "}"); + sb.append("{" + script + "}"); return sb.toString(); } diff --git a/server/src/main/java/org/opensearch/common/settings/AbstractScopedSettings.java b/server/src/main/java/org/opensearch/common/settings/AbstractScopedSettings.java index 8c10623e48fe4..247686c9178a0 100644 --- a/server/src/main/java/org/opensearch/common/settings/AbstractScopedSettings.java +++ b/server/src/main/java/org/opensearch/common/settings/AbstractScopedSettings.java @@ -598,7 +598,7 @@ void validate( String msg = msgPrefix + " [" + key + "]"; List keys = scoredKeys.stream().map((a) -> a.v2()).collect(Collectors.toList()); if (keys.isEmpty() == false) { - msg += " did you mean " + (keys.size() == 1 ? "[" + keys.get(0) + "]" : "any of " + keys.toString()) + "?"; + msg += " did you mean " + (keys.size() == 1 ? "[" + keys.get(0) + "]" : "any of " + keys) + "?"; } else { msg += " please check that any required plugins are installed, or check the breaking changes documentation for removed " + "settings"; @@ -739,7 +739,7 @@ private boolean assertMatcher(String key, int numComplexMatchers) { + " complex matchers to match key [" + key + "] but got: " - + list.toString(); + + list; return true; } diff --git a/server/src/main/java/org/opensearch/common/settings/Setting.java b/server/src/main/java/org/opensearch/common/settings/Setting.java index eb63522270e87..5c301158263dc 100644 --- a/server/src/main/java/org/opensearch/common/settings/Setting.java +++ b/server/src/main/java/org/opensearch/common/settings/Setting.java @@ -1212,7 +1212,7 @@ public void apply(Settings value, Settings current, Settings previous) { @Override public String toString() { - return "Updater for: " + setting.toString(); + return "Updater for: " + setting; } }; } @@ -1231,7 +1231,7 @@ private final class Updater implements AbstractScopedSettings.SettingUpdater @Override public String toString() { - return "Updater for: " + Setting.this.toString(); + return "Updater for: " + Setting.this; } @Override diff --git a/server/src/main/java/org/opensearch/common/time/EpochTime.java b/server/src/main/java/org/opensearch/common/time/EpochTime.java index 90fea84caa87c..01dc34d4d9d37 100644 --- a/server/src/main/java/org/opensearch/common/time/EpochTime.java +++ b/server/src/main/java/org/opensearch/common/time/EpochTime.java @@ -378,7 +378,7 @@ public String getDisplayName(Locale locale) { @Override public String toString() { - return "Epoch" + baseUnit.toString() + (rangeUnit != ChronoUnit.FOREVER ? "Of" + rangeUnit.toString() : ""); + return "Epoch" + baseUnit + (rangeUnit != ChronoUnit.FOREVER ? "Of" + rangeUnit : ""); } @Override diff --git a/server/src/main/java/org/opensearch/common/xcontent/SuggestingErrorOnUnknown.java b/server/src/main/java/org/opensearch/common/xcontent/SuggestingErrorOnUnknown.java index 1e90d21063d37..4a9b5bcd81f52 100644 --- a/server/src/main/java/org/opensearch/common/xcontent/SuggestingErrorOnUnknown.java +++ b/server/src/main/java/org/opensearch/common/xcontent/SuggestingErrorOnUnknown.java @@ -89,7 +89,7 @@ public static String suggest(String unknownField, Iterable candidates) { if (keys.size() == 1) { builder.append("[").append(keys.get(0)).append("]"); } else { - builder.append("any of ").append(keys.toString()); + builder.append("any of ").append(keys); } builder.append("?"); return builder.toString(); diff --git a/server/src/main/java/org/opensearch/env/EnvironmentSettingsResponse.java b/server/src/main/java/org/opensearch/env/EnvironmentSettingsResponse.java index eb115ee927d68..d5316fb88a680 100644 --- a/server/src/main/java/org/opensearch/env/EnvironmentSettingsResponse.java +++ b/server/src/main/java/org/opensearch/env/EnvironmentSettingsResponse.java @@ -43,7 +43,7 @@ public Settings getEnvironmentSettings() { @Override public String toString() { - return "EnvironmentSettingsResponse{environmentSettings=" + environmentSettings.toString() + '}'; + return "EnvironmentSettingsResponse{environmentSettings=" + environmentSettings + '}'; } @Override diff --git a/server/src/main/java/org/opensearch/env/NodeRepurposeCommand.java b/server/src/main/java/org/opensearch/env/NodeRepurposeCommand.java index 2712e5ab0b386..df9e1455a768a 100644 --- a/server/src/main/java/org/opensearch/env/NodeRepurposeCommand.java +++ b/server/src/main/java/org/opensearch/env/NodeRepurposeCommand.java @@ -287,7 +287,7 @@ private ClusterState loadClusterState(Terminal terminal, Environment env, Persis private void outputVerboseInformation(Terminal terminal, Collection pathsToCleanup, Set indexUUIDs, Metadata metadata) { if (terminal.isPrintable(Terminal.Verbosity.VERBOSE)) { terminal.println(Terminal.Verbosity.VERBOSE, "Paths to clean up:"); - pathsToCleanup.forEach(p -> terminal.println(Terminal.Verbosity.VERBOSE, " " + p.toString())); + pathsToCleanup.forEach(p -> terminal.println(Terminal.Verbosity.VERBOSE, " " + p)); terminal.println(Terminal.Verbosity.VERBOSE, "Indices affected:"); indexUUIDs.forEach(uuid -> terminal.println(Terminal.Verbosity.VERBOSE, " " + toIndexName(uuid, metadata))); } diff --git a/server/src/main/java/org/opensearch/env/ShardLockObtainFailedException.java b/server/src/main/java/org/opensearch/env/ShardLockObtainFailedException.java index ae77d942356b5..134286a769996 100644 --- a/server/src/main/java/org/opensearch/env/ShardLockObtainFailedException.java +++ b/server/src/main/java/org/opensearch/env/ShardLockObtainFailedException.java @@ -63,7 +63,7 @@ public ShardLockObtainFailedException(StreamInput in) throws IOException { private static String buildMessage(ShardId shardId, String message) { StringBuilder sb = new StringBuilder(); - sb.append(shardId.toString()); + sb.append(shardId); sb.append(": "); sb.append(message); return sb.toString(); diff --git a/server/src/main/java/org/opensearch/extensions/AddSettingsUpdateConsumerRequest.java b/server/src/main/java/org/opensearch/extensions/AddSettingsUpdateConsumerRequest.java index 24984a3800819..f20a29ad5c4d3 100644 --- a/server/src/main/java/org/opensearch/extensions/AddSettingsUpdateConsumerRequest.java +++ b/server/src/main/java/org/opensearch/extensions/AddSettingsUpdateConsumerRequest.java @@ -74,7 +74,7 @@ public DiscoveryExtensionNode getExtensionNode() { @Override public String toString() { - return "AddSettingsUpdateConsumerRequest{extensionNode=" + this.extensionNode.toString() + "}"; + return "AddSettingsUpdateConsumerRequest{extensionNode=" + this.extensionNode + "}"; } @Override diff --git a/server/src/main/java/org/opensearch/extensions/ExtensionDependencyResponse.java b/server/src/main/java/org/opensearch/extensions/ExtensionDependencyResponse.java index 4706d1821ffa9..b67ffd822a551 100644 --- a/server/src/main/java/org/opensearch/extensions/ExtensionDependencyResponse.java +++ b/server/src/main/java/org/opensearch/extensions/ExtensionDependencyResponse.java @@ -52,7 +52,7 @@ public List getExtensionDependency() { @Override public String toString() { - return "ExtensionDependencyResponse{extensiondependency=" + extensionDependencies.toString() + '}'; + return "ExtensionDependencyResponse{extensiondependency=" + extensionDependencies + '}'; } @Override diff --git a/server/src/main/java/org/opensearch/extensions/ExtensionRequest.java b/server/src/main/java/org/opensearch/extensions/ExtensionRequest.java index 19424e5213151..ce62716be5413 100644 --- a/server/src/main/java/org/opensearch/extensions/ExtensionRequest.java +++ b/server/src/main/java/org/opensearch/extensions/ExtensionRequest.java @@ -61,7 +61,7 @@ public String getUniqueId() { } public String toString() { - return "ExtensionRequest{" + request.toString() + '}'; + return "ExtensionRequest{" + request + '}'; } public ExtensionIdentityProto.ExtensionIdentity getExtensionIdentity() { diff --git a/server/src/main/java/org/opensearch/extensions/UpdateSettingsRequest.java b/server/src/main/java/org/opensearch/extensions/UpdateSettingsRequest.java index 0295269b1787f..ab8c6b71c0ccd 100644 --- a/server/src/main/java/org/opensearch/extensions/UpdateSettingsRequest.java +++ b/server/src/main/java/org/opensearch/extensions/UpdateSettingsRequest.java @@ -67,11 +67,11 @@ public Object getData() { @Override public String toString() { return "UpdateSettingRequest{settingType=" - + this.settingType.toString() + + this.settingType + "componentSetting=" - + this.componentSetting.toString() + + this.componentSetting + ", data=" - + this.data.toString() + + this.data + "}"; } diff --git a/server/src/main/java/org/opensearch/extensions/rest/ExtensionRestRequest.java b/server/src/main/java/org/opensearch/extensions/rest/ExtensionRestRequest.java index 89df1e4fbde35..88b9953fadd42 100644 --- a/server/src/main/java/org/opensearch/extensions/rest/ExtensionRestRequest.java +++ b/server/src/main/java/org/opensearch/extensions/rest/ExtensionRestRequest.java @@ -324,7 +324,7 @@ public String toString() { + ", params=" + params + ", headers=" - + headers.toString() + + headers + ", xContentType=" + mediaType + ", contentLength=" diff --git a/server/src/main/java/org/opensearch/gateway/AsyncShardFetch.java b/server/src/main/java/org/opensearch/gateway/AsyncShardFetch.java index 6017743ef2bd0..1651a181a8aa8 100644 --- a/server/src/main/java/org/opensearch/gateway/AsyncShardFetch.java +++ b/server/src/main/java/org/opensearch/gateway/AsyncShardFetch.java @@ -103,7 +103,7 @@ protected AsyncShardFetch( shardAttributesMap = new HashMap<>(); shardAttributesMap.put(shardId, new ShardAttributes(customDataPath)); this.action = (Lister, T>) action; - this.reroutingKey = "ShardId=[" + shardId.toString() + "]"; + this.reroutingKey = "ShardId=[" + shardId + "]"; cache = new ShardCache<>(logger, reroutingKey, type, clusterManagerMetrics); } diff --git a/server/src/main/java/org/opensearch/gateway/TransportNodesGatewayStartedShardHelper.java b/server/src/main/java/org/opensearch/gateway/TransportNodesGatewayStartedShardHelper.java index 2ddae1d8410c9..687158bfe7bae 100644 --- a/server/src/main/java/org/opensearch/gateway/TransportNodesGatewayStartedShardHelper.java +++ b/server/src/main/java/org/opensearch/gateway/TransportNodesGatewayStartedShardHelper.java @@ -227,7 +227,7 @@ public String toString() { buf.append(",storeException=").append(storeException); } if (replicationCheckpoint != null) { - buf.append(",ReplicationCheckpoint=").append(replicationCheckpoint.toString()); + buf.append(",ReplicationCheckpoint=").append(replicationCheckpoint); } buf.append("]"); return buf.toString(); diff --git a/server/src/main/java/org/opensearch/http/HttpInfo.java b/server/src/main/java/org/opensearch/http/HttpInfo.java index 4a39e40c471b1..f4ee6f2dcb49e 100644 --- a/server/src/main/java/org/opensearch/http/HttpInfo.java +++ b/server/src/main/java/org/opensearch/http/HttpInfo.java @@ -99,7 +99,7 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws ); } if (InetAddresses.isInetAddress(hostString) == false) { - publishAddressString = hostString + '/' + publishAddress.toString(); + publishAddressString = hostString + '/' + publishAddress; } builder.field(Fields.PUBLISH_ADDRESS, publishAddressString); builder.humanReadableField(Fields.MAX_CONTENT_LENGTH_IN_BYTES, Fields.MAX_CONTENT_LENGTH, maxContentLength()); diff --git a/server/src/main/java/org/opensearch/index/IndexSortConfig.java b/server/src/main/java/org/opensearch/index/IndexSortConfig.java index af2e22c4aad53..5c17af7f94024 100644 --- a/server/src/main/java/org/opensearch/index/IndexSortConfig.java +++ b/server/src/main/java/org/opensearch/index/IndexSortConfig.java @@ -155,9 +155,7 @@ public IndexSortConfig(IndexSettings indexSettings) { if (INDEX_SORT_ORDER_SETTING.exists(settings)) { List orders = INDEX_SORT_ORDER_SETTING.get(settings); if (orders.size() != sortSpecs.length) { - throw new IllegalArgumentException( - "index.sort.field:" + fields + " index.sort.order:" + orders.toString() + ", size mismatch" - ); + throw new IllegalArgumentException("index.sort.field:" + fields + " index.sort.order:" + orders + ", size mismatch"); } for (int i = 0; i < sortSpecs.length; i++) { sortSpecs[i].order = orders.get(i); diff --git a/server/src/main/java/org/opensearch/index/IndexingSlowLog.java b/server/src/main/java/org/opensearch/index/IndexingSlowLog.java index bc42fa304e2c5..8cc13969f1235 100644 --- a/server/src/main/java/org/opensearch/index/IndexingSlowLog.java +++ b/server/src/main/java/org/opensearch/index/IndexingSlowLog.java @@ -258,7 +258,7 @@ private static Map prepareMap( * We choose to fail to write to the slow log and instead let this percolate up to the post index listener loop where this * will be logged at the warn level. */ - final String message = String.format(Locale.ROOT, "failed to convert source for slow log entry [%s]", map.toString()); + final String message = String.format(Locale.ROOT, "failed to convert source for slow log entry [%s]", map); throw new UncheckedIOException(message, e); } return map; @@ -288,7 +288,7 @@ private static String message(Index index, ParsedDocument doc, long tookInNanos, * We choose to fail to write to the slow log and instead let this percolate up to the post index listener loop where this * will be logged at the warn level. */ - final String message = String.format(Locale.ROOT, "failed to convert source for slow log entry [%s]", sb.toString()); + final String message = String.format(Locale.ROOT, "failed to convert source for slow log entry [%s]", sb); throw new UncheckedIOException(message, e); } return sb.toString(); diff --git a/server/src/main/java/org/opensearch/index/codec/fuzzy/FuzzyFilterPostingsFormat.java b/server/src/main/java/org/opensearch/index/codec/fuzzy/FuzzyFilterPostingsFormat.java index 01f8054fc91be..c109272477f21 100644 --- a/server/src/main/java/org/opensearch/index/codec/fuzzy/FuzzyFilterPostingsFormat.java +++ b/server/src/main/java/org/opensearch/index/codec/fuzzy/FuzzyFilterPostingsFormat.java @@ -338,7 +338,7 @@ public ImpactsEnum impacts(int flags) throws IOException { @Override public String toString() { - return getClass().getSimpleName() + "(filter=" + filter.toString() + ")"; + return getClass().getSimpleName() + "(filter=" + filter + ")"; } } diff --git a/server/src/main/java/org/opensearch/index/document/SortedUnsignedLongDocValuesSetQuery.java b/server/src/main/java/org/opensearch/index/document/SortedUnsignedLongDocValuesSetQuery.java index 3d677aa6a8dfe..e556caa554e6e 100644 --- a/server/src/main/java/org/opensearch/index/document/SortedUnsignedLongDocValuesSetQuery.java +++ b/server/src/main/java/org/opensearch/index/document/SortedUnsignedLongDocValuesSetQuery.java @@ -50,7 +50,7 @@ public abstract class SortedUnsignedLongDocValuesSetQuery extends Query { @Override public String toString(String field) { - return new StringBuilder().append(field).append(": ").append(numbers.toString()).toString(); + return new StringBuilder().append(field).append(": ").append(numbers).toString(); } @Override diff --git a/server/src/main/java/org/opensearch/index/mapper/DynamicTemplate.java b/server/src/main/java/org/opensearch/index/mapper/DynamicTemplate.java index da62b20c98563..707bc8a1cf3a9 100644 --- a/server/src/main/java/org/opensearch/index/mapper/DynamicTemplate.java +++ b/server/src/main/java/org/opensearch/index/mapper/DynamicTemplate.java @@ -228,7 +228,7 @@ public static DynamicTemplate parse(String name, Map conf) throw } if (match == null && pathMatch == null && matchMappingType == null) { - throw new MapperParsingException("template must have match, path_match or match_mapping_type set " + conf.toString()); + throw new MapperParsingException("template must have match, path_match or match_mapping_type set " + conf); } if (mapping == null) { throw new MapperParsingException("template must have mapping set"); diff --git a/server/src/main/java/org/opensearch/index/mapper/FieldMapper.java b/server/src/main/java/org/opensearch/index/mapper/FieldMapper.java index 5ba68e6d7cb80..790c553c72006 100644 --- a/server/src/main/java/org/opensearch/index/mapper/FieldMapper.java +++ b/server/src/main/java/org/opensearch/index/mapper/FieldMapper.java @@ -450,7 +450,7 @@ public FieldMapper merge(Mapper mergeWith) { merged.mergeSharedOptions(toMerge, conflicts); merged.mergeOptions(toMerge, conflicts); if (conflicts.isEmpty() == false) { - throw new IllegalArgumentException("Mapper for [" + name() + "] conflicts with existing mapping:\n" + conflicts.toString()); + throw new IllegalArgumentException("Mapper for [" + name() + "] conflicts with existing mapping:\n" + conflicts); } merged.multiFields = multiFields.merge(toMerge.multiFields); // apply changeable values diff --git a/server/src/main/java/org/opensearch/index/mapper/ParametrizedFieldMapper.java b/server/src/main/java/org/opensearch/index/mapper/ParametrizedFieldMapper.java index db2b3c0deea88..cb3b88aad7edc 100644 --- a/server/src/main/java/org/opensearch/index/mapper/ParametrizedFieldMapper.java +++ b/server/src/main/java/org/opensearch/index/mapper/ParametrizedFieldMapper.java @@ -496,7 +496,7 @@ public static Parameter restrictedStringParam( return; } throw new MapperParsingException( - "Unknown value [" + v + "] for field [" + name + "] - accepted values are " + acceptedValues.toString() + "Unknown value [" + v + "] for field [" + name + "] - accepted values are " + acceptedValues ); }); } diff --git a/server/src/main/java/org/opensearch/index/mapper/TypeParsers.java b/server/src/main/java/org/opensearch/index/mapper/TypeParsers.java index 30fcba0ae61d3..428125a26c8a3 100644 --- a/server/src/main/java/org/opensearch/index/mapper/TypeParsers.java +++ b/server/src/main/java/org/opensearch/index/mapper/TypeParsers.java @@ -288,7 +288,7 @@ public static DateFormatter parseDateTimeFormatter(Object node) { if (node instanceof String) { return DateFormatter.forPattern((String) node); } - throw new IllegalArgumentException("Invalid format: [" + node.toString() + "]: expected string value"); + throw new IllegalArgumentException("Invalid format: [" + node + "]: expected string value"); } public static List parseCopyFields(Object propNode) { diff --git a/server/src/main/java/org/opensearch/index/query/TermsSetQueryBuilder.java b/server/src/main/java/org/opensearch/index/query/TermsSetQueryBuilder.java index 5582feb86bf5e..b3d04f07d869f 100644 --- a/server/src/main/java/org/opensearch/index/query/TermsSetQueryBuilder.java +++ b/server/src/main/java/org/opensearch/index/query/TermsSetQueryBuilder.java @@ -352,7 +352,7 @@ public boolean equals(Object obj) { @Override public String toString() { - return "script(" + script.toString() + ")"; + return "script(" + script + ")"; } @Override diff --git a/server/src/main/java/org/opensearch/index/query/functionscore/RandomScoreFunctionBuilder.java b/server/src/main/java/org/opensearch/index/query/functionscore/RandomScoreFunctionBuilder.java index 1726c44674d66..29bd0b25057d3 100644 --- a/server/src/main/java/org/opensearch/index/query/functionscore/RandomScoreFunctionBuilder.java +++ b/server/src/main/java/org/opensearch/index/query/functionscore/RandomScoreFunctionBuilder.java @@ -225,7 +225,7 @@ public static RandomScoreFunctionBuilder fromXContent(XContentParser parser) thr } else { throw new ParsingException( parser.getTokenLocation(), - "random_score seed must be an int, long or string, not '" + token.toString() + "'" + "random_score seed must be an int, long or string, not '" + token + "'" ); } } else if (token == XContentParser.Token.VALUE_STRING) { @@ -233,7 +233,7 @@ public static RandomScoreFunctionBuilder fromXContent(XContentParser parser) thr } else { throw new ParsingException( parser.getTokenLocation(), - "random_score seed must be an int/long or string, not '" + token.toString() + "'" + "random_score seed must be an int/long or string, not '" + token + "'" ); } } else if ("field".equals(currentFieldName)) { diff --git a/server/src/main/java/org/opensearch/index/shard/IndexShard.java b/server/src/main/java/org/opensearch/index/shard/IndexShard.java index 2c2cc01587131..b42bc1055b731 100644 --- a/server/src/main/java/org/opensearch/index/shard/IndexShard.java +++ b/server/src/main/java/org/opensearch/index/shard/IndexShard.java @@ -3002,7 +3002,7 @@ public void readAllowed() throws IllegalIndexShardStateException { throw new IllegalIndexShardStateException( shardId, state, - "operations only allowed when shard state is one of " + readAllowedStates.toString() + "operations only allowed when shard state is one of " + readAllowedStates ); } } diff --git a/server/src/main/java/org/opensearch/index/shard/RemoveCorruptedShardDataCommand.java b/server/src/main/java/org/opensearch/index/shard/RemoveCorruptedShardDataCommand.java index a56d61194bf45..52efa36a2c3db 100644 --- a/server/src/main/java/org/opensearch/index/shard/RemoveCorruptedShardDataCommand.java +++ b/server/src/main/java/org/opensearch/index/shard/RemoveCorruptedShardDataCommand.java @@ -172,7 +172,7 @@ protected void findAndProcessShardPath( } else { throw new OpenSearchException( "Unable to resolve shard id. Wrong folder structure at [ " - + path.toString() + + path + " ], expected .../nodes/[NODE-ID]/indices/[INDEX-UUID]/[SHARD-ID]" ); } diff --git a/server/src/main/java/org/opensearch/index/shard/ShardPath.java b/server/src/main/java/org/opensearch/index/shard/ShardPath.java index 911bfec94e190..ce51fae0c19d7 100644 --- a/server/src/main/java/org/opensearch/index/shard/ShardPath.java +++ b/server/src/main/java/org/opensearch/index/shard/ShardPath.java @@ -69,13 +69,13 @@ public final class ShardPath { public ShardPath(boolean isCustomDataPath, Path dataPath, Path shardStatePath, ShardId shardId) { assert dataPath.getFileName().toString().equals(Integer.toString(shardId.id())) : "dataPath must end with the shard ID but didn't: " - + dataPath.toString(); + + dataPath; assert shardStatePath.getFileName().toString().equals(Integer.toString(shardId.id())) - : "shardStatePath must end with the shard ID but didn't: " + dataPath.toString(); + : "shardStatePath must end with the shard ID but didn't: " + dataPath; assert dataPath.getParent().getFileName().toString().equals(shardId.getIndex().getUUID()) - : "dataPath must end with index path id but didn't: " + dataPath.toString(); + : "dataPath must end with index path id but didn't: " + dataPath; assert shardStatePath.getParent().getFileName().toString().equals(shardId.getIndex().getUUID()) - : "shardStatePath must end with index path id but didn't: " + dataPath.toString(); + : "shardStatePath must end with index path id but didn't: " + dataPath; if (isCustomDataPath && dataPath.equals(shardStatePath)) { throw new IllegalArgumentException("shard state path must be different to the data path when using custom data paths"); } diff --git a/server/src/main/java/org/opensearch/index/shard/StoreRecovery.java b/server/src/main/java/org/opensearch/index/shard/StoreRecovery.java index 8fc64b38dc860..181cb82d568c9 100644 --- a/server/src/main/java/org/opensearch/index/shard/StoreRecovery.java +++ b/server/src/main/java/org/opensearch/index/shard/StoreRecovery.java @@ -301,7 +301,7 @@ public IndexInput openInput(String name, IOContext context) throws IOException { } copies.set(true); final IndexInput input = in.openInput(name, context); - return new IndexInput("StatsDirectoryWrapper(" + input.toString() + ")") { + return new IndexInput("StatsDirectoryWrapper(" + input + ")") { @Override public void close() throws IOException { input.close(); diff --git a/server/src/main/java/org/opensearch/index/similarity/ScriptedSimilarity.java b/server/src/main/java/org/opensearch/index/similarity/ScriptedSimilarity.java index 5b39c03b7276a..2280945487d3c 100644 --- a/server/src/main/java/org/opensearch/index/similarity/ScriptedSimilarity.java +++ b/server/src/main/java/org/opensearch/index/similarity/ScriptedSimilarity.java @@ -122,7 +122,7 @@ public Explanation explain(Explanation freq, long norm) { float score = score(freq.getValue().floatValue(), norm); return Explanation.match( score, - "score from " + ScriptedSimilarity.this.toString() + " computed from:", + "score from " + ScriptedSimilarity.this + " computed from:", Explanation.match((float) scoreWeight, "weight"), Explanation.match(query.boost, "query.boost"), Explanation.match(field.docCount, "field.docCount"), diff --git a/server/src/main/java/org/opensearch/index/store/Store.java b/server/src/main/java/org/opensearch/index/store/Store.java index b8f06b1d70a79..6fc816fb95cb0 100644 --- a/server/src/main/java/org/opensearch/index/store/Store.java +++ b/server/src/main/java/org/opensearch/index/store/Store.java @@ -927,7 +927,7 @@ private void innerClose() throws IOException { @Override public String toString() { - return "store(" + in.toString() + ")"; + return "store(" + in + ")"; } @Override @@ -1142,7 +1142,7 @@ public static LoadedMetadata loadMetadata(SegmentInfos segmentInfos, Directory d final Version version = info.info.getVersion(); if (version == null) { // version is written since 3.1+: we should have already hit IndexFormatTooOld. - throw new IllegalArgumentException("expected valid version value: " + info.info.toString()); + throw new IllegalArgumentException("expected valid version value: " + info.info); } // With segment replication enabled, we compute metadata snapshots from the latest in memory infos. // In this case we will have SegmentInfos objects fetched from the primary's reader @@ -1224,8 +1224,8 @@ public static void hashFile(BytesRefBuilder fileHash, InputStream in, long size) fileHash.grow(len); fileHash.setLength(len); final int readBytes = in.readNBytes(fileHash.bytes(), 0, len); - assert readBytes == len : Integer.toString(readBytes) + " != " + Integer.toString(len); - assert fileHash.length() == len : Integer.toString(fileHash.length()) + " != " + Integer.toString(len); + assert readBytes == len : readBytes + " != " + len; + assert fileHash.length() == len : fileHash.length() + " != " + len; } @Override @@ -1496,7 +1496,7 @@ public void verify() throws IOException { + " expectedLength=" + metadata.length() + " (resource=" - + metadata.toString() + + metadata + ")", "VerifyingIndexOutput(" + metadata.name() + ")" ); @@ -1532,7 +1532,7 @@ private void readAndCompareChecksum() throws IOException { + " actual=" + actualChecksum + " (resource=" - + metadata.toString() + + metadata + ")", "VerifyingIndexOutput(" + metadata.name() + ")" ); diff --git a/server/src/main/java/org/opensearch/index/store/VerifyingIndexOutput.java b/server/src/main/java/org/opensearch/index/store/VerifyingIndexOutput.java index 507f7149319fe..cade3edc9e1fb 100644 --- a/server/src/main/java/org/opensearch/index/store/VerifyingIndexOutput.java +++ b/server/src/main/java/org/opensearch/index/store/VerifyingIndexOutput.java @@ -48,7 +48,7 @@ public abstract class VerifyingIndexOutput extends FilterIndexOutput { /** Sole constructor */ VerifyingIndexOutput(IndexOutput out) { - super("VerifyingIndexOutput(out=" + out.toString() + ")", out); + super("VerifyingIndexOutput(out=" + out + ")", out); } /** diff --git a/server/src/main/java/org/opensearch/index/store/remote/file/OnDemandBlockSnapshotIndexInput.java b/server/src/main/java/org/opensearch/index/store/remote/file/OnDemandBlockSnapshotIndexInput.java index 7adf05c03989b..499723b500e0a 100644 --- a/server/src/main/java/org/opensearch/index/store/remote/file/OnDemandBlockSnapshotIndexInput.java +++ b/server/src/main/java/org/opensearch/index/store/remote/file/OnDemandBlockSnapshotIndexInput.java @@ -61,7 +61,7 @@ public class OnDemandBlockSnapshotIndexInput extends AbstractBlockIndexInput { public OnDemandBlockSnapshotIndexInput(FileInfo fileInfo, FSDirectory directory, TransferManager transferManager) { this( "BlockedSnapshotIndexInput(path=\"" - + directory.getDirectory().toString() + + directory.getDirectory() + "/" + fileInfo.physicalName() + "\", " diff --git a/server/src/main/java/org/opensearch/index/store/remote/filecache/FileCachedIndexInput.java b/server/src/main/java/org/opensearch/index/store/remote/filecache/FileCachedIndexInput.java index ab6f5f931da0f..3e28a9a36812a 100644 --- a/server/src/main/java/org/opensearch/index/store/remote/filecache/FileCachedIndexInput.java +++ b/server/src/main/java/org/opensearch/index/store/remote/filecache/FileCachedIndexInput.java @@ -48,7 +48,7 @@ public FileCachedIndexInput(FileCache cache, Path filePath, IndexInput underlyin } FileCachedIndexInput(FileCache cache, Path filePath, IndexInput underlyingIndexInput, boolean isClone) { - super("FileCachedIndexInput (path=" + filePath.toString() + ")"); + super("FileCachedIndexInput (path=" + filePath + ")"); this.cache = cache; this.filePath = filePath; this.luceneIndexInput = underlyingIndexInput; diff --git a/server/src/main/java/org/opensearch/index/store/remote/utils/cache/stats/AggregateRefCountedCacheStats.java b/server/src/main/java/org/opensearch/index/store/remote/utils/cache/stats/AggregateRefCountedCacheStats.java index 29bdecb9eef27..5c88037934ffe 100644 --- a/server/src/main/java/org/opensearch/index/store/remote/utils/cache/stats/AggregateRefCountedCacheStats.java +++ b/server/src/main/java/org/opensearch/index/store/remote/utils/cache/stats/AggregateRefCountedCacheStats.java @@ -259,16 +259,16 @@ public String toString() { return getClass().getSimpleName() + '{' + "overallRefCountedCacheStats=" - + overallCacheStats.toString() + + overallCacheStats + ", " + "fullRefCountedCacheStats=" - + fullFileCacheStats.toString() + + fullFileCacheStats + ", " + "blockRefCountedCacheStats=" - + blockFileCacheStats.toString() + + blockFileCacheStats + ", " + "pinnedRefCountedCacheStats=" - + pinnedFileCacheStats.toString() + + pinnedFileCacheStats + '}'; } } diff --git a/server/src/main/java/org/opensearch/index/translog/InternalTranslogManager.java b/server/src/main/java/org/opensearch/index/translog/InternalTranslogManager.java index 9e340181e4696..5bf126cf7540b 100644 --- a/server/src/main/java/org/opensearch/index/translog/InternalTranslogManager.java +++ b/server/src/main/java/org/opensearch/index/translog/InternalTranslogManager.java @@ -293,7 +293,7 @@ public void ensureCanFlush() { // engine otherwise we might loose documents if the flush succeeds // and the translog recovery fails when we "commit" the translog on flush. if (pendingTranslogRecovery.get()) { - throw new IllegalStateException(shardId.toString() + " flushes are disabled - pending translog recovery"); + throw new IllegalStateException(shardId + " flushes are disabled - pending translog recovery"); } } diff --git a/server/src/main/java/org/opensearch/indices/IndicesRequestCache.java b/server/src/main/java/org/opensearch/indices/IndicesRequestCache.java index 1de9aacca82e0..d26ff8509c4db 100644 --- a/server/src/main/java/org/opensearch/indices/IndicesRequestCache.java +++ b/server/src/main/java/org/opensearch/indices/IndicesRequestCache.java @@ -231,7 +231,7 @@ CacheConfig getCacheConfig(Settings settings, NodeEnvironme .setKeySerializer(new IRCKeyWriteableSerializer()) .setValueSerializer(new BytesReferenceSerializer()) .setClusterSettings(clusterService.getClusterSettings()) - .setStoragePath(nodeEnvironment.nodePaths()[0].path.toString() + "/request_cache"); + .setStoragePath(nodeEnvironment.nodePaths()[0].path + "/request_cache"); if (!CacheService.storeNamePresent(CacheType.INDICES_REQUEST_CACHE, settings)) { // If a store name is absent, use the max size based on the IRC setting into the config. diff --git a/server/src/main/java/org/opensearch/indices/breaker/BreakerSettings.java b/server/src/main/java/org/opensearch/indices/breaker/BreakerSettings.java index e1ed346bfcb17..12bfa4a5502b7 100644 --- a/server/src/main/java/org/opensearch/indices/breaker/BreakerSettings.java +++ b/server/src/main/java/org/opensearch/indices/breaker/BreakerSettings.java @@ -153,7 +153,7 @@ public String toString() { return "[" + this.name + ",type=" - + this.type.toString() + + this.type + ",durability=" + (this.durability == null ? "null" : this.durability.toString()) + ",limit=" diff --git a/server/src/main/java/org/opensearch/indices/replication/SegmentReplicationSource.java b/server/src/main/java/org/opensearch/indices/replication/SegmentReplicationSource.java index fa8968030db96..aab11a7379315 100644 --- a/server/src/main/java/org/opensearch/indices/replication/SegmentReplicationSource.java +++ b/server/src/main/java/org/opensearch/indices/replication/SegmentReplicationSource.java @@ -108,7 +108,7 @@ public void copyFrom(Directory from, String src, String dest, IOContext context) @Override public IndexInput openInput(String name, IOContext context) throws IOException { final IndexInput input = in.openInput(name, context); - return new IndexInput("StatsDirectoryWrapper(" + input.toString() + ")") { + return new IndexInput("StatsDirectoryWrapper(" + input + ")") { @Override public void close() throws IOException { input.close(); diff --git a/server/src/main/java/org/opensearch/ingest/ConfigurationUtils.java b/server/src/main/java/org/opensearch/ingest/ConfigurationUtils.java index a2c2137130587..9dc5d148af38c 100644 --- a/server/src/main/java/org/opensearch/ingest/ConfigurationUtils.java +++ b/server/src/main/java/org/opensearch/ingest/ConfigurationUtils.java @@ -250,7 +250,7 @@ public static Integer readIntProperty( processorType, processorTag, propertyName, - "property cannot be converted to an int [" + value.toString() + "]" + "property cannot be converted to an int [" + value + "]" ); } } @@ -278,7 +278,7 @@ public static Double readDoubleProperty( processorType, processorTag, propertyName, - "property cannot be converted to a double [" + value.toString() + "]" + "property cannot be converted to a double [" + value + "]" ); } } diff --git a/server/src/main/java/org/opensearch/lucene/queries/SearchAfterSortedDocQuery.java b/server/src/main/java/org/opensearch/lucene/queries/SearchAfterSortedDocQuery.java index 81778c3387863..5182d118a1eed 100644 --- a/server/src/main/java/org/opensearch/lucene/queries/SearchAfterSortedDocQuery.java +++ b/server/src/main/java/org/opensearch/lucene/queries/SearchAfterSortedDocQuery.java @@ -126,7 +126,7 @@ public void visit(QueryVisitor visitor) { @Override public String toString(String field) { - return "SearchAfterSortedDocQuery(sort=" + sort + ", afterDoc=" + after.toString() + ")"; + return "SearchAfterSortedDocQuery(sort=" + sort + ", afterDoc=" + after + ")"; } @Override diff --git a/server/src/main/java/org/opensearch/node/InternalSettingsPreparer.java b/server/src/main/java/org/opensearch/node/InternalSettingsPreparer.java index 3b9bd6a05dbf9..d1a077e2e2015 100644 --- a/server/src/main/java/org/opensearch/node/InternalSettingsPreparer.java +++ b/server/src/main/java/org/opensearch/node/InternalSettingsPreparer.java @@ -95,7 +95,7 @@ public static Environment prepareEnvironment( try { output.loadFromPath(path); } catch (IOException e) { - throw new SettingsException("Failed to load settings from " + path.toString(), e); + throw new SettingsException("Failed to load settings from " + path, e); } } diff --git a/server/src/main/java/org/opensearch/repositories/blobstore/BlobStoreRepository.java b/server/src/main/java/org/opensearch/repositories/blobstore/BlobStoreRepository.java index fa2c9c247439a..1a68daf76b0dc 100644 --- a/server/src/main/java/org/opensearch/repositories/blobstore/BlobStoreRepository.java +++ b/server/src/main/java/org/opensearch/repositories/blobstore/BlobStoreRepository.java @@ -3572,7 +3572,7 @@ public void onFailure(Exception e) { if (ensureSafeGenerationExists(expectedGen, listener::onFailure) == false) { return; } - final String indexBlob = INDEX_FILE_PREFIX + Long.toString(newGen); + final String indexBlob = INDEX_FILE_PREFIX + newGen; logger.debug("Repository [{}] writing new index generational blob [{}]", metadata.name(), indexBlob); Version minNodeVersion = clusterService.state().nodes().getMinNodeVersion(); final BytesReference serializedRepoData = BytesReference.bytes( diff --git a/server/src/main/java/org/opensearch/rest/BaseRestHandler.java b/server/src/main/java/org/opensearch/rest/BaseRestHandler.java index b4484939e1137..94e3dfdee63a3 100644 --- a/server/src/main/java/org/opensearch/rest/BaseRestHandler.java +++ b/server/src/main/java/org/opensearch/rest/BaseRestHandler.java @@ -167,7 +167,7 @@ public static String unrecognizedStrings( if (keys.size() == 1) { message.append("[").append(keys.get(0)).append("]"); } else { - message.append("any of ").append(keys.toString()); + message.append("any of ").append(keys); } message.append("?"); } diff --git a/server/src/main/java/org/opensearch/rest/action/admin/cluster/RestNodesHotThreadsAction.java b/server/src/main/java/org/opensearch/rest/action/admin/cluster/RestNodesHotThreadsAction.java index 297611d9a78c0..39992527940c3 100644 --- a/server/src/main/java/org/opensearch/rest/action/admin/cluster/RestNodesHotThreadsAction.java +++ b/server/src/main/java/org/opensearch/rest/action/admin/cluster/RestNodesHotThreadsAction.java @@ -136,7 +136,7 @@ public RestChannelConsumer prepareRequest(final RestRequest request, final NodeC public RestResponse buildResponse(NodesHotThreadsResponse response) throws Exception { StringBuilder sb = new StringBuilder(); for (NodeHotThreads node : response.getNodes()) { - sb.append("::: ").append(node.getNode().toString()).append("\n"); + sb.append("::: ").append(node.getNode()).append("\n"); Strings.spaceify(3, node.getHotThreads(), sb); sb.append('\n'); } diff --git a/server/src/main/java/org/opensearch/search/SearchContextSourcePrinter.java b/server/src/main/java/org/opensearch/search/SearchContextSourcePrinter.java index c673eb512347c..0f523c3a58267 100644 --- a/server/src/main/java/org/opensearch/search/SearchContextSourcePrinter.java +++ b/server/src/main/java/org/opensearch/search/SearchContextSourcePrinter.java @@ -53,7 +53,7 @@ public String toString() { builder.append(searchContext.indexShard().shardId()); builder.append(" "); if (searchContext.request() != null && searchContext.request().source() != null) { - builder.append("source[").append(searchContext.request().source().toString()).append("], "); + builder.append("source[").append(searchContext.request().source()).append("], "); } else { builder.append("source[], "); } diff --git a/server/src/main/java/org/opensearch/search/aggregations/bucket/histogram/AutoDateHistogramAggregationBuilder.java b/server/src/main/java/org/opensearch/search/aggregations/bucket/histogram/AutoDateHistogramAggregationBuilder.java index 40944cdd92dee..a10adcc72c440 100644 --- a/server/src/main/java/org/opensearch/search/aggregations/bucket/histogram/AutoDateHistogramAggregationBuilder.java +++ b/server/src/main/java/org/opensearch/search/aggregations/bucket/histogram/AutoDateHistogramAggregationBuilder.java @@ -195,7 +195,7 @@ public String getMinimumIntervalExpression() { public AutoDateHistogramAggregationBuilder setMinimumIntervalExpression(String minimumIntervalExpression) { if (minimumIntervalExpression != null && !ALLOWED_INTERVALS.containsValue(minimumIntervalExpression)) { throw new IllegalArgumentException( - MINIMUM_INTERVAL_FIELD.getPreferredName() + " must be one of [" + ALLOWED_INTERVALS.values().toString() + "]" + MINIMUM_INTERVAL_FIELD.getPreferredName() + " must be one of [" + ALLOWED_INTERVALS.values() + "]" ); } this.minimumIntervalExpression = minimumIntervalExpression; @@ -306,7 +306,7 @@ public RoundingInfo( this.innerIntervals = innerIntervals; Objects.requireNonNull(dateTimeUnit, "dateTimeUnit cannot be null"); if (!ALLOWED_INTERVALS.containsKey(dateTimeUnit)) { - throw new IllegalArgumentException("dateTimeUnit must be one of " + ALLOWED_INTERVALS.keySet().toString()); + throw new IllegalArgumentException("dateTimeUnit must be one of " + ALLOWED_INTERVALS.keySet()); } this.dateTimeUnit = ALLOWED_INTERVALS.get(dateTimeUnit); } diff --git a/server/src/main/java/org/opensearch/search/aggregations/bucket/histogram/DateIntervalWrapper.java b/server/src/main/java/org/opensearch/search/aggregations/bucket/histogram/DateIntervalWrapper.java index 83c20ba1c1d04..8b063a0babde9 100644 --- a/server/src/main/java/org/opensearch/search/aggregations/bucket/histogram/DateIntervalWrapper.java +++ b/server/src/main/java/org/opensearch/search/aggregations/bucket/histogram/DateIntervalWrapper.java @@ -214,7 +214,7 @@ public DateHistogramInterval getAsCalendarInterval() { if (intervalType.equals(IntervalTypeEnum.CALENDAR) || tryIntervalAsCalendarUnit() != null) { return dateHistogramInterval; } - throw new IllegalStateException("Cannot convert [" + intervalType.toString() + "] interval type into calendar interval"); + throw new IllegalStateException("Cannot convert [" + intervalType + "] interval type into calendar interval"); } /** @@ -244,7 +244,7 @@ public DateHistogramInterval getAsFixedInterval() { if (intervalType.equals(IntervalTypeEnum.FIXED) || tryIntervalAsFixedUnit() != null) { return dateHistogramInterval; } - throw new IllegalStateException("Cannot convert [" + intervalType.toString() + "] interval type into fixed interval"); + throw new IllegalStateException("Cannot convert [" + intervalType + "] interval type into fixed interval"); } /** diff --git a/server/src/main/java/org/opensearch/search/aggregations/bucket/histogram/InternalAutoDateHistogram.java b/server/src/main/java/org/opensearch/search/aggregations/bucket/histogram/InternalAutoDateHistogram.java index 0866d26526761..d3e0406522053 100644 --- a/server/src/main/java/org/opensearch/search/aggregations/bucket/histogram/InternalAutoDateHistogram.java +++ b/server/src/main/java/org/opensearch/search/aggregations/bucket/histogram/InternalAutoDateHistogram.java @@ -265,7 +265,7 @@ public DateHistogramInterval getInterval() { RoundingInfo roundingInfo = this.bucketInfo.roundingInfos[this.bucketInfo.roundingIdx]; String unitAbbreviation = roundingInfo.unitAbbreviation; - return new DateHistogramInterval(Long.toString(bucketInnerInterval) + unitAbbreviation); + return new DateHistogramInterval(bucketInnerInterval + unitAbbreviation); } @Override diff --git a/server/src/main/java/org/opensearch/search/aggregations/pipeline/InternalPercentilesBucket.java b/server/src/main/java/org/opensearch/search/aggregations/pipeline/InternalPercentilesBucket.java index 0473d724bee20..116d347adbdc8 100644 --- a/server/src/main/java/org/opensearch/search/aggregations/pipeline/InternalPercentilesBucket.java +++ b/server/src/main/java/org/opensearch/search/aggregations/pipeline/InternalPercentilesBucket.java @@ -121,7 +121,7 @@ public double percentile(double percent) throws IllegalArgumentException { if (percentile == null) { throw new IllegalArgumentException( "Percent requested [" - + String.valueOf(percent) + + percent + "] was not" + " one of the computed percentiles. Available keys are: " + Arrays.toString(percents) @@ -177,7 +177,7 @@ public XContentBuilder doXContentBody(XContentBuilder builder, Params params) th builder.field("key", percent); builder.field("value", hasValue ? value : null); if (hasValue && format != DocValueFormat.RAW) { - builder.field(String.valueOf(percent) + "_as_string", percentileAsString(percent)); + builder.field(percent + "_as_string", percentileAsString(percent)); } builder.endObject(); } diff --git a/server/src/main/java/org/opensearch/search/aggregations/pipeline/ParsedPercentilesBucket.java b/server/src/main/java/org/opensearch/search/aggregations/pipeline/ParsedPercentilesBucket.java index e1fbb1336eb76..5cc7b9296fa62 100644 --- a/server/src/main/java/org/opensearch/search/aggregations/pipeline/ParsedPercentilesBucket.java +++ b/server/src/main/java/org/opensearch/search/aggregations/pipeline/ParsedPercentilesBucket.java @@ -59,7 +59,7 @@ public double percentile(double percent) throws IllegalArgumentException { if (value == null) { throw new IllegalArgumentException( "Percent requested [" - + String.valueOf(percent) + + percent + "] was not" + " one of the computed percentiles. Available keys are: " + percentiles.keySet() diff --git a/server/src/main/java/org/opensearch/search/aggregations/support/MultiValuesSource.java b/server/src/main/java/org/opensearch/search/aggregations/support/MultiValuesSource.java index 53ad7fe9abae0..c477961bafa49 100644 --- a/server/src/main/java/org/opensearch/search/aggregations/support/MultiValuesSource.java +++ b/server/src/main/java/org/opensearch/search/aggregations/support/MultiValuesSource.java @@ -61,7 +61,7 @@ public NumericMultiValuesSource(Map valuesSourceConf final ValuesSource valuesSource = entry.getValue().getValuesSource(); if (!(valuesSource instanceof ValuesSource.Numeric numericValuesSource)) { throw new AggregationExecutionException( - "ValuesSource type " + valuesSource.toString() + "is not supported for multi-valued aggregation" + "ValuesSource type " + valuesSource + "is not supported for multi-valued aggregation" ); } values.put(entry.getKey(), numericValuesSource); diff --git a/server/src/main/java/org/opensearch/search/approximate/ApproximatePointRangeQuery.java b/server/src/main/java/org/opensearch/search/approximate/ApproximatePointRangeQuery.java index 046eb4dc1c86f..86e91532fcb6d 100644 --- a/server/src/main/java/org/opensearch/search/approximate/ApproximatePointRangeQuery.java +++ b/server/src/main/java/org/opensearch/search/approximate/ApproximatePointRangeQuery.java @@ -515,7 +515,7 @@ private boolean equalsTo(ApproximatePointRangeQuery other) { public final String toString(String field) { final StringBuilder sb = new StringBuilder(); sb.append("Approximate("); - sb.append(pointRangeQuery.toString()); + sb.append(pointRangeQuery); sb.append(")"); return sb.toString(); diff --git a/server/src/main/java/org/opensearch/search/approximate/ApproximateScoreQuery.java b/server/src/main/java/org/opensearch/search/approximate/ApproximateScoreQuery.java index be1b6eed5333d..58643787f6848 100644 --- a/server/src/main/java/org/opensearch/search/approximate/ApproximateScoreQuery.java +++ b/server/src/main/java/org/opensearch/search/approximate/ApproximateScoreQuery.java @@ -61,11 +61,7 @@ public void setContext(SearchContext context) { @Override public String toString(String s) { - return "ApproximateScoreQuery(originalQuery=" - + originalQuery.toString() - + ", approximationQuery=" - + approximationQuery.toString() - + ")"; + return "ApproximateScoreQuery(originalQuery=" + originalQuery + ", approximationQuery=" + approximationQuery + ")"; } @Override diff --git a/server/src/main/java/org/opensearch/search/fetch/subphase/highlight/FastVectorHighlighter.java b/server/src/main/java/org/opensearch/search/fetch/subphase/highlight/FastVectorHighlighter.java index 9a127dcd63a9c..2a5522396b97c 100644 --- a/server/src/main/java/org/opensearch/search/fetch/subphase/highlight/FastVectorHighlighter.java +++ b/server/src/main/java/org/opensearch/search/fetch/subphase/highlight/FastVectorHighlighter.java @@ -309,7 +309,7 @@ private static BoundaryScanner getBoundaryScanner(Field field) { } return DEFAULT_SIMPLE_BOUNDARY_SCANNER; default: - throw new IllegalArgumentException("Invalid boundary scanner type: " + type.toString()); + throw new IllegalArgumentException("Invalid boundary scanner type: " + type); } } diff --git a/server/src/main/java/org/opensearch/search/fetch/subphase/highlight/UnifiedHighlighter.java b/server/src/main/java/org/opensearch/search/fetch/subphase/highlight/UnifiedHighlighter.java index f84c7ea7e2d3b..cf9ea010b9011 100644 --- a/server/src/main/java/org/opensearch/search/fetch/subphase/highlight/UnifiedHighlighter.java +++ b/server/src/main/java/org/opensearch/search/fetch/subphase/highlight/UnifiedHighlighter.java @@ -243,7 +243,7 @@ protected BreakIterator getBreakIterator(SearchHighlightContext.Field field) { // ignore maxLen return BreakIterator.getWordInstance(locale); default: - throw new IllegalArgumentException("Invalid boundary scanner type: " + type.toString()); + throw new IllegalArgumentException("Invalid boundary scanner type: " + type); } } diff --git a/server/src/main/java/org/opensearch/search/profile/fetch/FlatFetchProfileTree.java b/server/src/main/java/org/opensearch/search/profile/fetch/FlatFetchProfileTree.java index e9adfcf9c0760..118e2d375806f 100644 --- a/server/src/main/java/org/opensearch/search/profile/fetch/FlatFetchProfileTree.java +++ b/server/src/main/java/org/opensearch/search/profile/fetch/FlatFetchProfileTree.java @@ -28,22 +28,22 @@ class FlatFetchProfileTree { private static final Set ROOT_KEYS = Set.of( FetchTimingType.CREATE_STORED_FIELDS_VISITOR.toString(), - FetchTimingType.CREATE_STORED_FIELDS_VISITOR.toString() + Timer.TIMING_TYPE_COUNT_SUFFIX, + FetchTimingType.CREATE_STORED_FIELDS_VISITOR + Timer.TIMING_TYPE_COUNT_SUFFIX, FetchTimingType.BUILD_SUB_PHASE_PROCESSORS.toString(), - FetchTimingType.BUILD_SUB_PHASE_PROCESSORS.toString() + Timer.TIMING_TYPE_COUNT_SUFFIX, + FetchTimingType.BUILD_SUB_PHASE_PROCESSORS + Timer.TIMING_TYPE_COUNT_SUFFIX, FetchTimingType.LOAD_STORED_FIELDS.toString(), - FetchTimingType.LOAD_STORED_FIELDS.toString() + Timer.TIMING_TYPE_COUNT_SUFFIX, + FetchTimingType.LOAD_STORED_FIELDS + Timer.TIMING_TYPE_COUNT_SUFFIX, FetchTimingType.LOAD_SOURCE.toString(), - FetchTimingType.LOAD_SOURCE.toString() + Timer.TIMING_TYPE_COUNT_SUFFIX, + FetchTimingType.LOAD_SOURCE + Timer.TIMING_TYPE_COUNT_SUFFIX, FetchTimingType.GET_NEXT_READER.toString(), - FetchTimingType.GET_NEXT_READER.toString() + Timer.TIMING_TYPE_COUNT_SUFFIX + FetchTimingType.GET_NEXT_READER + Timer.TIMING_TYPE_COUNT_SUFFIX ); private static final Set SUB_PHASE_KEYS = Set.of( FetchTimingType.PROCESS.toString(), - FetchTimingType.PROCESS.toString() + Timer.TIMING_TYPE_COUNT_SUFFIX, + FetchTimingType.PROCESS + Timer.TIMING_TYPE_COUNT_SUFFIX, FetchTimingType.SET_NEXT_READER.toString(), - FetchTimingType.SET_NEXT_READER.toString() + Timer.TIMING_TYPE_COUNT_SUFFIX + FetchTimingType.SET_NEXT_READER + Timer.TIMING_TYPE_COUNT_SUFFIX ); private static class Node { diff --git a/server/src/main/java/org/opensearch/search/profile/query/InternalProfileCollector.java b/server/src/main/java/org/opensearch/search/profile/query/InternalProfileCollector.java index 024d91a8e2ed2..4d40710154178 100644 --- a/server/src/main/java/org/opensearch/search/profile/query/InternalProfileCollector.java +++ b/server/src/main/java/org/opensearch/search/profile/query/InternalProfileCollector.java @@ -137,7 +137,7 @@ private String deriveCollectorName(Collector c) { // Aggregation collector toString()'s include the user-defined agg name if (reason.equals(CollectorResult.REASON_AGGREGATION) || reason.equals(CollectorResult.REASON_AGGREGATION_GLOBAL)) { - s += ": [" + c.toString() + "]"; + s += ": [" + c + "]"; } return s; } diff --git a/server/src/main/java/org/opensearch/search/suggest/completion/context/ContextMappings.java b/server/src/main/java/org/opensearch/search/suggest/completion/context/ContextMappings.java index 3bbcdb7ed05ca..f33faf3517153 100644 --- a/server/src/main/java/org/opensearch/search/suggest/completion/context/ContextMappings.java +++ b/server/src/main/java/org/opensearch/search/suggest/completion/context/ContextMappings.java @@ -102,7 +102,7 @@ public ContextMapping get(String name) { if (contextMapping == null) { List keys = new ArrayList<>(contextNameMap.keySet()); Collections.sort(keys); - throw new IllegalArgumentException("Unknown context name [" + name + "], must be one of " + keys.toString()); + throw new IllegalArgumentException("Unknown context name [" + name + "], must be one of " + keys); } return contextMapping; } diff --git a/server/src/main/java/org/opensearch/snapshots/Snapshot.java b/server/src/main/java/org/opensearch/snapshots/Snapshot.java index 4dd930c7b59c0..f682c09a02c23 100644 --- a/server/src/main/java/org/opensearch/snapshots/Snapshot.java +++ b/server/src/main/java/org/opensearch/snapshots/Snapshot.java @@ -86,7 +86,7 @@ public SnapshotId getSnapshotId() { @Override public String toString() { - return repository + ":" + snapshotId.toString(); + return repository + ":" + snapshotId; } @Override diff --git a/server/src/main/java/org/opensearch/threadpool/ThreadPool.java b/server/src/main/java/org/opensearch/threadpool/ThreadPool.java index 0c9adfe109008..4e3b5099e203a 100644 --- a/server/src/main/java/org/opensearch/threadpool/ThreadPool.java +++ b/server/src/main/java/org/opensearch/threadpool/ThreadPool.java @@ -791,7 +791,7 @@ public boolean equals(Object obj) { @Override public String toString() { - return "[threaded] " + runnable.toString(); + return "[threaded] " + runnable; } } @@ -838,7 +838,7 @@ public boolean equals(Object obj) { @Override public String toString() { - return "[threaded] " + runnable.toString(); + return "[threaded] " + runnable; } } diff --git a/server/src/main/java/org/opensearch/transport/PlainTransportFuture.java b/server/src/main/java/org/opensearch/transport/PlainTransportFuture.java index ff9ca8b189904..7f859da106376 100644 --- a/server/src/main/java/org/opensearch/transport/PlainTransportFuture.java +++ b/server/src/main/java/org/opensearch/transport/PlainTransportFuture.java @@ -123,6 +123,6 @@ public void handleException(TransportException exp) { @Override public String toString() { - return "future(" + handler.toString() + ")"; + return "future(" + handler + ")"; } } diff --git a/server/src/main/java/org/opensearch/transport/SniffConnectionStrategy.java b/server/src/main/java/org/opensearch/transport/SniffConnectionStrategy.java index 1d94228218fd0..c99a0048882db 100644 --- a/server/src/main/java/org/opensearch/transport/SniffConnectionStrategy.java +++ b/server/src/main/java/org/opensearch/transport/SniffConnectionStrategy.java @@ -494,7 +494,7 @@ private static DiscoveryNode resolveSeedNode(String clusterAlias, String address if (proxyAddress == null || proxyAddress.isEmpty()) { TransportAddress transportAddress = new TransportAddress(parseConfiguredAddress(address)); return new DiscoveryNode( - clusterAlias + "#" + transportAddress.toString(), + clusterAlias + "#" + transportAddress, transportAddress, Version.CURRENT.minimumCompatibilityVersion() ); diff --git a/server/src/main/java/org/opensearch/transport/TransportInfo.java b/server/src/main/java/org/opensearch/transport/TransportInfo.java index 75179f7932238..ad5639755497a 100644 --- a/server/src/main/java/org/opensearch/transport/TransportInfo.java +++ b/server/src/main/java/org/opensearch/transport/TransportInfo.java @@ -123,7 +123,7 @@ private String formatPublishAddressString(String propertyName, TransportAddress String hostString = publishAddress.address().getHostString(); if (InetAddresses.isInetAddress(hostString) == false) { if (cnameInPublishAddress) { - publishAddressString = hostString + '/' + publishAddress.toString(); + publishAddressString = hostString + '/' + publishAddress; } else { deprecationLogger.deprecate( "cname_in_publish_address_" + propertyName, diff --git a/server/src/main/java/org/opensearch/transport/TransportService.java b/server/src/main/java/org/opensearch/transport/TransportService.java index ed64aa1229517..959ed87f62cad 100644 --- a/server/src/main/java/org/opensearch/transport/TransportService.java +++ b/server/src/main/java/org/opensearch/transport/TransportService.java @@ -1615,7 +1615,7 @@ public String executor() { @Override public String toString() { - return getClass().getName() + "/" + delegate.toString(); + return getClass().getName() + "/" + delegate; } void setTimeoutHandler(TimeoutHandler handler) { @@ -1838,7 +1838,7 @@ public T read(StreamInput in) throws IOException { @Override public String toString() { - return getClass().getName() + "/[" + action + "]:" + handler.toString(); + return getClass().getName() + "/[" + action + "]:" + handler; } }; } else { diff --git a/server/src/main/java/org/opensearch/wlm/WorkloadGroupService.java b/server/src/main/java/org/opensearch/wlm/WorkloadGroupService.java index a36a5a8bbfd31..de0b6f80c7164 100644 --- a/server/src/main/java/org/opensearch/wlm/WorkloadGroupService.java +++ b/server/src/main/java/org/opensearch/wlm/WorkloadGroupService.java @@ -305,9 +305,7 @@ public void rejectIfNeeded(String workloadGroupId) { } if (reject) { workloadGroupState.totalRejections.inc(); - throw new OpenSearchRejectedExecutionException( - "WorkloadGroup " + workloadGroupId + " is already contended. " + reason.toString() - ); + throw new OpenSearchRejectedExecutionException("WorkloadGroup " + workloadGroupId + " is already contended. " + reason); } }); } diff --git a/test/fixtures/azure-fixture/build.gradle b/test/fixtures/azure-fixture/build.gradle index 904297a3b4c65..7b04f39f2be48 100644 --- a/test/fixtures/azure-fixture/build.gradle +++ b/test/fixtures/azure-fixture/build.gradle @@ -41,8 +41,8 @@ dependencies { preProcessFixture { dependsOn jar, configurations.runtimeClasspath // always run the task, otherwise the folders won't be created - outputs.upToDateWhen { - false + outputs.upToDateWhen { + false } doLast { file("${testFixturesDir}/shared").mkdirs() diff --git a/test/fixtures/gcs-fixture/build.gradle b/test/fixtures/gcs-fixture/build.gradle index 60f672e6bd00b..153bfeb21ee2d 100644 --- a/test/fixtures/gcs-fixture/build.gradle +++ b/test/fixtures/gcs-fixture/build.gradle @@ -41,8 +41,8 @@ group = 'fixture.gcs' preProcessFixture { dependsOn jar, configurations.runtimeClasspath // always run the task, otherwise the folders won't be created - outputs.upToDateWhen { - false + outputs.upToDateWhen { + false } doLast { file("${testFixturesDir}/shared").mkdirs() diff --git a/test/fixtures/s3-fixture/build.gradle b/test/fixtures/s3-fixture/build.gradle index 519e8514af4d4..9b0dcbb52f812 100644 --- a/test/fixtures/s3-fixture/build.gradle +++ b/test/fixtures/s3-fixture/build.gradle @@ -41,8 +41,8 @@ dependencies { preProcessFixture { dependsOn jar, configurations.runtimeClasspath // always run the task, otherwise the folders won't be created - outputs.upToDateWhen { - false + outputs.upToDateWhen { + false } doLast { file("${testFixturesDir}/shared").mkdirs() diff --git a/test/telemetry/src/main/java/org/opensearch/test/telemetry/tracing/TelemetryValidators.java b/test/telemetry/src/main/java/org/opensearch/test/telemetry/tracing/TelemetryValidators.java index 9b5d84954908b..1d02f69672316 100644 --- a/test/telemetry/src/main/java/org/opensearch/test/telemetry/tracing/TelemetryValidators.java +++ b/test/telemetry/src/main/java/org/opensearch/test/telemetry/tracing/TelemetryValidators.java @@ -51,7 +51,7 @@ private String printProblematicSpansMap(Map> spanMap) sb.append("SpanData validation failed for validator " + entry.getKey()); sb.append("\n"); for (MockSpanData span : entry.getValue()) { - sb.append(span.toString()); + sb.append(span); } } return sb.toString();