diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b2c379f486a0..8304c399e77cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - Bump `com.maxmind.geoip2:geoip2` from 4.0.0 to 4.0.1 - Bump `com.networknt:json-schema-validator` from 1.0.76 to 1.0.78 - Bump `com.netflix.nebula:gradle-info-plugin` from 12.0.0 to 12.0.1 +- Bump `com.diffplug.spotless` from 6.15.0 to 6.17.0 ### Changed - [CCR] Add getHistoryOperationsFromTranslog method to fetch the history snapshot from translogs ([#3948](https://github.com/opensearch-project/OpenSearch/pull/3948)) diff --git a/build.gradle b/build.gradle index 7ef766310ab2c..6c5885a295c1e 100644 --- a/build.gradle +++ b/build.gradle @@ -53,7 +53,7 @@ plugins { id 'lifecycle-base' id 'opensearch.docker-support' id 'opensearch.global-build-info' - id "com.diffplug.spotless" version "6.15.0" apply false + id "com.diffplug.spotless" version "6.17.0" apply false id "org.gradle.test-retry" version "1.5.1" apply false id "test-report-aggregation" id 'jacoco-report-aggregation' diff --git a/buildSrc/src/main/java/org/opensearch/gradle/docker/DockerSupportPlugin.java b/buildSrc/src/main/java/org/opensearch/gradle/docker/DockerSupportPlugin.java index 92777638982d2..5455875a96611 100644 --- a/buildSrc/src/main/java/org/opensearch/gradle/docker/DockerSupportPlugin.java +++ b/buildSrc/src/main/java/org/opensearch/gradle/docker/DockerSupportPlugin.java @@ -56,13 +56,9 @@ public void apply(Project project) { Provider dockerSupportServiceProvider = project.getGradle() .getSharedServices() - .registerIfAbsent( - DOCKER_SUPPORT_SERVICE_NAME, - DockerSupportService.class, - spec -> spec.parameters( - params -> { params.setExclusionsFile(new File(project.getRootDir(), DOCKER_ON_LINUX_EXCLUSIONS_FILE)); } - ) - ); + .registerIfAbsent(DOCKER_SUPPORT_SERVICE_NAME, DockerSupportService.class, spec -> spec.parameters(params -> { + params.setExclusionsFile(new File(project.getRootDir(), DOCKER_ON_LINUX_EXCLUSIONS_FILE)); + })); // Ensure that if we are trying to run any DockerBuildTask tasks, we assert an available Docker installation exists project.getGradle().getTaskGraph().whenReady(graph -> { diff --git a/buildSrc/src/main/java/org/opensearch/gradle/internal/InternalDistributionBwcSetupPlugin.java b/buildSrc/src/main/java/org/opensearch/gradle/internal/InternalDistributionBwcSetupPlugin.java index dd2393702fe2b..33869e76680cd 100644 --- a/buildSrc/src/main/java/org/opensearch/gradle/internal/InternalDistributionBwcSetupPlugin.java +++ b/buildSrc/src/main/java/org/opensearch/gradle/internal/InternalDistributionBwcSetupPlugin.java @@ -76,12 +76,9 @@ public InternalDistributionBwcSetupPlugin(ProviderFactory providerFactory) { @Override public void apply(Project project) { project.getRootProject().getPluginManager().apply(GlobalBuildInfoPlugin.class); - BuildParams.getBwcVersions() - .forPreviousUnreleased( - (BwcVersions.UnreleasedVersionInfo unreleasedVersion) -> { - configureBwcProject(project.project(unreleasedVersion.gradleProjectPath), unreleasedVersion); - } - ); + BuildParams.getBwcVersions().forPreviousUnreleased((BwcVersions.UnreleasedVersionInfo unreleasedVersion) -> { + configureBwcProject(project.project(unreleasedVersion.gradleProjectPath), unreleasedVersion); + }); } private void configureBwcProject(Project project, BwcVersions.UnreleasedVersionInfo versionInfo) { diff --git a/buildSrc/src/main/java/org/opensearch/gradle/test/DistroTestPlugin.java b/buildSrc/src/main/java/org/opensearch/gradle/test/DistroTestPlugin.java index 64e30700360b3..3bb92d826e5eb 100644 --- a/buildSrc/src/main/java/org/opensearch/gradle/test/DistroTestPlugin.java +++ b/buildSrc/src/main/java/org/opensearch/gradle/test/DistroTestPlugin.java @@ -197,13 +197,9 @@ public void apply(Project project) { // windows boxes get windows distributions, and linux boxes get linux distributions if (isWindows(vmProject)) { - configureVMWrapperTasks( - vmProject, - windowsTestTasks, - depsTasks, - wrapperTask -> { vmLifecyleTasks.get(OpenSearchDistribution.Type.ARCHIVE).configure(t -> t.dependsOn(wrapperTask)); }, - vmDependencies - ); + configureVMWrapperTasks(vmProject, windowsTestTasks, depsTasks, wrapperTask -> { + vmLifecyleTasks.get(OpenSearchDistribution.Type.ARCHIVE).configure(t -> t.dependsOn(wrapperTask)); + }, vmDependencies); } else { for (Entry>> entry : linuxTestTasks.entrySet()) { OpenSearchDistribution.Type type = entry.getKey(); diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/core/MainResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/core/MainResponse.java index b318c6c6214c9..6df51a6a4ff3e 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/core/MainResponse.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/core/MainResponse.java @@ -43,7 +43,9 @@ public class MainResponse { private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( MainResponse.class.getName(), true, - args -> { return new MainResponse((String) args[0], (Version) args[1], (String) args[2], (String) args[3]); } + args -> { + return new MainResponse((String) args[0], (Version) args[1], (String) args[2], (String) args[3]); + } ); static { diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/core/TermVectorsResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/core/TermVectorsResponse.java index f7919bc576a3e..5e671c416e4ef 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/core/TermVectorsResponse.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/core/TermVectorsResponse.java @@ -240,7 +240,9 @@ public static final class FieldStatistics { private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( "field_statistics", true, - args -> { return new FieldStatistics((long) args[0], (int) args[1], (long) args[2]); } + args -> { + return new FieldStatistics((long) args[0], (int) args[1], (long) args[2]); + } ); static { @@ -411,11 +413,9 @@ public int hashCode() { public static final class Token { - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "token", - true, - args -> { return new Token((Integer) args[0], (Integer) args[1], (Integer) args[2], (String) args[3]); } - ); + private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>("token", true, args -> { + return new Token((Integer) args[0], (Integer) args[1], (Integer) args[2], (String) args[3]); + }); static { PARSER.declareInt(optionalConstructorArg(), new ParseField("start_offset")); PARSER.declareInt(optionalConstructorArg(), new ParseField("end_offset")); diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/CrudIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/CrudIT.java index 97ee889429434..86efeb5d84b10 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/CrudIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/CrudIT.java @@ -628,10 +628,9 @@ public void testIndex() throws IOException { assertEquals("index", indexResponse.getIndex()); assertEquals("with_create_op_type", indexResponse.getId()); - OpenSearchStatusException exception = expectThrows( - OpenSearchStatusException.class, - () -> { execute(indexRequest, highLevelClient()::index, highLevelClient()::indexAsync); } - ); + OpenSearchStatusException exception = expectThrows(OpenSearchStatusException.class, () -> { + execute(indexRequest, highLevelClient()::index, highLevelClient()::indexAsync); + }); assertEquals(RestStatus.CONFLICT, exception.status()); assertEquals( diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/ReindexIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/ReindexIT.java index 78fb2aef02ee0..cbee86c34c360 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/ReindexIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/ReindexIT.java @@ -112,10 +112,9 @@ public void testReindex() throws IOException { reindexRequest.setRefresh(true); reindexRequest.setRequireAlias(true); - OpenSearchStatusException exception = expectThrows( - OpenSearchStatusException.class, - () -> { execute(reindexRequest, highLevelClient()::reindex, highLevelClient()::reindexAsync); } - ); + OpenSearchStatusException exception = expectThrows(OpenSearchStatusException.class, () -> { + execute(reindexRequest, highLevelClient()::reindex, highLevelClient()::reindexAsync); + }); assertEquals(RestStatus.NOT_FOUND, exception.status()); assertEquals( "OpenSearch exception [type=index_not_found_exception, reason=no such index [dest] and [require_alias] request flag is [true] and [dest] is not an alias]", diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/RestHighLevelClientTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/RestHighLevelClientTests.java index 5aa095431456c..ddd17a9c3c214 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/RestHighLevelClientTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/RestHighLevelClientTests.java @@ -425,13 +425,9 @@ public void testPerformRequestOnSuccess() throws IOException { { IOException ioe = expectThrows( IOException.class, - () -> restHighLevelClient.performRequest( - mainRequest, - requestConverter, - RequestOptions.DEFAULT, - response -> { throw new IllegalStateException(); }, - Collections.emptySet() - ) + () -> restHighLevelClient.performRequest(mainRequest, requestConverter, RequestOptions.DEFAULT, response -> { + throw new IllegalStateException(); + }, Collections.emptySet()) ); assertEquals( "Unable to parse response body for Response{requestLine=GET / http/1.1, host=http://localhost:9200, " @@ -573,13 +569,9 @@ public void testPerformRequestOnResponseExceptionWithIgnoresErrorNoBody() throws when(restClient.performRequest(any(Request.class))).thenThrow(responseException); OpenSearchException openSearchException = expectThrows( OpenSearchException.class, - () -> restHighLevelClient.performRequest( - mainRequest, - requestConverter, - RequestOptions.DEFAULT, - response -> { throw new IllegalStateException(); }, - Collections.singleton(404) - ) + () -> restHighLevelClient.performRequest(mainRequest, requestConverter, RequestOptions.DEFAULT, response -> { + throw new IllegalStateException(); + }, Collections.singleton(404)) ); assertEquals(RestStatus.NOT_FOUND, openSearchException.status()); assertSame(responseException, openSearchException.getCause()); @@ -596,13 +588,9 @@ public void testPerformRequestOnResponseExceptionWithIgnoresErrorValidBody() thr when(restClient.performRequest(any(Request.class))).thenThrow(responseException); OpenSearchException openSearchException = expectThrows( OpenSearchException.class, - () -> restHighLevelClient.performRequest( - mainRequest, - requestConverter, - RequestOptions.DEFAULT, - response -> { throw new IllegalStateException(); }, - Collections.singleton(404) - ) + () -> restHighLevelClient.performRequest(mainRequest, requestConverter, RequestOptions.DEFAULT, response -> { + throw new IllegalStateException(); + }, Collections.singleton(404)) ); assertEquals(RestStatus.NOT_FOUND, openSearchException.status()); assertSame(responseException, openSearchException.getSuppressed()[0]); diff --git a/modules/analysis-common/src/test/java/org/opensearch/analysis/common/SynonymsAnalysisTests.java b/modules/analysis-common/src/test/java/org/opensearch/analysis/common/SynonymsAnalysisTests.java index 2618c106d9275..733004cafcadc 100644 --- a/modules/analysis-common/src/test/java/org/opensearch/analysis/common/SynonymsAnalysisTests.java +++ b/modules/analysis-common/src/test/java/org/opensearch/analysis/common/SynonymsAnalysisTests.java @@ -240,10 +240,9 @@ public void testShingleFilters() { .build(); IndexSettings idxSettings = IndexSettingsModule.newIndexSettings("index", settings); - expectThrows( - IllegalArgumentException.class, - () -> { indexAnalyzers = createTestAnalysis(idxSettings, settings, new CommonAnalysisModulePlugin()).indexAnalyzers; } - ); + expectThrows(IllegalArgumentException.class, () -> { + indexAnalyzers = createTestAnalysis(idxSettings, settings, new CommonAnalysisModulePlugin()).indexAnalyzers; + }); } @@ -301,7 +300,9 @@ public void testPreconfiguredTokenFilters() throws IOException { IllegalArgumentException e = expectThrows( IllegalArgumentException.class, "Expected exception for factory " + tf.getName(), - () -> { tf.get(idxSettings, null, tf.getName(), settings).getSynonymFilter(); } + () -> { + tf.get(idxSettings, null, tf.getName(), settings).getSynonymFilter(); + } ); assertEquals(tf.getName(), "Token filter [" + tf.getName() + "] cannot be used to parse synonyms", e.getMessage()); } else { diff --git a/modules/geo/src/test/java/org/opensearch/geo/search/aggregations/bucket/geogrid/GeoGridAggregatorTestCase.java b/modules/geo/src/test/java/org/opensearch/geo/search/aggregations/bucket/geogrid/GeoGridAggregatorTestCase.java index 5ec10a7f4f7cf..6766d31b0491e 100644 --- a/modules/geo/src/test/java/org/opensearch/geo/search/aggregations/bucket/geogrid/GeoGridAggregatorTestCase.java +++ b/modules/geo/src/test/java/org/opensearch/geo/search/aggregations/bucket/geogrid/GeoGridAggregatorTestCase.java @@ -123,7 +123,9 @@ public void testUnmapped() throws IOException { randomPrecision(), null, geoGrid -> { assertEquals(0, geoGrid.getBuckets().size()); }, - iw -> { iw.addDocument(Collections.singleton(new LatLonDocValuesField(FIELD_NAME, 10D, 10D))); } + iw -> { + iw.addDocument(Collections.singleton(new LatLonDocValuesField(FIELD_NAME, 10D, 10D))); + } ); } diff --git a/modules/ingest-geoip/src/test/java/org/opensearch/ingest/geoip/IngestGeoIpModulePluginTests.java b/modules/ingest-geoip/src/test/java/org/opensearch/ingest/geoip/IngestGeoIpModulePluginTests.java index e79354b3d7cd0..cbaab11bd4346 100644 --- a/modules/ingest-geoip/src/test/java/org/opensearch/ingest/geoip/IngestGeoIpModulePluginTests.java +++ b/modules/ingest-geoip/src/test/java/org/opensearch/ingest/geoip/IngestGeoIpModulePluginTests.java @@ -65,11 +65,9 @@ public void testThrowsFunctionsException() { GeoIpCache cache = new GeoIpCache(1); IllegalArgumentException ex = expectThrows( IllegalArgumentException.class, - () -> cache.putIfAbsent( - InetAddresses.forString("127.0.0.1"), - AbstractResponse.class, - ip -> { throw new IllegalArgumentException("bad"); } - ) + () -> cache.putIfAbsent(InetAddresses.forString("127.0.0.1"), AbstractResponse.class, ip -> { + throw new IllegalArgumentException("bad"); + }) ); assertEquals("bad", ex.getMessage()); } diff --git a/modules/lang-painless/src/test/java/org/opensearch/painless/AllowlistLoaderTests.java b/modules/lang-painless/src/test/java/org/opensearch/painless/AllowlistLoaderTests.java index 828ff2679128b..f378eff383a80 100644 --- a/modules/lang-painless/src/test/java/org/opensearch/painless/AllowlistLoaderTests.java +++ b/modules/lang-painless/src/test/java/org/opensearch/painless/AllowlistLoaderTests.java @@ -47,19 +47,15 @@ public class AllowlistLoaderTests extends ScriptTestCase { public void testUnknownAnnotations() { Map parsers = new HashMap<>(AllowlistAnnotationParser.BASE_ANNOTATION_PARSERS); - RuntimeException expected = expectThrows( - RuntimeException.class, - () -> { AllowlistLoader.loadFromResourceFiles(Allowlist.class, parsers, "org.opensearch.painless.annotation.unknown"); } - ); + RuntimeException expected = expectThrows(RuntimeException.class, () -> { + AllowlistLoader.loadFromResourceFiles(Allowlist.class, parsers, "org.opensearch.painless.annotation.unknown"); + }); assertEquals("invalid annotation: parser not found for [unknownAnnotation] [@unknownAnnotation]", expected.getCause().getMessage()); assertEquals(IllegalArgumentException.class, expected.getCause().getClass()); - expected = expectThrows( - RuntimeException.class, - () -> { - AllowlistLoader.loadFromResourceFiles(Allowlist.class, parsers, "org.opensearch.painless.annotation.unknown_with_options"); - } - ); + expected = expectThrows(RuntimeException.class, () -> { + AllowlistLoader.loadFromResourceFiles(Allowlist.class, parsers, "org.opensearch.painless.annotation.unknown_with_options"); + }); assertEquals( "invalid annotation: parser not found for [unknownAnootationWithMessage] [@unknownAnootationWithMessage[arg=\"arg value\"]]", expected.getCause().getMessage() diff --git a/modules/lang-painless/src/test/java/org/opensearch/painless/DefBootstrapTests.java b/modules/lang-painless/src/test/java/org/opensearch/painless/DefBootstrapTests.java index 856f17d4aae13..ae860d177cce1 100644 --- a/modules/lang-painless/src/test/java/org/opensearch/painless/DefBootstrapTests.java +++ b/modules/lang-painless/src/test/java/org/opensearch/painless/DefBootstrapTests.java @@ -157,21 +157,13 @@ public void testMegamorphic() throws Throwable { map.put("a", "b"); assertEquals(2, (int) handle.invokeExact((Object) map)); - final IllegalArgumentException iae = expectThrows( - IllegalArgumentException.class, - () -> { Integer.toString((int) handle.invokeExact(new Object())); } - ); + final IllegalArgumentException iae = expectThrows(IllegalArgumentException.class, () -> { + Integer.toString((int) handle.invokeExact(new Object())); + }); assertEquals("dynamic method [java.lang.Object, size/0] not found", iae.getMessage()); - assertTrue( - "Does not fail inside ClassValue.computeValue()", - Arrays.stream(iae.getStackTrace()) - .anyMatch( - e -> { - return e.getMethodName().equals("computeValue") - && e.getClassName().startsWith("org.opensearch.painless.DefBootstrap$PIC$"); - } - ) - ); + assertTrue("Does not fail inside ClassValue.computeValue()", Arrays.stream(iae.getStackTrace()).anyMatch(e -> { + return e.getMethodName().equals("computeValue") && e.getClassName().startsWith("org.opensearch.painless.DefBootstrap$PIC$"); + })); } // test operators with null guards diff --git a/modules/lang-painless/src/test/java/org/opensearch/painless/FunctionRefTests.java b/modules/lang-painless/src/test/java/org/opensearch/painless/FunctionRefTests.java index 2ed1fa49d0bda..065e0fbd1f4e2 100644 --- a/modules/lang-painless/src/test/java/org/opensearch/painless/FunctionRefTests.java +++ b/modules/lang-painless/src/test/java/org/opensearch/painless/FunctionRefTests.java @@ -268,18 +268,16 @@ public void testInterfaceStaticMethod() { } public void testMethodMissing() { - Exception e = expectScriptThrows( - IllegalArgumentException.class, - () -> { exec("List l = [2, 1]; l.sort(Integer::bogus); return l.get(0);"); } - ); + Exception e = expectScriptThrows(IllegalArgumentException.class, () -> { + exec("List l = [2, 1]; l.sort(Integer::bogus); return l.get(0);"); + }); assertThat(e.getMessage(), containsString("function reference [Integer::bogus/2] matching [java.util.Comparator")); } public void testQualifiedMethodMissing() { - Exception e = expectScriptThrows( - IllegalArgumentException.class, - () -> { exec("List l = [2, 1]; l.sort(java.time.Instant::bogus); return l.get(0);", false); } - ); + Exception e = expectScriptThrows(IllegalArgumentException.class, () -> { + exec("List l = [2, 1]; l.sort(java.time.Instant::bogus); return l.get(0);", false); + }); assertThat( e.getMessage(), containsString("function reference [java.time.Instant::bogus/2] matching [java.util.Comparator, compare/2") @@ -287,26 +285,23 @@ public void testQualifiedMethodMissing() { } public void testClassMissing() { - Exception e = expectScriptThrows( - IllegalArgumentException.class, - () -> { exec("List l = [2, 1]; l.sort(Bogus::bogus); return l.get(0);", false); } - ); + Exception e = expectScriptThrows(IllegalArgumentException.class, () -> { + exec("List l = [2, 1]; l.sort(Bogus::bogus); return l.get(0);", false); + }); assertThat(e.getMessage(), endsWith("variable [Bogus] is not defined")); } public void testQualifiedClassMissing() { - Exception e = expectScriptThrows( - IllegalArgumentException.class, - () -> { exec("List l = [2, 1]; l.sort(org.joda.time.BogusDateTime::bogus); return l.get(0);", false); } - ); + Exception e = expectScriptThrows(IllegalArgumentException.class, () -> { + exec("List l = [2, 1]; l.sort(org.joda.time.BogusDateTime::bogus); return l.get(0);", false); + }); assertEquals("variable [org.joda.time.BogusDateTime] is not defined", e.getMessage()); } public void testNotFunctionalInterface() { - IllegalArgumentException expected = expectScriptThrows( - IllegalArgumentException.class, - () -> { exec("List l = new ArrayList(); l.add(2); l.add(1); l.add(Integer::bogus); return l.get(0);"); } - ); + IllegalArgumentException expected = expectScriptThrows(IllegalArgumentException.class, () -> { + exec("List l = new ArrayList(); l.add(2); l.add(1); l.add(Integer::bogus); return l.get(0);"); + }); assertThat( expected.getMessage(), containsString("cannot convert function reference [Integer::bogus] to a non-functional interface [def]") @@ -314,17 +309,15 @@ public void testNotFunctionalInterface() { } public void testIncompatible() { - expectScriptThrows( - ClassCastException.class, - () -> { exec("List l = new ArrayList(); l.add(2); l.add(1); l.sort(String::startsWith); return l.get(0);"); } - ); + expectScriptThrows(ClassCastException.class, () -> { + exec("List l = new ArrayList(); l.add(2); l.add(1); l.sort(String::startsWith); return l.get(0);"); + }); } public void testWrongArity() { - IllegalArgumentException expected = expectScriptThrows( - IllegalArgumentException.class, - () -> { exec("Optional.empty().orElseGet(String::startsWith);"); } - ); + IllegalArgumentException expected = expectScriptThrows(IllegalArgumentException.class, () -> { + exec("Optional.empty().orElseGet(String::startsWith);"); + }); assertThat( expected.getMessage(), containsString("function reference [String::startsWith/0] matching [java.util.function.Supplier") @@ -332,18 +325,16 @@ public void testWrongArity() { } public void testWrongArityNotEnough() { - IllegalArgumentException expected = expectScriptThrows( - IllegalArgumentException.class, - () -> { exec("List l = new ArrayList(); l.add(2); l.add(1); l.sort(String::isEmpty);"); } - ); + IllegalArgumentException expected = expectScriptThrows(IllegalArgumentException.class, () -> { + exec("List l = new ArrayList(); l.add(2); l.add(1); l.sort(String::isEmpty);"); + }); assertThat(expected.getMessage(), containsString("function reference [String::isEmpty/2] matching [java.util.Comparator")); } public void testWrongArityDef() { - IllegalArgumentException expected = expectScriptThrows( - IllegalArgumentException.class, - () -> { exec("def y = Optional.empty(); return y.orElseGet(String::startsWith);"); } - ); + IllegalArgumentException expected = expectScriptThrows(IllegalArgumentException.class, () -> { + exec("def y = Optional.empty(); return y.orElseGet(String::startsWith);"); + }); assertThat( expected.getMessage(), containsString("function reference [String::startsWith/0] matching [java.util.function.Supplier") @@ -351,38 +342,33 @@ public void testWrongArityDef() { } public void testWrongArityNotEnoughDef() { - IllegalArgumentException expected = expectScriptThrows( - IllegalArgumentException.class, - () -> { exec("def l = new ArrayList(); l.add(2); l.add(1); l.sort(String::isEmpty);"); } - ); + IllegalArgumentException expected = expectScriptThrows(IllegalArgumentException.class, () -> { + exec("def l = new ArrayList(); l.add(2); l.add(1); l.sort(String::isEmpty);"); + }); assertThat(expected.getMessage(), containsString("function reference [String::isEmpty/2] matching [java.util.Comparator")); } public void testReturnVoid() { - Throwable expected = expectScriptThrows( - ClassCastException.class, - () -> { exec("StringBuilder b = new StringBuilder(); List l = [1, 2]; l.stream().mapToLong(b::setLength).sum();"); } - ); + Throwable expected = expectScriptThrows(ClassCastException.class, () -> { + exec("StringBuilder b = new StringBuilder(); List l = [1, 2]; l.stream().mapToLong(b::setLength).sum();"); + }); assertThat(expected.getMessage(), containsString("Cannot cast from [void] to [long].")); } public void testReturnVoidDef() { - Exception expected = expectScriptThrows( - LambdaConversionException.class, - () -> { exec("StringBuilder b = new StringBuilder(); def l = [1, 2]; l.stream().mapToLong(b::setLength);"); } - ); + Exception expected = expectScriptThrows(LambdaConversionException.class, () -> { + exec("StringBuilder b = new StringBuilder(); def l = [1, 2]; l.stream().mapToLong(b::setLength);"); + }); assertThat(expected.getMessage(), containsString("lambda expects return type [long], but found return type [void]")); - expected = expectScriptThrows( - LambdaConversionException.class, - () -> { exec("def b = new StringBuilder(); def l = [1, 2]; l.stream().mapToLong(b::setLength);"); } - ); + expected = expectScriptThrows(LambdaConversionException.class, () -> { + exec("def b = new StringBuilder(); def l = [1, 2]; l.stream().mapToLong(b::setLength);"); + }); assertThat(expected.getMessage(), containsString("lambda expects return type [long], but found return type [void]")); - expected = expectScriptThrows( - LambdaConversionException.class, - () -> { exec("def b = new StringBuilder(); List l = [1, 2]; l.stream().mapToLong(b::setLength);"); } - ); + expected = expectScriptThrows(LambdaConversionException.class, () -> { + exec("def b = new StringBuilder(); List l = [1, 2]; l.stream().mapToLong(b::setLength);"); + }); assertThat(expected.getMessage(), containsString("lambda expects return type [long], but found return type [void]")); } } diff --git a/modules/lang-painless/src/test/java/org/opensearch/painless/FunctionTests.java b/modules/lang-painless/src/test/java/org/opensearch/painless/FunctionTests.java index 77b6e8f0b3d5c..45efaa2c8a5a4 100644 --- a/modules/lang-painless/src/test/java/org/opensearch/painless/FunctionTests.java +++ b/modules/lang-painless/src/test/java/org/opensearch/painless/FunctionTests.java @@ -82,10 +82,9 @@ public void testReturnsAreUnboxedIfNeeded() { } public void testDuplicates() { - Exception expected = expectScriptThrows( - IllegalArgumentException.class, - () -> { exec("void test(int x) {x = 2;} void test(def y) {y = 3;} test()"); } - ); + Exception expected = expectScriptThrows(IllegalArgumentException.class, () -> { + exec("void test(int x) {x = 2;} void test(def y) {y = 3;} test()"); + }); assertThat(expected.getMessage(), containsString("found duplicate function")); } @@ -108,23 +107,20 @@ public void testInfiniteLoop() { public void testReturnVoid() { assertEquals(null, exec("void test(StringBuilder b, int i) {b.setLength(i)} test(new StringBuilder(), 1)")); - Exception expected = expectScriptThrows( - IllegalArgumentException.class, - () -> { exec("int test(StringBuilder b, int i) {b.setLength(i)} test(new StringBuilder(), 1)"); } - ); + Exception expected = expectScriptThrows(IllegalArgumentException.class, () -> { + exec("int test(StringBuilder b, int i) {b.setLength(i)} test(new StringBuilder(), 1)"); + }); assertEquals( "invalid function definition: " + "not all paths provide a return value for function [test] with [2] parameters", expected.getMessage() ); - expected = expectScriptThrows( - ClassCastException.class, - () -> { exec("int test(StringBuilder b, int i) {return b.setLength(i)} test(new StringBuilder(), 1)"); } - ); + expected = expectScriptThrows(ClassCastException.class, () -> { + exec("int test(StringBuilder b, int i) {return b.setLength(i)} test(new StringBuilder(), 1)"); + }); assertEquals("Cannot cast from [void] to [int].", expected.getMessage()); - expected = expectScriptThrows( - ClassCastException.class, - () -> { exec("def test(StringBuilder b, int i) {return b.setLength(i)} test(new StringBuilder(), 1)"); } - ); + expected = expectScriptThrows(ClassCastException.class, () -> { + exec("def test(StringBuilder b, int i) {return b.setLength(i)} test(new StringBuilder(), 1)"); + }); assertEquals("Cannot cast from [void] to [def].", expected.getMessage()); } } diff --git a/modules/lang-painless/src/test/java/org/opensearch/painless/GeneralCastTests.java b/modules/lang-painless/src/test/java/org/opensearch/painless/GeneralCastTests.java index 225dbd51819de..27930e2cb43d8 100644 --- a/modules/lang-painless/src/test/java/org/opensearch/painless/GeneralCastTests.java +++ b/modules/lang-painless/src/test/java/org/opensearch/painless/GeneralCastTests.java @@ -293,14 +293,12 @@ public void testIllegalExplicitConversionsDef() { } public void testIllegalVoidCasts() { - expectScriptThrows( - IllegalArgumentException.class, - () -> { exec("def map = ['a': 1,'b': 2,'c': 3]; map.c = Collections.sort(new ArrayList(map.keySet()));"); } - ); - expectScriptThrows( - IllegalArgumentException.class, - () -> { exec("Map map = ['a': 1,'b': 2,'c': 3]; def x = new HashMap(); x.put(1, map.clear());"); } - ); + expectScriptThrows(IllegalArgumentException.class, () -> { + exec("def map = ['a': 1,'b': 2,'c': 3]; map.c = Collections.sort(new ArrayList(map.keySet()));"); + }); + expectScriptThrows(IllegalArgumentException.class, () -> { + exec("Map map = ['a': 1,'b': 2,'c': 3]; def x = new HashMap(); x.put(1, map.clear());"); + }); } public void testBoxedDefCalls() { diff --git a/modules/lang-painless/src/test/java/org/opensearch/painless/LambdaTests.java b/modules/lang-painless/src/test/java/org/opensearch/painless/LambdaTests.java index c1b19522021b8..8d0cbb4018801 100644 --- a/modules/lang-painless/src/test/java/org/opensearch/painless/LambdaTests.java +++ b/modules/lang-painless/src/test/java/org/opensearch/painless/LambdaTests.java @@ -173,28 +173,19 @@ public void testTwoCaptures() { } public void testCapturesAreReadOnly() { - IllegalArgumentException expected = expectScriptThrows( - IllegalArgumentException.class, - () -> { - exec( - "List l = new ArrayList(); l.add(1); l.add(1); " + "return l.stream().mapToInt(x -> { l = null; return x + 1 }).sum();" - ); - } - ); + IllegalArgumentException expected = expectScriptThrows(IllegalArgumentException.class, () -> { + exec("List l = new ArrayList(); l.add(1); l.add(1); " + "return l.stream().mapToInt(x -> { l = null; return x + 1 }).sum();"); + }); assertTrue(expected.getMessage().contains("is read-only")); } /** Lambda parameters shouldn't be able to mask a variable already in scope */ public void testNoParamMasking() { - IllegalArgumentException expected = expectScriptThrows( - IllegalArgumentException.class, - () -> { - exec( - "int x = 0; List l = new ArrayList(); l.add(1); l.add(1); " - + "return l.stream().mapToInt(x -> { x += 1; return x }).sum();" - ); - } - ); + IllegalArgumentException expected = expectScriptThrows(IllegalArgumentException.class, () -> { + exec( + "int x = 0; List l = new ArrayList(); l.add(1); l.add(1); " + "return l.stream().mapToInt(x -> { x += 1; return x }).sum();" + ); + }); assertTrue(expected.getMessage().contains("already defined")); } @@ -214,36 +205,30 @@ public void testNestedCaptureParams() { } public void testWrongArity() { - IllegalArgumentException expected = expectScriptThrows( - IllegalArgumentException.class, - false, - () -> { exec("Optional.empty().orElseGet(x -> x);"); } - ); + IllegalArgumentException expected = expectScriptThrows(IllegalArgumentException.class, false, () -> { + exec("Optional.empty().orElseGet(x -> x);"); + }); assertTrue(expected.getMessage().contains("Incorrect number of parameters")); } public void testWrongArityDef() { - IllegalArgumentException expected = expectScriptThrows( - IllegalArgumentException.class, - () -> { exec("def y = Optional.empty(); return y.orElseGet(x -> x);"); } - ); + IllegalArgumentException expected = expectScriptThrows(IllegalArgumentException.class, () -> { + exec("def y = Optional.empty(); return y.orElseGet(x -> x);"); + }); assertTrue(expected.getMessage(), expected.getMessage().contains("due to an incorrect number of arguments")); } public void testWrongArityNotEnough() { - IllegalArgumentException expected = expectScriptThrows( - IllegalArgumentException.class, - false, - () -> { exec("List l = new ArrayList(); l.add(1); l.add(1); " + "return l.stream().mapToInt(() -> 5).sum();"); } - ); + IllegalArgumentException expected = expectScriptThrows(IllegalArgumentException.class, false, () -> { + exec("List l = new ArrayList(); l.add(1); l.add(1); " + "return l.stream().mapToInt(() -> 5).sum();"); + }); assertTrue(expected.getMessage().contains("Incorrect number of parameters")); } public void testWrongArityNotEnoughDef() { - IllegalArgumentException expected = expectScriptThrows( - IllegalArgumentException.class, - () -> { exec("def l = new ArrayList(); l.add(1); l.add(1); " + "return l.stream().mapToInt(() -> 5).sum();"); } - ); + IllegalArgumentException expected = expectScriptThrows(IllegalArgumentException.class, () -> { + exec("def l = new ArrayList(); l.add(1); l.add(1); " + "return l.stream().mapToInt(() -> 5).sum();"); + }); assertTrue(expected.getMessage(), expected.getMessage().contains("due to an incorrect number of arguments")); } @@ -308,19 +293,17 @@ public void testReservedCapture() { } public void testReturnVoid() { - Throwable expected = expectScriptThrows( - ClassCastException.class, - () -> { exec("StringBuilder b = new StringBuilder(); List l = [1, 2]; l.stream().mapToLong(i -> b.setLength(i))"); } - ); + Throwable expected = expectScriptThrows(ClassCastException.class, () -> { + exec("StringBuilder b = new StringBuilder(); List l = [1, 2]; l.stream().mapToLong(i -> b.setLength(i))"); + }); assertThat(expected.getMessage(), containsString("Cannot cast from [void] to [long].")); } public void testReturnVoidDef() { // If we can catch the error at compile time we do - Exception expected = expectScriptThrows( - ClassCastException.class, - () -> { exec("StringBuilder b = new StringBuilder(); def l = [1, 2]; l.stream().mapToLong(i -> b.setLength(i))"); } - ); + Exception expected = expectScriptThrows(ClassCastException.class, () -> { + exec("StringBuilder b = new StringBuilder(); def l = [1, 2]; l.stream().mapToLong(i -> b.setLength(i))"); + }); assertThat(expected.getMessage(), containsString("Cannot cast from [void] to [def].")); // Otherwise we convert the void into a null diff --git a/modules/lang-painless/src/test/java/org/opensearch/painless/OverloadTests.java b/modules/lang-painless/src/test/java/org/opensearch/painless/OverloadTests.java index 16f3c16a59548..02fa18ec07178 100644 --- a/modules/lang-painless/src/test/java/org/opensearch/painless/OverloadTests.java +++ b/modules/lang-painless/src/test/java/org/opensearch/painless/OverloadTests.java @@ -38,20 +38,18 @@ public class OverloadTests extends ScriptTestCase { public void testMethod() { // assertEquals(2, exec("return 'abc123abc'.indexOf('c');")); // assertEquals(8, exec("return 'abc123abc'.indexOf('c', 3);")); - IllegalArgumentException expected = expectScriptThrows( - IllegalArgumentException.class, - () -> { exec("return 'abc123abc'.indexOf('c', 3, 'bogus');"); } - ); + IllegalArgumentException expected = expectScriptThrows(IllegalArgumentException.class, () -> { + exec("return 'abc123abc'.indexOf('c', 3, 'bogus');"); + }); assertTrue(expected.getMessage().contains("[java.lang.String, indexOf/3]")); } public void testMethodDynamic() { assertEquals(2, exec("def x = 'abc123abc'; return x.indexOf('c');")); assertEquals(8, exec("def x = 'abc123abc'; return x.indexOf('c', 3);")); - IllegalArgumentException expected = expectScriptThrows( - IllegalArgumentException.class, - () -> { exec("def x = 'abc123abc'; return x.indexOf('c', 3, 'bogus');"); } - ); + IllegalArgumentException expected = expectScriptThrows(IllegalArgumentException.class, () -> { + exec("def x = 'abc123abc'; return x.indexOf('c', 3, 'bogus');"); + }); assertTrue(expected.getMessage().contains("dynamic method [java.lang.String, indexOf/3] not found")); } diff --git a/modules/lang-painless/src/test/java/org/opensearch/painless/StringTests.java b/modules/lang-painless/src/test/java/org/opensearch/painless/StringTests.java index d344a9c2a31f1..b9586924d4fcd 100644 --- a/modules/lang-painless/src/test/java/org/opensearch/painless/StringTests.java +++ b/modules/lang-painless/src/test/java/org/opensearch/painless/StringTests.java @@ -182,11 +182,9 @@ public void testStringAndCharacter() { assertEquals('c', exec("String s = \"c\"; (char)s")); assertEquals('c', exec("String s = 'c'; (char)s")); - ClassCastException expected = expectScriptThrows( - ClassCastException.class, - false, - () -> { assertEquals("cc", exec("return (String)(char)\"cc\"")); } - ); + ClassCastException expected = expectScriptThrows(ClassCastException.class, false, () -> { + assertEquals("cc", exec("return (String)(char)\"cc\"")); + }); assertTrue(expected.getMessage().contains("cannot cast java.lang.String with length not equal to one to char")); expected = expectScriptThrows(ClassCastException.class, false, () -> { assertEquals("cc", exec("return (String)(char)'cc'")); }); diff --git a/modules/lang-painless/src/test/java/org/opensearch/painless/WhenThingsGoWrongTests.java b/modules/lang-painless/src/test/java/org/opensearch/painless/WhenThingsGoWrongTests.java index fb8d2eccfa043..3f12bf57a0e33 100644 --- a/modules/lang-painless/src/test/java/org/opensearch/painless/WhenThingsGoWrongTests.java +++ b/modules/lang-painless/src/test/java/org/opensearch/painless/WhenThingsGoWrongTests.java @@ -57,10 +57,9 @@ public void testNullPointer() { public void testScriptStack() { for (String type : new String[] { "String", "def " }) { // trigger NPE at line 1 of the script - ScriptException exception = expectThrows( - ScriptException.class, - () -> { exec(type + " x = null; boolean y = x.isEmpty();\n" + "return y;"); } - ); + ScriptException exception = expectThrows(ScriptException.class, () -> { + exec(type + " x = null; boolean y = x.isEmpty();\n" + "return y;"); + }); // null deref at x.isEmpty(), the '.' is offset 30 assertScriptElementColumn(30, exception); assertScriptStack(exception, "y = x.isEmpty();\n", " ^---- HERE"); @@ -84,12 +83,9 @@ public void testScriptStack() { assertThat(exception.getCause(), instanceOf(NullPointerException.class)); // trigger NPE at line 4 in script (inside conditional) - exception = expectThrows( - ScriptException.class, - () -> { - exec(type + " x = null;\n" + "boolean y = false;\n" + "if (!y) {\n" + " y = x.isEmpty();\n" + "}\n" + "return y;"); - } - ); + exception = expectThrows(ScriptException.class, () -> { + exec(type + " x = null;\n" + "boolean y = false;\n" + "if (!y) {\n" + " y = x.isEmpty();\n" + "}\n" + "return y;"); + }); // null deref at x.isEmpty(), the '.' is offset 53 assertScriptElementColumn(53, exception); assertScriptStack(exception, "y = x.isEmpty();\n}\n", " ^---- HERE"); @@ -121,10 +117,9 @@ public void testInvalidShift() { } public void testBogusParameter() { - IllegalArgumentException expected = expectThrows( - IllegalArgumentException.class, - () -> { exec("return 5;", null, Collections.singletonMap("bogusParameterKey", "bogusParameterValue"), true); } - ); + IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> { + exec("return 5;", null, Collections.singletonMap("bogusParameterKey", "bogusParameterValue"), true); + }); assertTrue(expected.getMessage().contains("Unrecognized compile-time parameter")); } @@ -178,10 +173,9 @@ public void testLoopLimits() { } public void testIllegalDynamicMethod() { - IllegalArgumentException expected = expectScriptThrows( - IllegalArgumentException.class, - () -> { exec("def x = 'test'; return x.getClass().toString()"); } - ); + IllegalArgumentException expected = expectScriptThrows(IllegalArgumentException.class, () -> { + exec("def x = 'test'; return x.getClass().toString()"); + }); assertTrue(expected.getMessage().contains("dynamic method [java.lang.String, getClass/0] not found")); } diff --git a/modules/percolator/src/internalClusterTest/java/org/opensearch/percolator/PercolatorQuerySearchIT.java b/modules/percolator/src/internalClusterTest/java/org/opensearch/percolator/PercolatorQuerySearchIT.java index bc518b7facc80..a0b04f62a84b6 100644 --- a/modules/percolator/src/internalClusterTest/java/org/opensearch/percolator/PercolatorQuerySearchIT.java +++ b/modules/percolator/src/internalClusterTest/java/org/opensearch/percolator/PercolatorQuerySearchIT.java @@ -436,10 +436,9 @@ public void testPercolatorQueryExistingDocumentSourceDisabled() throws Exception client().admin().indices().prepareRefresh().get(); logger.info("percolating empty doc with source disabled"); - IllegalArgumentException e = expectThrows( - IllegalArgumentException.class, - () -> { client().prepareSearch().setQuery(new PercolateQueryBuilder("query", "test", "1", null, null, null)).get(); } - ); + IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> { + client().prepareSearch().setQuery(new PercolateQueryBuilder("query", "test", "1", null, null, null)).get(); + }); assertThat(e.getMessage(), containsString("source disabled")); } diff --git a/modules/percolator/src/test/java/org/opensearch/percolator/PercolateQueryBuilderTests.java b/modules/percolator/src/test/java/org/opensearch/percolator/PercolateQueryBuilderTests.java index c8faa46dd3451..5014b838d94e3 100644 --- a/modules/percolator/src/test/java/org/opensearch/percolator/PercolateQueryBuilderTests.java +++ b/modules/percolator/src/test/java/org/opensearch/percolator/PercolateQueryBuilderTests.java @@ -245,10 +245,9 @@ protected Set getObjectsHoldingArbitraryContent() { } public void testRequiredParameters() { - IllegalArgumentException e = expectThrows( - IllegalArgumentException.class, - () -> { new PercolateQueryBuilder(null, new BytesArray("{}"), XContentType.JSON); } - ); + IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> { + new PercolateQueryBuilder(null, new BytesArray("{}"), XContentType.JSON); + }); assertThat(e.getMessage(), equalTo("[field] is a required argument")); e = expectThrows( diff --git a/modules/rank-eval/src/main/java/org/opensearch/index/rankeval/DiscountedCumulativeGain.java b/modules/rank-eval/src/main/java/org/opensearch/index/rankeval/DiscountedCumulativeGain.java index 553da09aba7ad..5c7a4137fcb24 100644 --- a/modules/rank-eval/src/main/java/org/opensearch/index/rankeval/DiscountedCumulativeGain.java +++ b/modules/rank-eval/src/main/java/org/opensearch/index/rankeval/DiscountedCumulativeGain.java @@ -282,11 +282,9 @@ public XContentBuilder innerToXContent(XContentBuilder builder, Params params) t return builder; } - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - NAME, - true, - args -> { return new Detail((Double) args[0], (Double) args[1] != null ? (Double) args[1] : 0.0d, (Integer) args[2]); } - ); + private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>(NAME, true, args -> { + return new Detail((Double) args[0], (Double) args[1] != null ? (Double) args[1] : 0.0d, (Integer) args[2]); + }); static { PARSER.declareDouble(constructorArg(), DCG_FIELD); diff --git a/modules/rank-eval/src/main/java/org/opensearch/index/rankeval/ExpectedReciprocalRank.java b/modules/rank-eval/src/main/java/org/opensearch/index/rankeval/ExpectedReciprocalRank.java index ff840bd4b3446..eeb273abe408c 100644 --- a/modules/rank-eval/src/main/java/org/opensearch/index/rankeval/ExpectedReciprocalRank.java +++ b/modules/rank-eval/src/main/java/org/opensearch/index/rankeval/ExpectedReciprocalRank.java @@ -262,11 +262,9 @@ public XContentBuilder innerToXContent(XContentBuilder builder, Params params) t return builder.field(UNRATED_FIELD.getPreferredName(), this.unratedDocs); } - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - NAME, - true, - args -> { return new Detail((Integer) args[0]); } - ); + private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>(NAME, true, args -> { + return new Detail((Integer) args[0]); + }); static { PARSER.declareInt(constructorArg(), UNRATED_FIELD); diff --git a/modules/rank-eval/src/main/java/org/opensearch/index/rankeval/MeanReciprocalRank.java b/modules/rank-eval/src/main/java/org/opensearch/index/rankeval/MeanReciprocalRank.java index 351839176b8be..8410d7fb20bdd 100644 --- a/modules/rank-eval/src/main/java/org/opensearch/index/rankeval/MeanReciprocalRank.java +++ b/modules/rank-eval/src/main/java/org/opensearch/index/rankeval/MeanReciprocalRank.java @@ -219,11 +219,9 @@ public XContentBuilder innerToXContent(XContentBuilder builder, Params params) t return builder.field(FIRST_RELEVANT_RANK_FIELD.getPreferredName(), firstRelevantRank); } - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - NAME, - true, - args -> { return new Detail((Integer) args[0]); } - ); + private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>(NAME, true, args -> { + return new Detail((Integer) args[0]); + }); static { PARSER.declareInt(constructorArg(), FIRST_RELEVANT_RANK_FIELD); diff --git a/modules/rank-eval/src/test/java/org/opensearch/index/rankeval/DiscountedCumulativeGainTests.java b/modules/rank-eval/src/test/java/org/opensearch/index/rankeval/DiscountedCumulativeGainTests.java index f2cc572e4f0a1..1de854b91a6ae 100644 --- a/modules/rank-eval/src/test/java/org/opensearch/index/rankeval/DiscountedCumulativeGainTests.java +++ b/modules/rank-eval/src/test/java/org/opensearch/index/rankeval/DiscountedCumulativeGainTests.java @@ -346,11 +346,9 @@ public void testSerialization() throws IOException { } public void testEqualsAndHash() throws IOException { - checkEqualsAndHashCode( - createTestItem(), - original -> { return new DiscountedCumulativeGain(original.getNormalize(), original.getUnknownDocRating(), original.getK()); }, - DiscountedCumulativeGainTests::mutateTestItem - ); + checkEqualsAndHashCode(createTestItem(), original -> { + return new DiscountedCumulativeGain(original.getNormalize(), original.getUnknownDocRating(), original.getK()); + }, DiscountedCumulativeGainTests::mutateTestItem); } private static DiscountedCumulativeGain mutateTestItem(DiscountedCumulativeGain original) { diff --git a/modules/rank-eval/src/test/java/org/opensearch/index/rankeval/ExpectedReciprocalRankTests.java b/modules/rank-eval/src/test/java/org/opensearch/index/rankeval/ExpectedReciprocalRankTests.java index 656c6142b2a8c..c7573bc50e86b 100644 --- a/modules/rank-eval/src/test/java/org/opensearch/index/rankeval/ExpectedReciprocalRankTests.java +++ b/modules/rank-eval/src/test/java/org/opensearch/index/rankeval/ExpectedReciprocalRankTests.java @@ -213,11 +213,9 @@ public void testSerialization() throws IOException { } public void testEqualsAndHash() throws IOException { - checkEqualsAndHashCode( - createTestItem(), - original -> { return new ExpectedReciprocalRank(original.getMaxRelevance(), original.getUnknownDocRating(), original.getK()); }, - ExpectedReciprocalRankTests::mutateTestItem - ); + checkEqualsAndHashCode(createTestItem(), original -> { + return new ExpectedReciprocalRank(original.getMaxRelevance(), original.getUnknownDocRating(), original.getK()); + }, ExpectedReciprocalRankTests::mutateTestItem); } private static ExpectedReciprocalRank mutateTestItem(ExpectedReciprocalRank original) { diff --git a/modules/rank-eval/src/test/java/org/opensearch/index/rankeval/RatedDocumentTests.java b/modules/rank-eval/src/test/java/org/opensearch/index/rankeval/RatedDocumentTests.java index 84e471b18d16f..909024e2abe86 100644 --- a/modules/rank-eval/src/test/java/org/opensearch/index/rankeval/RatedDocumentTests.java +++ b/modules/rank-eval/src/test/java/org/opensearch/index/rankeval/RatedDocumentTests.java @@ -91,11 +91,9 @@ public void testSerialization() throws IOException { } public void testEqualsAndHash() throws IOException { - checkEqualsAndHashCode( - createRatedDocument(), - original -> { return new RatedDocument(original.getIndex(), original.getDocID(), original.getRating()); }, - RatedDocumentTests::mutateTestItem - ); + checkEqualsAndHashCode(createRatedDocument(), original -> { + return new RatedDocument(original.getIndex(), original.getDocID(), original.getRating()); + }, RatedDocumentTests::mutateTestItem); } private static RatedDocument mutateTestItem(RatedDocument original) { diff --git a/modules/reindex/src/test/java/org/opensearch/index/reindex/ClientScrollableHitSourceTests.java b/modules/reindex/src/test/java/org/opensearch/index/reindex/ClientScrollableHitSourceTests.java index 9333e5bd3dcc9..3a79a0b35e391 100644 --- a/modules/reindex/src/test/java/org/opensearch/index/reindex/ClientScrollableHitSourceTests.java +++ b/modules/reindex/src/test/java/org/opensearch/index/reindex/ClientScrollableHitSourceTests.java @@ -105,10 +105,9 @@ private static class ExpectedException extends RuntimeException { public void testRetryFail() { int retries = randomInt(10); - ExpectedException ex = expectThrows( - ExpectedException.class, - () -> { dotestBasicsWithRetry(retries, retries + 1, retries + 1, e -> { throw new ExpectedException(e); }); } - ); + ExpectedException ex = expectThrows(ExpectedException.class, () -> { + dotestBasicsWithRetry(retries, retries + 1, retries + 1, e -> { throw new ExpectedException(e); }); + }); assertThat(ex.getCause(), instanceOf(OpenSearchRejectedExecutionException.class)); } diff --git a/plugins/analysis-icu/src/test/java/org/opensearch/index/analysis/IcuAnalyzerTests.java b/plugins/analysis-icu/src/test/java/org/opensearch/index/analysis/IcuAnalyzerTests.java index e490248fc8122..c363bc6eb43f8 100644 --- a/plugins/analysis-icu/src/test/java/org/opensearch/index/analysis/IcuAnalyzerTests.java +++ b/plugins/analysis-icu/src/test/java/org/opensearch/index/analysis/IcuAnalyzerTests.java @@ -90,10 +90,9 @@ public void testBadSettings() { Settings settings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT).put("mode", "wrong").build(); IndexSettings idxSettings = IndexSettingsModule.newIndexSettings("index", settings); - IllegalArgumentException e = expectThrows( - IllegalArgumentException.class, - () -> { new IcuAnalyzerProvider(idxSettings, null, "icu", settings); } - ); + IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> { + new IcuAnalyzerProvider(idxSettings, null, "icu", settings); + }); assertThat(e.getMessage(), containsString("Unknown mode [wrong] in analyzer [icu], expected one of [compose, decompose]")); diff --git a/plugins/repository-hdfs/src/test/java/org/opensearch/repositories/hdfs/HaHdfsFailoverTestSuiteIT.java b/plugins/repository-hdfs/src/test/java/org/opensearch/repositories/hdfs/HaHdfsFailoverTestSuiteIT.java index e12b24f27dcdc..d0b63f17e3887 100644 --- a/plugins/repository-hdfs/src/test/java/org/opensearch/repositories/hdfs/HaHdfsFailoverTestSuiteIT.java +++ b/plugins/repository-hdfs/src/test/java/org/opensearch/repositories/hdfs/HaHdfsFailoverTestSuiteIT.java @@ -75,9 +75,9 @@ public void testHAFailoverWithRepository() throws Exception { String nn2Port = "10002"; if (ports.length() > 0) { final Path path = PathUtils.get(ports); - final List lines = AccessController.doPrivileged( - (PrivilegedExceptionAction>) () -> { return Files.readAllLines(path); } - ); + final List lines = AccessController.doPrivileged((PrivilegedExceptionAction>) () -> { + return Files.readAllLines(path); + }); nn1Port = lines.get(0); nn2Port = lines.get(1); } diff --git a/server/src/internalClusterTest/java/org/opensearch/action/admin/cluster/node/tasks/TasksIT.java b/server/src/internalClusterTest/java/org/opensearch/action/admin/cluster/node/tasks/TasksIT.java index 61059f83f0e77..62180412dbf98 100644 --- a/server/src/internalClusterTest/java/org/opensearch/action/admin/cluster/node/tasks/TasksIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/action/admin/cluster/node/tasks/TasksIT.java @@ -510,14 +510,12 @@ public void taskExecutionStarted(Task task, Boolean closeableInvoked) {} if (index != null) { index.join(); } - assertBusy( - () -> { - assertEquals( - emptyList(), - client().admin().cluster().prepareListTasks().setActions("indices:data/write/index*").get().getTasks() - ); - } - ); + assertBusy(() -> { + assertEquals( + emptyList(), + client().admin().cluster().prepareListTasks().setActions("indices:data/write/index*").get().getTasks() + ); + }); } } diff --git a/server/src/internalClusterTest/java/org/opensearch/action/bulk/BulkWithUpdatesIT.java b/server/src/internalClusterTest/java/org/opensearch/action/bulk/BulkWithUpdatesIT.java index 4cf3f3564c8eb..53afa53de92f3 100644 --- a/server/src/internalClusterTest/java/org/opensearch/action/bulk/BulkWithUpdatesIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/action/bulk/BulkWithUpdatesIT.java @@ -105,18 +105,9 @@ protected Map, Object>> pluginScripts() { scripts.put("ctx._source.field2 = 'value2'", vars -> srcScript(vars, source -> source.replace("field2", "value2"))); - scripts.put( - "throw script exception on unknown var", - vars -> { - throw new ScriptException( - "message", - null, - Collections.emptyList(), - "exception on unknown var", - CustomScriptPlugin.NAME - ); - } - ); + scripts.put("throw script exception on unknown var", vars -> { + throw new ScriptException("message", null, Collections.emptyList(), "exception on unknown var", CustomScriptPlugin.NAME); + }); scripts.put("ctx.op = \"none\"", vars -> ((Map) vars.get("ctx")).put("op", "none")); scripts.put("ctx.op = \"delete\"", vars -> ((Map) vars.get("ctx")).put("op", "delete")); diff --git a/server/src/internalClusterTest/java/org/opensearch/cluster/metadata/TemplateUpgradeServiceIT.java b/server/src/internalClusterTest/java/org/opensearch/cluster/metadata/TemplateUpgradeServiceIT.java index 604b0c903c70a..17d024dfb999d 100644 --- a/server/src/internalClusterTest/java/org/opensearch/cluster/metadata/TemplateUpgradeServiceIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/cluster/metadata/TemplateUpgradeServiceIT.java @@ -99,11 +99,9 @@ public Collection createComponents( IndexNameExpressionResolver expressionResolver, Supplier repositoriesServiceSupplier ) { - clusterService.getClusterSettings() - .addSettingsUpdateConsumer( - UPDATE_TEMPLATE_DUMMY_SETTING, - integer -> { logger.debug("the template dummy setting was updated to {}", integer); } - ); + clusterService.getClusterSettings().addSettingsUpdateConsumer(UPDATE_TEMPLATE_DUMMY_SETTING, integer -> { + logger.debug("the template dummy setting was updated to {}", integer); + }); return super.createComponents( client, clusterService, diff --git a/server/src/internalClusterTest/java/org/opensearch/indexing/IndexActionIT.java b/server/src/internalClusterTest/java/org/opensearch/indexing/IndexActionIT.java index 45fbb2651a96d..73d6d9aff7b72 100644 --- a/server/src/internalClusterTest/java/org/opensearch/indexing/IndexActionIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/indexing/IndexActionIT.java @@ -288,10 +288,9 @@ public void testInvalidIndexName() { } public void testDocumentWithBlankFieldName() { - MapperParsingException e = expectThrows( - MapperParsingException.class, - () -> { client().prepareIndex("test").setId("1").setSource("", "value1_2").execute().actionGet(); } - ); + MapperParsingException e = expectThrows(MapperParsingException.class, () -> { + client().prepareIndex("test").setId("1").setSource("", "value1_2").execute().actionGet(); + }); assertThat(e.getMessage(), containsString("failed to parse")); assertThat(e.getRootCause().getMessage(), containsString("field name cannot be an empty string")); } diff --git a/server/src/internalClusterTest/java/org/opensearch/indices/replication/SegmentReplicationRelocationIT.java b/server/src/internalClusterTest/java/org/opensearch/indices/replication/SegmentReplicationRelocationIT.java index 645335c2f63a8..62db6b96d4e69 100644 --- a/server/src/internalClusterTest/java/org/opensearch/indices/replication/SegmentReplicationRelocationIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/indices/replication/SegmentReplicationRelocationIT.java @@ -555,13 +555,8 @@ public void testFlushAfterRelocation() throws Exception { // Verify if all docs are present in replica after relocation, if new relocated primary doesn't flush after relocation the below // assert will fail. - assertBusy( - () -> { - assertHitCount( - client(replicaNode).prepareSearch(INDEX_NAME).setPreference("_only_local").setSize(0).get(), - initialDocCount - ); - } - ); + assertBusy(() -> { + assertHitCount(client(replicaNode).prepareSearch(INDEX_NAME).setPreference("_only_local").setSize(0).get(), initialDocCount); + }); } } diff --git a/server/src/internalClusterTest/java/org/opensearch/indices/settings/UpdateSettingsIT.java b/server/src/internalClusterTest/java/org/opensearch/indices/settings/UpdateSettingsIT.java index af1fdfed6512a..beb0ea797bbec 100644 --- a/server/src/internalClusterTest/java/org/opensearch/indices/settings/UpdateSettingsIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/indices/settings/UpdateSettingsIT.java @@ -137,11 +137,9 @@ public static class DummySettingPlugin extends Plugin { @Override public void onIndexModule(IndexModule indexModule) { - indexModule.addSettingsUpdateConsumer( - DUMMY_SETTING, - (s) -> {}, - (s) -> { if (s.equals("boom")) throw new IllegalArgumentException("this setting goes boom"); } - ); + indexModule.addSettingsUpdateConsumer(DUMMY_SETTING, (s) -> {}, (s) -> { + if (s.equals("boom")) throw new IllegalArgumentException("this setting goes boom"); + }); } @Override diff --git a/server/src/main/java/org/opensearch/action/admin/cluster/settings/ClusterUpdateSettingsResponse.java b/server/src/main/java/org/opensearch/action/admin/cluster/settings/ClusterUpdateSettingsResponse.java index 31c5c8a551497..463a77a0dcf9a 100644 --- a/server/src/main/java/org/opensearch/action/admin/cluster/settings/ClusterUpdateSettingsResponse.java +++ b/server/src/main/java/org/opensearch/action/admin/cluster/settings/ClusterUpdateSettingsResponse.java @@ -59,7 +59,9 @@ public class ClusterUpdateSettingsResponse extends AcknowledgedResponse { private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( "cluster_update_settings_response", true, - args -> { return new ClusterUpdateSettingsResponse((boolean) args[0], (Settings) args[1], (Settings) args[2]); } + args -> { + return new ClusterUpdateSettingsResponse((boolean) args[0], (Settings) args[1], (Settings) args[2]); + } ); static { declareAcknowledgedField(PARSER); diff --git a/server/src/main/java/org/opensearch/action/admin/cluster/shards/routing/weighted/put/TransportAddWeightedRoutingAction.java b/server/src/main/java/org/opensearch/action/admin/cluster/shards/routing/weighted/put/TransportAddWeightedRoutingAction.java index 249e313c1f53b..56203d4edc3d0 100644 --- a/server/src/main/java/org/opensearch/action/admin/cluster/shards/routing/weighted/put/TransportAddWeightedRoutingAction.java +++ b/server/src/main/java/org/opensearch/action/admin/cluster/shards/routing/weighted/put/TransportAddWeightedRoutingAction.java @@ -81,12 +81,9 @@ protected void clusterManagerOperation( } weightedRoutingService.registerWeightedRoutingMetadata( request, - ActionListener.delegateFailure( - listener, - (delegatedListener, response) -> { - delegatedListener.onResponse(new ClusterPutWeightedRoutingResponse(response.isAcknowledged())); - } - ) + ActionListener.delegateFailure(listener, (delegatedListener, response) -> { + delegatedListener.onResponse(new ClusterPutWeightedRoutingResponse(response.isAcknowledged())); + }) ); } diff --git a/server/src/main/java/org/opensearch/action/admin/indices/create/AutoCreateAction.java b/server/src/main/java/org/opensearch/action/admin/indices/create/AutoCreateAction.java index 77f09f02c9a9c..556d46683f0ab 100644 --- a/server/src/main/java/org/opensearch/action/admin/indices/create/AutoCreateAction.java +++ b/server/src/main/java/org/opensearch/action/admin/indices/create/AutoCreateAction.java @@ -132,7 +132,9 @@ protected void clusterManagerOperation( new String[] { indexName }, ActiveShardCount.DEFAULT, request.timeout(), - shardsAcked -> { finalListener.onResponse(new CreateIndexResponse(true, shardsAcked, indexName)); }, + shardsAcked -> { + finalListener.onResponse(new CreateIndexResponse(true, shardsAcked, indexName)); + }, finalListener::onFailure ); } else { diff --git a/server/src/main/java/org/opensearch/action/ingest/SimulateExecutionService.java b/server/src/main/java/org/opensearch/action/ingest/SimulateExecutionService.java index ae66dafc954f9..82db29c950161 100644 --- a/server/src/main/java/org/opensearch/action/ingest/SimulateExecutionService.java +++ b/server/src/main/java/org/opensearch/action/ingest/SimulateExecutionService.java @@ -76,10 +76,9 @@ void executeDocument( pipeline.getVersion(), verbosePipelineProcessor ); - ingestDocument.executePipeline( - verbosePipeline, - (result, e) -> { handler.accept(new SimulateDocumentVerboseResult(processorResultList), e); } - ); + ingestDocument.executePipeline(verbosePipeline, (result, e) -> { + handler.accept(new SimulateDocumentVerboseResult(processorResultList), e); + }); } else { ingestDocument.executePipeline(pipeline, (result, e) -> { if (e == null) { diff --git a/server/src/main/java/org/opensearch/action/search/SearchTransportService.java b/server/src/main/java/org/opensearch/action/search/SearchTransportService.java index 8cf92ae5a23d8..13302f88fd87f 100644 --- a/server/src/main/java/org/opensearch/action/search/SearchTransportService.java +++ b/server/src/main/java/org/opensearch/action/search/SearchTransportService.java @@ -508,7 +508,9 @@ public static void registerRequestHandler(TransportService transportService, Sea FREE_PIT_CONTEXT_ACTION_NAME, ThreadPool.Names.SAME, PitFreeContextsRequest::new, - (request, channel, task) -> { channel.sendResponse(searchService.freeReaderContextsIfFound(request.getContextIds())); } + (request, channel, task) -> { + channel.sendResponse(searchService.freeReaderContextsIfFound(request.getContextIds())); + } ); TransportActionProxy.registerProxyAction(transportService, FREE_PIT_CONTEXT_ACTION_NAME, DeletePitResponse::new); diff --git a/server/src/main/java/org/opensearch/cluster/metadata/MetadataCreateDataStreamService.java b/server/src/main/java/org/opensearch/cluster/metadata/MetadataCreateDataStreamService.java index d7cb3b6dbaa46..65cc775662831 100644 --- a/server/src/main/java/org/opensearch/cluster/metadata/MetadataCreateDataStreamService.java +++ b/server/src/main/java/org/opensearch/cluster/metadata/MetadataCreateDataStreamService.java @@ -99,7 +99,9 @@ public void createDataStream(CreateDataStreamClusterStateUpdateRequest request, new String[] { firstBackingIndexName }, ActiveShardCount.DEFAULT, request.masterNodeTimeout(), - shardsAcked -> { finalListener.onResponse(new AcknowledgedResponse(true)); }, + shardsAcked -> { + finalListener.onResponse(new AcknowledgedResponse(true)); + }, finalListener::onFailure ); } else { diff --git a/server/src/main/java/org/opensearch/cluster/service/MasterService.java b/server/src/main/java/org/opensearch/cluster/service/MasterService.java index 780f12c12f134..03bc3219ac8f8 100644 --- a/server/src/main/java/org/opensearch/cluster/service/MasterService.java +++ b/server/src/main/java/org/opensearch/cluster/service/MasterService.java @@ -905,11 +905,9 @@ private ClusterTasksResult executeTasks(TaskInputs taskInputs, ClusterSt ); if (Assertions.ENABLED) { ClusterTasksResult finalClusterTasksResult = clusterTasksResult; - taskInputs.updateTasks.forEach( - updateTask -> { - assert finalClusterTasksResult.executionResults.containsKey(updateTask.task) : "missing task result for " + updateTask; - } - ); + taskInputs.updateTasks.forEach(updateTask -> { + assert finalClusterTasksResult.executionResults.containsKey(updateTask.task) : "missing task result for " + updateTask; + }); } return clusterTasksResult; diff --git a/server/src/main/java/org/opensearch/cluster/service/TaskBatcher.java b/server/src/main/java/org/opensearch/cluster/service/TaskBatcher.java index 686169f81e837..ed744f4f42d07 100644 --- a/server/src/main/java/org/opensearch/cluster/service/TaskBatcher.java +++ b/server/src/main/java/org/opensearch/cluster/service/TaskBatcher.java @@ -86,14 +86,9 @@ public void submitTasks(List tasks, @Nullable TimeValue t try { // convert to an identity map to check for dups based on task identity final Map tasksIdentity = tasks.stream() - .collect( - Collectors.toMap( - BatchedTask::getTask, - Function.identity(), - (a, b) -> { throw new IllegalStateException("cannot add duplicate task: " + a); }, - IdentityHashMap::new - ) - ); + .collect(Collectors.toMap(BatchedTask::getTask, Function.identity(), (a, b) -> { + throw new IllegalStateException("cannot add duplicate task: " + a); + }, IdentityHashMap::new)); LinkedHashSet newTasks = new LinkedHashSet<>(tasks); tasksPerBatchingKey.merge(firstTask.batchingKey, newTasks, (existingTasks, updatedTasks) -> { for (BatchedTask existing : existingTasks) { diff --git a/server/src/main/java/org/opensearch/extensions/rest/RestSendToExtensionAction.java b/server/src/main/java/org/opensearch/extensions/rest/RestSendToExtensionAction.java index 357be3a9fc2fe..247269e2f1f17 100644 --- a/server/src/main/java/org/opensearch/extensions/rest/RestSendToExtensionAction.java +++ b/server/src/main/java/org/opensearch/extensions/rest/RestSendToExtensionAction.java @@ -198,10 +198,9 @@ public String executor() { restExecuteOnExtensionResponse.getContent() ); // No constructor that includes headers so we roll our own - restExecuteOnExtensionResponse.getHeaders() - .entrySet() - .stream() - .forEach(e -> { e.getValue().stream().forEach(v -> restResponse.addHeader(e.getKey(), v)); }); + restExecuteOnExtensionResponse.getHeaders().entrySet().stream().forEach(e -> { + e.getValue().stream().forEach(v -> restResponse.addHeader(e.getKey(), v)); + }); return channel -> channel.sendResponse(restResponse); } diff --git a/server/src/main/java/org/opensearch/index/IndexModule.java b/server/src/main/java/org/opensearch/index/IndexModule.java index 0b8a983848305..5e8f95acdfe39 100644 --- a/server/src/main/java/org/opensearch/index/IndexModule.java +++ b/server/src/main/java/org/opensearch/index/IndexModule.java @@ -635,7 +635,9 @@ public MapperService newIndexMapperService( xContentRegistry, new SimilarityService(indexSettings, scriptService, similarities), mapperRegistry, - () -> { throw new UnsupportedOperationException("no index query shard context available"); }, + () -> { + throw new UnsupportedOperationException("no index query shard context available"); + }, () -> false, scriptService ); diff --git a/server/src/main/java/org/opensearch/index/IndexSortConfig.java b/server/src/main/java/org/opensearch/index/IndexSortConfig.java index 179d79f90cc8c..f73f96df4f9ad 100644 --- a/server/src/main/java/org/opensearch/index/IndexSortConfig.java +++ b/server/src/main/java/org/opensearch/index/IndexSortConfig.java @@ -221,10 +221,9 @@ public Sort buildIndexSort( } IndexFieldData fieldData; try { - fieldData = fieldDataLookup.apply( - ft, - () -> { throw new UnsupportedOperationException("index sorting not supported on runtime field [" + ft.name() + "]"); } - ); + fieldData = fieldDataLookup.apply(ft, () -> { + throw new UnsupportedOperationException("index sorting not supported on runtime field [" + ft.name() + "]"); + }); } catch (Exception e) { throw new IllegalArgumentException("docvalues not found for index sort field:[" + sortSpec.field + "]", e); } diff --git a/server/src/main/java/org/opensearch/index/IndexWarmer.java b/server/src/main/java/org/opensearch/index/IndexWarmer.java index 4b49a6c92dd9f..b62afe6b6dcfc 100644 --- a/server/src/main/java/org/opensearch/index/IndexWarmer.java +++ b/server/src/main/java/org/opensearch/index/IndexWarmer.java @@ -166,7 +166,9 @@ public TerminationHandle warmReader(final IndexShard indexShard, final OpenSearc IndexFieldData.Global ifd = indexFieldDataService.getForField( fieldType, indexFieldDataService.index().getName(), - () -> { throw new UnsupportedOperationException("search lookup not available when warming an index"); } + () -> { + throw new UnsupportedOperationException("search lookup not available when warming an index"); + } ); IndexFieldData global = ifd.loadGlobal(reader); if (reader.leaves().isEmpty() == false) { diff --git a/server/src/main/java/org/opensearch/index/analysis/AnalysisRegistry.java b/server/src/main/java/org/opensearch/index/analysis/AnalysisRegistry.java index 7a78d97edf360..4a7dc238a8c5d 100644 --- a/server/src/main/java/org/opensearch/index/analysis/AnalysisRegistry.java +++ b/server/src/main/java/org/opensearch/index/analysis/AnalysisRegistry.java @@ -645,7 +645,9 @@ public IndexAnalyzers build( charFilterFactoryFactories, tokenizerFactoryFactories ), - (k, v) -> { throw new IllegalStateException("already registered analyzer with name: " + entry.getKey()); } + (k, v) -> { + throw new IllegalStateException("already registered analyzer with name: " + entry.getKey()); + } ); } for (Map.Entry> entry : normalizerProviders.entrySet()) { diff --git a/server/src/main/java/org/opensearch/index/translog/Translog.java b/server/src/main/java/org/opensearch/index/translog/Translog.java index 3318f6858dc82..f9ddb946b7e59 100644 --- a/server/src/main/java/org/opensearch/index/translog/Translog.java +++ b/server/src/main/java/org/opensearch/index/translog/Translog.java @@ -2016,11 +2016,15 @@ public static String createEmptyTranslog( EMPTY_TRANSLOG_BUFFER_SIZE, minTranslogGeneration, initialGlobalCheckpoint, - () -> { throw new UnsupportedOperationException(); }, + () -> { + throw new UnsupportedOperationException(); + }, () -> { throw new UnsupportedOperationException(); }, primaryTerm, new TragicExceptionHolder(), - seqNo -> { throw new UnsupportedOperationException(); }, + seqNo -> { + throw new UnsupportedOperationException(); + }, BigArrays.NON_RECYCLING_INSTANCE ); writer.close(); diff --git a/server/src/main/java/org/opensearch/search/aggregations/bucket/composite/DoubleValuesSource.java b/server/src/main/java/org/opensearch/search/aggregations/bucket/composite/DoubleValuesSource.java index d05c78f540641..970f07b6a9d74 100644 --- a/server/src/main/java/org/opensearch/search/aggregations/bucket/composite/DoubleValuesSource.java +++ b/server/src/main/java/org/opensearch/search/aggregations/bucket/composite/DoubleValuesSource.java @@ -152,11 +152,9 @@ void setAfter(Comparable value) { } else if (value instanceof Number) { afterValue = ((Number) value).doubleValue(); } else { - afterValue = format.parseDouble( - value.toString(), - false, - () -> { throw new IllegalArgumentException("now() is not supported in [after] key"); } - ); + afterValue = format.parseDouble(value.toString(), false, () -> { + throw new IllegalArgumentException("now() is not supported in [after] key"); + }); } } diff --git a/server/src/main/java/org/opensearch/search/aggregations/bucket/composite/LongValuesSource.java b/server/src/main/java/org/opensearch/search/aggregations/bucket/composite/LongValuesSource.java index ec6410c2a9377..8f0e99b187c2d 100644 --- a/server/src/main/java/org/opensearch/search/aggregations/bucket/composite/LongValuesSource.java +++ b/server/src/main/java/org/opensearch/search/aggregations/bucket/composite/LongValuesSource.java @@ -170,11 +170,9 @@ protected void setAfter(Comparable value) { afterValue = null; } else { // parse the value from a string in case it is a date or a formatted unsigned long. - afterValue = format.parseLong( - value.toString(), - false, - () -> { throw new IllegalArgumentException("now() is not supported in [after] key"); } - ); + afterValue = format.parseLong(value.toString(), false, () -> { + throw new IllegalArgumentException("now() is not supported in [after] key"); + }); } } diff --git a/server/src/main/java/org/opensearch/search/aggregations/bucket/histogram/DateHistogramAggregator.java b/server/src/main/java/org/opensearch/search/aggregations/bucket/histogram/DateHistogramAggregator.java index 295dfec639de6..040621ce8ec34 100644 --- a/server/src/main/java/org/opensearch/search/aggregations/bucket/histogram/DateHistogramAggregator.java +++ b/server/src/main/java/org/opensearch/search/aggregations/bucket/histogram/DateHistogramAggregator.java @@ -162,34 +162,29 @@ public void collect(int doc, long owningBucketOrd) throws IOException { @Override public InternalAggregation[] buildAggregations(long[] owningBucketOrds) throws IOException { - return buildAggregationsForVariableBuckets( - owningBucketOrds, - bucketOrds, - (bucketValue, docCount, subAggregationResults) -> { - return new InternalDateHistogram.Bucket(bucketValue, docCount, keyed, formatter, subAggregationResults); - }, - (owningBucketOrd, buckets) -> { - // the contract of the histogram aggregation is that shards must return buckets ordered by key in ascending order - CollectionUtil.introSort(buckets, BucketOrder.key(true).comparator()); - - // value source will be null for unmapped fields - // Important: use `rounding` here, not `shardRounding` - InternalDateHistogram.EmptyBucketInfo emptyBucketInfo = minDocCount == 0 - ? new InternalDateHistogram.EmptyBucketInfo(rounding.withoutOffset(), buildEmptySubAggregations(), extendedBounds) - : null; - return new InternalDateHistogram( - name, - buckets, - order, - minDocCount, - rounding.offset(), - emptyBucketInfo, - formatter, - keyed, - metadata() - ); - } - ); + return buildAggregationsForVariableBuckets(owningBucketOrds, bucketOrds, (bucketValue, docCount, subAggregationResults) -> { + return new InternalDateHistogram.Bucket(bucketValue, docCount, keyed, formatter, subAggregationResults); + }, (owningBucketOrd, buckets) -> { + // the contract of the histogram aggregation is that shards must return buckets ordered by key in ascending order + CollectionUtil.introSort(buckets, BucketOrder.key(true).comparator()); + + // value source will be null for unmapped fields + // Important: use `rounding` here, not `shardRounding` + InternalDateHistogram.EmptyBucketInfo emptyBucketInfo = minDocCount == 0 + ? new InternalDateHistogram.EmptyBucketInfo(rounding.withoutOffset(), buildEmptySubAggregations(), extendedBounds) + : null; + return new InternalDateHistogram( + name, + buckets, + order, + minDocCount, + rounding.offset(), + emptyBucketInfo, + formatter, + keyed, + metadata() + ); + }); } @Override diff --git a/server/src/main/java/org/opensearch/search/aggregations/bucket/terms/TermsAggregatorFactory.java b/server/src/main/java/org/opensearch/search/aggregations/bucket/terms/TermsAggregatorFactory.java index b74c2712a58b4..61e422328ee9d 100644 --- a/server/src/main/java/org/opensearch/search/aggregations/bucket/terms/TermsAggregatorFactory.java +++ b/server/src/main/java/org/opensearch/search/aggregations/bucket/terms/TermsAggregatorFactory.java @@ -444,7 +444,7 @@ Aggregator create( && ordinalsValuesSource.supportsGlobalOrdinalsMapping() && // we use the static COLLECT_SEGMENT_ORDS to allow tests to force specific optimizations - (COLLECT_SEGMENT_ORDS != null ? COLLECT_SEGMENT_ORDS.booleanValue() : ratio <= 0.5 && maxOrd <= 2048)) { + (COLLECT_SEGMENT_ORDS != null ? COLLECT_SEGMENT_ORDS.booleanValue() : ratio <= 0.5 && maxOrd <= 2048)) { /* * We can use the low cardinality execution mode iff this aggregator: * - has no sub-aggregator AND diff --git a/server/src/main/java/org/opensearch/search/aggregations/pipeline/DerivativePipelineAggregator.java b/server/src/main/java/org/opensearch/search/aggregations/pipeline/DerivativePipelineAggregator.java index 4bdd2c3168fae..9151aaebd5f4c 100644 --- a/server/src/main/java/org/opensearch/search/aggregations/pipeline/DerivativePipelineAggregator.java +++ b/server/src/main/java/org/opensearch/search/aggregations/pipeline/DerivativePipelineAggregator.java @@ -95,9 +95,9 @@ public InternalAggregation reduce(InternalAggregation aggregation, ReduceContext if (xAxisUnits != null) { xDiff = (thisBucketKey.doubleValue() - lastBucketKey.doubleValue()) / xAxisUnits; } - final List aggs = StreamSupport.stream(bucket.getAggregations().spliterator(), false) - .map((p) -> { return (InternalAggregation) p; }) - .collect(Collectors.toList()); + final List aggs = StreamSupport.stream(bucket.getAggregations().spliterator(), false).map((p) -> { + return (InternalAggregation) p; + }).collect(Collectors.toList()); aggs.add(new InternalDerivative(name(), gradient, xDiff, formatter, metadata())); Bucket newBucket = factory.createBucket(factory.getKey(bucket), bucket.getDocCount(), InternalAggregations.from(aggs)); newBuckets.add(newBucket); diff --git a/server/src/test/java/org/opensearch/action/ActionListenerTests.java b/server/src/test/java/org/opensearch/action/ActionListenerTests.java index bf64b4ed8a1a5..e56deb6088722 100644 --- a/server/src/test/java/org/opensearch/action/ActionListenerTests.java +++ b/server/src/test/java/org/opensearch/action/ActionListenerTests.java @@ -266,10 +266,9 @@ public void onFailure(Exception e) { assertThat(assertionError.getCause(), instanceOf(IllegalArgumentException.class)); assertNull(exReference.get()); - assertionError = expectThrows( - AssertionError.class, - () -> ActionListener.completeWith(listener, () -> { throw new IllegalArgumentException(); }) - ); + assertionError = expectThrows(AssertionError.class, () -> ActionListener.completeWith(listener, () -> { + throw new IllegalArgumentException(); + })); assertThat(assertionError.getCause(), instanceOf(IllegalArgumentException.class)); assertThat(exReference.get(), instanceOf(IllegalArgumentException.class)); } diff --git a/server/src/test/java/org/opensearch/action/admin/cluster/configuration/TransportAddVotingConfigExclusionsActionTests.java b/server/src/test/java/org/opensearch/action/admin/cluster/configuration/TransportAddVotingConfigExclusionsActionTests.java index 03c6b5ab822c1..40a041e9b94e3 100644 --- a/server/src/test/java/org/opensearch/action/admin/cluster/configuration/TransportAddVotingConfigExclusionsActionTests.java +++ b/server/src/test/java/org/opensearch/action/admin/cluster/configuration/TransportAddVotingConfigExclusionsActionTests.java @@ -386,7 +386,9 @@ public void testExcludeAbsentNodesByNodeIds() throws InterruptedException { Strings.EMPTY_ARRAY, TimeValue.timeValueSeconds(30) ), - expectSuccess(e -> { countDownLatch.countDown(); }) + expectSuccess(e -> { + countDownLatch.countDown(); + }) ); assertTrue(countDownLatch.await(30, TimeUnit.SECONDS)); @@ -430,7 +432,9 @@ public void testExcludeAbsentNodesByNodeNames() throws InterruptedException { localNode, AddVotingConfigExclusionsAction.NAME, new AddVotingConfigExclusionsRequest("absent_node"), - expectSuccess(e -> { countDownLatch.countDown(); }) + expectSuccess(e -> { + countDownLatch.countDown(); + }) ); assertTrue(countDownLatch.await(30, TimeUnit.SECONDS)); diff --git a/server/src/test/java/org/opensearch/action/admin/indices/TransportAnalyzeActionTests.java b/server/src/test/java/org/opensearch/action/admin/indices/TransportAnalyzeActionTests.java index 17cc539a5d561..f575be74a3e9b 100644 --- a/server/src/test/java/org/opensearch/action/admin/indices/TransportAnalyzeActionTests.java +++ b/server/src/test/java/org/opensearch/action/admin/indices/TransportAnalyzeActionTests.java @@ -380,10 +380,9 @@ public void testGetIndexAnalyserWithoutIndexAnalyzers() { public void testGetFieldAnalyzerWithoutIndexAnalyzers() { AnalyzeAction.Request req = new AnalyzeAction.Request().field("field").text("text"); - IllegalArgumentException e = expectThrows( - IllegalArgumentException.class, - () -> { TransportAnalyzeAction.analyze(req, registry, null, maxTokenCount); } - ); + IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> { + TransportAnalyzeAction.analyze(req, registry, null, maxTokenCount); + }); assertEquals(e.getMessage(), "analysis based on a specific field requires an index"); } diff --git a/server/src/test/java/org/opensearch/action/admin/indices/create/CreateIndexRequestBuilderTests.java b/server/src/test/java/org/opensearch/action/admin/indices/create/CreateIndexRequestBuilderTests.java index 8b773e7d4dc3f..8ecd60803b52d 100644 --- a/server/src/test/java/org/opensearch/action/admin/indices/create/CreateIndexRequestBuilderTests.java +++ b/server/src/test/java/org/opensearch/action/admin/indices/create/CreateIndexRequestBuilderTests.java @@ -74,10 +74,9 @@ public void tearDown() throws Exception { public void testSetSource() throws IOException { CreateIndexRequestBuilder builder = new CreateIndexRequestBuilder(this.testClient, CreateIndexAction.INSTANCE); - OpenSearchParseException e = expectThrows( - OpenSearchParseException.class, - () -> { builder.setSource("{\"" + KEY + "\" : \"" + VALUE + "\"}", XContentType.JSON); } - ); + OpenSearchParseException e = expectThrows(OpenSearchParseException.class, () -> { + builder.setSource("{\"" + KEY + "\" : \"" + VALUE + "\"}", XContentType.JSON); + }); assertEquals(String.format(Locale.ROOT, "unknown key [%s] for create index", KEY), e.getMessage()); builder.setSource("{\"settings\" : {\"" + KEY + "\" : \"" + VALUE + "\"}}", XContentType.JSON); diff --git a/server/src/test/java/org/opensearch/action/admin/indices/get/GetIndexActionTests.java b/server/src/test/java/org/opensearch/action/admin/indices/get/GetIndexActionTests.java index 001efb32c2988..81e73c4889d3b 100644 --- a/server/src/test/java/org/opensearch/action/admin/indices/get/GetIndexActionTests.java +++ b/server/src/test/java/org/opensearch/action/admin/indices/get/GetIndexActionTests.java @@ -109,7 +109,9 @@ public void testIncludeDefaults() { "index.refresh_interval should be set as we are including defaults", defaultsResponse.getSetting(indexName, "index.refresh_interval") ), - exception -> { throw new AssertionError(exception); } + exception -> { + throw new AssertionError(exception); + } ) ); } @@ -124,7 +126,9 @@ public void testDoNotIncludeDefaults() { "index.refresh_interval should be null as it was never set", noDefaultsResponse.getSetting(indexName, "index.refresh_interval") ), - exception -> { throw new AssertionError(exception); } + exception -> { + throw new AssertionError(exception); + } ) ); } diff --git a/server/src/test/java/org/opensearch/action/bulk/BulkRequestParserTests.java b/server/src/test/java/org/opensearch/action/bulk/BulkRequestParserTests.java index 32a0b3723f7ae..c51c9f7ea77dc 100644 --- a/server/src/test/java/org/opensearch/action/bulk/BulkRequestParserTests.java +++ b/server/src/test/java/org/opensearch/action/bulk/BulkRequestParserTests.java @@ -58,49 +58,19 @@ public void testIndexRequest() throws IOException { }, req -> fail(), req -> fail()); assertTrue(parsed.get()); - parser.parse( - request, - "foo", - null, - null, - null, - true, - false, - XContentType.JSON, - indexRequest -> { assertTrue(indexRequest.isRequireAlias()); }, - req -> fail(), - req -> fail() - ); + parser.parse(request, "foo", null, null, null, true, false, XContentType.JSON, indexRequest -> { + assertTrue(indexRequest.isRequireAlias()); + }, req -> fail(), req -> fail()); request = new BytesArray("{ \"index\":{ \"_id\": \"bar\", \"require_alias\": true } }\n{}\n"); - parser.parse( - request, - "foo", - null, - null, - null, - null, - false, - XContentType.JSON, - indexRequest -> { assertTrue(indexRequest.isRequireAlias()); }, - req -> fail(), - req -> fail() - ); + parser.parse(request, "foo", null, null, null, null, false, XContentType.JSON, indexRequest -> { + assertTrue(indexRequest.isRequireAlias()); + }, req -> fail(), req -> fail()); request = new BytesArray("{ \"index\":{ \"_id\": \"bar\", \"require_alias\": false } }\n{}\n"); - parser.parse( - request, - "foo", - null, - null, - null, - true, - false, - XContentType.JSON, - indexRequest -> { assertFalse(indexRequest.isRequireAlias()); }, - req -> fail(), - req -> fail() - ); + parser.parse(request, "foo", null, null, null, true, false, XContentType.JSON, indexRequest -> { + assertFalse(indexRequest.isRequireAlias()); + }, req -> fail(), req -> fail()); } public void testDeleteRequest() throws IOException { @@ -129,49 +99,19 @@ public void testUpdateRequest() throws IOException { }, req -> fail()); assertTrue(parsed.get()); - parser.parse( - request, - "foo", - null, - null, - null, - true, - false, - XContentType.JSON, - req -> fail(), - updateRequest -> { assertTrue(updateRequest.isRequireAlias()); }, - req -> fail() - ); + parser.parse(request, "foo", null, null, null, true, false, XContentType.JSON, req -> fail(), updateRequest -> { + assertTrue(updateRequest.isRequireAlias()); + }, req -> fail()); request = new BytesArray("{ \"update\":{ \"_id\": \"bar\", \"require_alias\": true } }\n{}\n"); - parser.parse( - request, - "foo", - null, - null, - null, - null, - false, - XContentType.JSON, - req -> fail(), - updateRequest -> { assertTrue(updateRequest.isRequireAlias()); }, - req -> fail() - ); + parser.parse(request, "foo", null, null, null, null, false, XContentType.JSON, req -> fail(), updateRequest -> { + assertTrue(updateRequest.isRequireAlias()); + }, req -> fail()); request = new BytesArray("{ \"update\":{ \"_id\": \"bar\", \"require_alias\": false } }\n{}\n"); - parser.parse( - request, - "foo", - null, - null, - null, - true, - false, - XContentType.JSON, - req -> fail(), - updateRequest -> { assertFalse(updateRequest.isRequireAlias()); }, - req -> fail() - ); + parser.parse(request, "foo", null, null, null, true, false, XContentType.JSON, req -> fail(), updateRequest -> { + assertFalse(updateRequest.isRequireAlias()); + }, req -> fail()); } public void testBarfOnLackOfTrailingNewline() { diff --git a/server/src/test/java/org/opensearch/action/bulk/TransportBulkActionIndicesThatCannotBeCreatedTests.java b/server/src/test/java/org/opensearch/action/bulk/TransportBulkActionIndicesThatCannotBeCreatedTests.java index 32e9dd44008cd..0846a5f8dec5c 100644 --- a/server/src/test/java/org/opensearch/action/bulk/TransportBulkActionIndicesThatCannotBeCreatedTests.java +++ b/server/src/test/java/org/opensearch/action/bulk/TransportBulkActionIndicesThatCannotBeCreatedTests.java @@ -96,11 +96,9 @@ public void testAllFail() { bulkRequest.add(new IndexRequest("can't")); bulkRequest.add(new DeleteRequest("do").version(0).versionType(VersionType.EXTERNAL)); bulkRequest.add(new UpdateRequest("nothin", randomAlphaOfLength(5))); - indicesThatCannotBeCreatedTestCase( - new HashSet<>(Arrays.asList("no", "can't", "do", "nothin")), - bulkRequest, - index -> { throw new IndexNotFoundException("Can't make it because I say so"); } - ); + indicesThatCannotBeCreatedTestCase(new HashSet<>(Arrays.asList("no", "can't", "do", "nothin")), bulkRequest, index -> { + throw new IndexNotFoundException("Can't make it because I say so"); + }); } public void testSomeFail() { diff --git a/server/src/test/java/org/opensearch/action/bulk/TransportBulkActionIngestTests.java b/server/src/test/java/org/opensearch/action/bulk/TransportBulkActionIngestTests.java index 202f1b7dcb5b4..5b96c2a71dbf8 100644 --- a/server/src/test/java/org/opensearch/action/bulk/TransportBulkActionIngestTests.java +++ b/server/src/test/java/org/opensearch/action/bulk/TransportBulkActionIngestTests.java @@ -302,11 +302,9 @@ public void testIngestSkipped() throws Exception { public void testSingleItemBulkActionIngestSkipped() throws Exception { IndexRequest indexRequest = new IndexRequest("index").id("id"); indexRequest.source(emptyMap()); - singleItemBulkWriteAction.execute( - null, - indexRequest, - ActionListener.wrap(response -> {}, exception -> { throw new AssertionError(exception); }) - ); + singleItemBulkWriteAction.execute(null, indexRequest, ActionListener.wrap(response -> {}, exception -> { + throw new AssertionError(exception); + })); assertTrue(action.isExecuted); verifyNoInteractions(ingestService); } diff --git a/server/src/test/java/org/opensearch/action/search/SearchAsyncActionTests.java b/server/src/test/java/org/opensearch/action/search/SearchAsyncActionTests.java index d6a0ecd0512dc..277f2f1dee0bf 100644 --- a/server/src/test/java/org/opensearch/action/search/SearchAsyncActionTests.java +++ b/server/src/test/java/org/opensearch/action/search/SearchAsyncActionTests.java @@ -317,7 +317,9 @@ public void testFanOutAndCollect() throws InterruptedException { AtomicReference response = new AtomicReference<>(); ActionListener responseListener = ActionListener.wrap( searchResponse -> response.set((TestSearchResponse) searchResponse), - (e) -> { throw new AssertionError("unexpected", e); } + (e) -> { + throw new AssertionError("unexpected", e); + } ); DiscoveryNode primaryNode = new DiscoveryNode("node_1", buildNewFakeTransportAddress(), Version.CURRENT); DiscoveryNode replicaNode = new DiscoveryNode("node_2", buildNewFakeTransportAddress(), Version.CURRENT); diff --git a/server/src/test/java/org/opensearch/client/OriginSettingClientTests.java b/server/src/test/java/org/opensearch/client/OriginSettingClientTests.java index 2f24ff3fb1f29..eca49516f42c2 100644 --- a/server/src/test/java/org/opensearch/client/OriginSettingClientTests.java +++ b/server/src/test/java/org/opensearch/client/OriginSettingClientTests.java @@ -77,9 +77,8 @@ protected void } private ActionListener listenerThatAssertsOriginNotSet(ThreadContext threadContext) { - return ActionListener.wrap( - r -> { assertNull(threadContext.getTransient(ThreadContext.ACTION_ORIGIN_TRANSIENT_NAME)); }, - e -> { fail("didn't expect to fail but: " + e); } - ); + return ActionListener.wrap(r -> { assertNull(threadContext.getTransient(ThreadContext.ACTION_ORIGIN_TRANSIENT_NAME)); }, e -> { + fail("didn't expect to fail but: " + e); + }); } } diff --git a/server/src/test/java/org/opensearch/cluster/InternalClusterInfoServiceSchedulingTests.java b/server/src/test/java/org/opensearch/cluster/InternalClusterInfoServiceSchedulingTests.java index c1ea8c82d4ebf..1cd21482566ef 100644 --- a/server/src/test/java/org/opensearch/cluster/InternalClusterInfoServiceSchedulingTests.java +++ b/server/src/test/java/org/opensearch/cluster/InternalClusterInfoServiceSchedulingTests.java @@ -94,7 +94,9 @@ protected PrioritizedOpenSearchThreadPoolExecutor createThreadPoolExecutor() { "test", "clusterManagerService", threadPool, - r -> { fail("cluster-manager service should not run any tasks"); } + r -> { + fail("cluster-manager service should not run any tasks"); + } ); final ClusterService clusterService = new ClusterService(settings, clusterSettings, clusterManagerService, clusterApplierService); diff --git a/server/src/test/java/org/opensearch/cluster/coordination/ClusterBootstrapServiceDeprecatedMasterTests.java b/server/src/test/java/org/opensearch/cluster/coordination/ClusterBootstrapServiceDeprecatedMasterTests.java index fb3a628827462..137de1355f11b 100644 --- a/server/src/test/java/org/opensearch/cluster/coordination/ClusterBootstrapServiceDeprecatedMasterTests.java +++ b/server/src/test/java/org/opensearch/cluster/coordination/ClusterBootstrapServiceDeprecatedMasterTests.java @@ -125,9 +125,9 @@ public void testBootstrapsAutomaticallyWithDefaultConfiguration() { settings.put(UNCONFIGURED_BOOTSTRAP_TIMEOUT_SETTING.getKey(), timeout + "ms"); } - final AtomicReference>> discoveredNodesSupplier = new AtomicReference<>( - () -> { throw new AssertionError("should not be called yet"); } - ); + final AtomicReference>> discoveredNodesSupplier = new AtomicReference<>(() -> { + throw new AssertionError("should not be called yet"); + }); final AtomicBoolean bootstrapped = new AtomicBoolean(); ClusterBootstrapService clusterBootstrapService = new ClusterBootstrapService( @@ -163,13 +163,9 @@ public void testDoesNothingByDefaultIfMasterNodesConfigured() { } private void testDoesNothingWithSettings(Settings.Builder builder) { - ClusterBootstrapService clusterBootstrapService = new ClusterBootstrapService( - builder.build(), - transportService, - () -> { throw new AssertionError("should not be called"); }, - () -> false, - vc -> { throw new AssertionError("should not be called"); } - ); + ClusterBootstrapService clusterBootstrapService = new ClusterBootstrapService(builder.build(), transportService, () -> { + throw new AssertionError("should not be called"); + }, () -> false, vc -> { throw new AssertionError("should not be called"); }); transportService.start(); clusterBootstrapService.scheduleUnconfiguredBootstrap(); deterministicTaskQueue.runAllTasks(); @@ -182,7 +178,9 @@ public void testThrowsExceptionOnDuplicates() { transportService, Collections::emptyList, () -> false, - vc -> { throw new AssertionError("should not be called"); } + vc -> { + throw new AssertionError("should not be called"); + } ); }); @@ -236,7 +234,9 @@ public void testDoesNotBootstrapsOnNonMasterNode() { transportService, () -> Stream.of(localNode, otherNode1, otherNode2).collect(Collectors.toList()), () -> false, - vc -> { throw new AssertionError("should not be called"); } + vc -> { + throw new AssertionError("should not be called"); + } ); assertWarnings(CLUSTER_SETTING_DEPRECATED_MESSAGE); transportService.start(); @@ -250,7 +250,9 @@ public void testDoesNotBootstrapsIfLocalNodeNotInInitialMasterNodes() { transportService, () -> Stream.of(localNode, otherNode1, otherNode2).collect(Collectors.toList()), () -> false, - vc -> { throw new AssertionError("should not be called"); } + vc -> { + throw new AssertionError("should not be called"); + } ); assertWarnings(CLUSTER_SETTING_DEPRECATED_MESSAGE); transportService.start(); @@ -264,7 +266,9 @@ public void testDoesNotBootstrapsIfNotConfigured() { transportService, () -> Stream.of(localNode, otherNode1, otherNode2).collect(Collectors.toList()), () -> false, - vc -> { throw new AssertionError("should not be called"); } + vc -> { + throw new AssertionError("should not be called"); + } ); assertWarnings(CLUSTER_SETTING_DEPRECATED_MESSAGE); transportService.start(); diff --git a/server/src/test/java/org/opensearch/cluster/coordination/ClusterBootstrapServiceTests.java b/server/src/test/java/org/opensearch/cluster/coordination/ClusterBootstrapServiceTests.java index 9f9ccf34a6a9d..be7b32d4aef11 100644 --- a/server/src/test/java/org/opensearch/cluster/coordination/ClusterBootstrapServiceTests.java +++ b/server/src/test/java/org/opensearch/cluster/coordination/ClusterBootstrapServiceTests.java @@ -126,9 +126,9 @@ public void testBootstrapsAutomaticallyWithDefaultConfiguration() { settings.put(UNCONFIGURED_BOOTSTRAP_TIMEOUT_SETTING.getKey(), timeout + "ms"); } - final AtomicReference>> discoveredNodesSupplier = new AtomicReference<>( - () -> { throw new AssertionError("should not be called yet"); } - ); + final AtomicReference>> discoveredNodesSupplier = new AtomicReference<>(() -> { + throw new AssertionError("should not be called yet"); + }); final AtomicBoolean bootstrapped = new AtomicBoolean(); ClusterBootstrapService clusterBootstrapService = new ClusterBootstrapService( @@ -182,13 +182,9 @@ public void testDoesNothingByDefaultOnClusterManagerIneligibleNodes() { } private void testDoesNothingWithSettings(Settings.Builder builder) { - ClusterBootstrapService clusterBootstrapService = new ClusterBootstrapService( - builder.build(), - transportService, - () -> { throw new AssertionError("should not be called"); }, - () -> false, - vc -> { throw new AssertionError("should not be called"); } - ); + ClusterBootstrapService clusterBootstrapService = new ClusterBootstrapService(builder.build(), transportService, () -> { + throw new AssertionError("should not be called"); + }, () -> false, vc -> { throw new AssertionError("should not be called"); }); transportService.start(); clusterBootstrapService.scheduleUnconfiguredBootstrap(); deterministicTaskQueue.runAllTasks(); @@ -201,7 +197,9 @@ public void testThrowsExceptionOnDuplicates() { transportService, Collections::emptyList, () -> false, - vc -> { throw new AssertionError("should not be called"); } + vc -> { + throw new AssertionError("should not be called"); + } ); }); @@ -330,7 +328,9 @@ public void testDoesNotBootstrapIfNoNodesDiscovered() { transportService, Collections::emptyList, () -> true, - vc -> { throw new AssertionError("should not be called"); } + vc -> { + throw new AssertionError("should not be called"); + } ); transportService.start(); @@ -353,7 +353,9 @@ public void testDoesNotBootstrapIfTwoOfFiveNodesDiscovered() { transportService, () -> Stream.of(otherNode1).collect(Collectors.toList()), () -> false, - vc -> { throw new AssertionError("should not be called"); } + vc -> { + throw new AssertionError("should not be called"); + } ); transportService.start(); @@ -377,7 +379,9 @@ public void testDoesNotBootstrapIfThreeOfSixNodesDiscovered() { transportService, () -> Stream.of(otherNode1, otherNode2).collect(Collectors.toList()), () -> false, - vc -> { throw new AssertionError("should not be called"); } + vc -> { + throw new AssertionError("should not be called"); + } ); transportService.start(); @@ -393,7 +397,9 @@ public void testDoesNotBootstrapIfAlreadyBootstrapped() { transportService, () -> Stream.of(otherNode1, otherNode2).collect(Collectors.toList()), () -> true, - vc -> { throw new AssertionError("should not be called"); } + vc -> { + throw new AssertionError("should not be called"); + } ); transportService.start(); @@ -417,7 +423,9 @@ public void testDoesNotBootstrapsOnNonClusterManagerNode() { transportService, () -> Stream.of(localNode, otherNode1, otherNode2).collect(Collectors.toList()), () -> false, - vc -> { throw new AssertionError("should not be called"); } + vc -> { + throw new AssertionError("should not be called"); + } ); transportService.start(); clusterBootstrapService.onFoundPeersUpdated(); @@ -430,7 +438,9 @@ public void testDoesNotBootstrapsIfLocalNodeNotInInitialClusterManagerNodes() { transportService, () -> Stream.of(localNode, otherNode1, otherNode2).collect(Collectors.toList()), () -> false, - vc -> { throw new AssertionError("should not be called"); } + vc -> { + throw new AssertionError("should not be called"); + } ); transportService.start(); clusterBootstrapService.onFoundPeersUpdated(); @@ -443,7 +453,9 @@ public void testDoesNotBootstrapsIfNotConfigured() { transportService, () -> Stream.of(localNode, otherNode1, otherNode2).collect(Collectors.toList()), () -> false, - vc -> { throw new AssertionError("should not be called"); } + vc -> { + throw new AssertionError("should not be called"); + } ); transportService.start(); clusterBootstrapService.scheduleUnconfiguredBootstrap(); @@ -484,7 +496,9 @@ public void testCancelsBootstrapIfRequirementMatchesMultipleNodes() { transportService, discoveredNodes::get, () -> false, - vc -> { throw new AssertionError("should not be called"); } + vc -> { + throw new AssertionError("should not be called"); + } ); transportService.start(); @@ -507,7 +521,9 @@ public void testCancelsBootstrapIfNodeMatchesMultipleRequirements() { transportService, discoveredNodes::get, () -> false, - vc -> { throw new AssertionError("should not be called"); } + vc -> { + throw new AssertionError("should not be called"); + } ); transportService.start(); @@ -593,7 +609,9 @@ public void testDoesNotJustMatchEverything() { transportService, Collections::emptyList, () -> false, - vc -> { throw new AssertionError("should not be called"); } + vc -> { + throw new AssertionError("should not be called"); + } ); transportService.start(); diff --git a/server/src/test/java/org/opensearch/cluster/coordination/CoordinatorTests.java b/server/src/test/java/org/opensearch/cluster/coordination/CoordinatorTests.java index 16fd27fc7dff6..8d3763adfe440 100644 --- a/server/src/test/java/org/opensearch/cluster/coordination/CoordinatorTests.java +++ b/server/src/test/java/org/opensearch/cluster/coordination/CoordinatorTests.java @@ -1232,11 +1232,9 @@ public void testClusterCannotFormWithFailingJoinValidation() { nodes.stream().map(ClusterNode::getLocalNode).map(DiscoveryNode::getId).collect(Collectors.toSet()) ) == false, () -> randomSubsetOf(cluster.clusterNodes) - ).forEach( - cn -> cn.extraJoinValidators.add( - (discoveryNode, clusterState) -> { throw new IllegalArgumentException("join validation failed"); } - ) - ); + ).forEach(cn -> cn.extraJoinValidators.add((discoveryNode, clusterState) -> { + throw new IllegalArgumentException("join validation failed"); + })); cluster.bootstrapIfNecessary(); cluster.runFor(10000, "failing join validation"); assertTrue(cluster.clusterNodes.stream().allMatch(cn -> cn.getLastAppliedClusterState().version() == 0)); diff --git a/server/src/test/java/org/opensearch/cluster/coordination/FollowersCheckerTests.java b/server/src/test/java/org/opensearch/cluster/coordination/FollowersCheckerTests.java index 5bbbed5f4f8c0..0862597937e9d 100644 --- a/server/src/test/java/org/opensearch/cluster/coordination/FollowersCheckerTests.java +++ b/server/src/test/java/org/opensearch/cluster/coordination/FollowersCheckerTests.java @@ -132,7 +132,9 @@ protected void onSendRequest(long requestId, String action, TransportRequest req settings, transportService, fcr -> { assert false : fcr; }, - (node, reason) -> { assert false : node; }, + (node, reason) -> { + assert false : node; + }, () -> new StatusInfo(StatusInfo.Status.HEALTHY, "healthy-info") ); @@ -705,7 +707,9 @@ public void testPreferClusterManagerNodes() { Settings.EMPTY, transportService, fcr -> { assert false : fcr; }, - (node, reason) -> { assert false : node; }, + (node, reason) -> { + assert false : node; + }, () -> new StatusInfo(HEALTHY, "healthy-info") ); followersChecker.setCurrentNodes(discoveryNodes); diff --git a/server/src/test/java/org/opensearch/cluster/coordination/JoinHelperTests.java b/server/src/test/java/org/opensearch/cluster/coordination/JoinHelperTests.java index 7b21042b2ed4a..b56abe101bd4c 100644 --- a/server/src/test/java/org/opensearch/cluster/coordination/JoinHelperTests.java +++ b/server/src/test/java/org/opensearch/cluster/coordination/JoinHelperTests.java @@ -86,7 +86,9 @@ public void testJoinDeduplication() { transportService, () -> 0L, () -> null, - (joinRequest, joinCallback) -> { throw new AssertionError(); }, + (joinRequest, joinCallback) -> { + throw new AssertionError(); + }, startJoinRequest -> { throw new AssertionError(); }, Collections.emptyList(), (s, p, r) -> {}, @@ -220,20 +222,11 @@ private void assertJoinValidationRejectsMismatchedClusterUUID(String actionName, null, Collections.emptySet() ); - new JoinHelper( - Settings.EMPTY, - null, - null, - transportService, - () -> 0L, - () -> localClusterState, - (joinRequest, joinCallback) -> { throw new AssertionError(); }, - startJoinRequest -> { throw new AssertionError(); }, - Collections.emptyList(), - (s, p, r) -> {}, - null, - nodeCommissioned -> {} - ); // registers request handler + new JoinHelper(Settings.EMPTY, null, null, transportService, () -> 0L, () -> localClusterState, (joinRequest, joinCallback) -> { + throw new AssertionError(); + }, startJoinRequest -> { throw new AssertionError(); }, Collections.emptyList(), (s, p, r) -> {}, null, nodeCommissioned -> {}); // registers + // request + // handler transportService.start(); transportService.acceptIncomingRequests(); @@ -282,7 +275,9 @@ public void testJoinFailureOnUnhealthyNodes() { transportService, () -> 0L, () -> null, - (joinRequest, joinCallback) -> { throw new AssertionError(); }, + (joinRequest, joinCallback) -> { + throw new AssertionError(); + }, startJoinRequest -> { throw new AssertionError(); }, Collections.emptyList(), (s, p, r) -> {}, diff --git a/server/src/test/java/org/opensearch/cluster/coordination/NodeJoinTests.java b/server/src/test/java/org/opensearch/cluster/coordination/NodeJoinTests.java index 73c934c0e90b7..2752f57b499b3 100644 --- a/server/src/test/java/org/opensearch/cluster/coordination/NodeJoinTests.java +++ b/server/src/test/java/org/opensearch/cluster/coordination/NodeJoinTests.java @@ -529,14 +529,9 @@ public void testJoinUpdateVotingConfigExclusion() throws Exception { ) ); - assertTrue( - MasterServiceTests.discoveryState(clusterManagerService) - .getVotingConfigExclusions() - .stream() - .anyMatch( - exclusion -> { return "knownNodeName".equals(exclusion.getNodeName()) && "newNodeId".equals(exclusion.getNodeId()); } - ) - ); + assertTrue(MasterServiceTests.discoveryState(clusterManagerService).getVotingConfigExclusions().stream().anyMatch(exclusion -> { + return "knownNodeName".equals(exclusion.getNodeName()) && "newNodeId".equals(exclusion.getNodeId()); + })); } private ClusterState buildStateWithVotingConfigExclusion( diff --git a/server/src/test/java/org/opensearch/cluster/metadata/MetadataCreateIndexServiceTests.java b/server/src/test/java/org/opensearch/cluster/metadata/MetadataCreateIndexServiceTests.java index 66196331093bf..9b3eeff1ffe1a 100644 --- a/server/src/test/java/org/opensearch/cluster/metadata/MetadataCreateIndexServiceTests.java +++ b/server/src/test/java/org/opensearch/cluster/metadata/MetadataCreateIndexServiceTests.java @@ -724,9 +724,9 @@ public void testParseMappingsAppliesDataFromTemplateAndRequest() throws Exceptio } public void testAggregateSettingsAppliesSettingsFromTemplatesAndRequest() { - IndexTemplateMetadata templateMetadata = addMatchingTemplate( - builder -> { builder.settings(Settings.builder().put("template_setting", "value1")); } - ); + IndexTemplateMetadata templateMetadata = addMatchingTemplate(builder -> { + builder.settings(Settings.builder().put("template_setting", "value1")); + }); ImmutableOpenMap.Builder templatesBuilder = ImmutableOpenMap.builder(); templatesBuilder.put("template_1", templateMetadata); Metadata metadata = new Metadata.Builder().templates(templatesBuilder.build()).build(); diff --git a/server/src/test/java/org/opensearch/cluster/routing/allocation/FailedNodeRoutingTests.java b/server/src/test/java/org/opensearch/cluster/routing/allocation/FailedNodeRoutingTests.java index 121694e880b10..cddc5cc900b9c 100644 --- a/server/src/test/java/org/opensearch/cluster/routing/allocation/FailedNodeRoutingTests.java +++ b/server/src/test/java/org/opensearch/cluster/routing/allocation/FailedNodeRoutingTests.java @@ -188,8 +188,9 @@ public void testRandomClusterPromotesNewestReplica() throws InterruptedException // Pick a random subset of primaries to fail List shardsToFail = new ArrayList<>(); List failedPrimaries = randomSubsetOf(primaries); - failedPrimaries.stream() - .forEach(sr -> { shardsToFail.add(new FailedShard(randomFrom(sr), "failed primary", new Exception(), randomBoolean())); }); + failedPrimaries.stream().forEach(sr -> { + shardsToFail.add(new FailedShard(randomFrom(sr), "failed primary", new Exception(), randomBoolean())); + }); logger.info("--> state before failing shards: {}", state); state = cluster.applyFailedShards(state, shardsToFail); diff --git a/server/src/test/java/org/opensearch/cluster/routing/allocation/IndexShardConstraintDeciderOverlapTests.java b/server/src/test/java/org/opensearch/cluster/routing/allocation/IndexShardConstraintDeciderOverlapTests.java index 773c82be55ead..24c6dcff42849 100644 --- a/server/src/test/java/org/opensearch/cluster/routing/allocation/IndexShardConstraintDeciderOverlapTests.java +++ b/server/src/test/java/org/opensearch/cluster/routing/allocation/IndexShardConstraintDeciderOverlapTests.java @@ -68,10 +68,10 @@ public void testHighWatermarkBreachWithLowShardCount() { final ImmutableOpenMap reservedSpace = new ImmutableOpenMap.Builder< ClusterInfo.NodeAndPath, ClusterInfo.ReservedSpace>().fPut(getNodeAndDevNullPath("node_0"), getReservedSpace()) - .fPut(getNodeAndDevNullPath("node_1"), getReservedSpace()) - .fPut(getNodeAndDevNullPath("node_2"), getReservedSpace()) - .fPut(getNodeAndDevNullPath("high_watermark_node_0"), getReservedSpace()) - .build(); + .fPut(getNodeAndDevNullPath("node_1"), getReservedSpace()) + .fPut(getNodeAndDevNullPath("node_2"), getReservedSpace()) + .fPut(getNodeAndDevNullPath("high_watermark_node_0"), getReservedSpace()) + .build(); final ClusterInfo clusterInfo = new DevNullClusterInfo(usages, usages, shardSizes, reservedSpace); ClusterInfoService cis = () -> clusterInfo; allocation = createAllocationService(settings, cis); diff --git a/server/src/test/java/org/opensearch/cluster/service/ClusterManagerTaskThrottlerTests.java b/server/src/test/java/org/opensearch/cluster/service/ClusterManagerTaskThrottlerTests.java index 0acdbffe3dc4f..7492ea80638ed 100644 --- a/server/src/test/java/org/opensearch/cluster/service/ClusterManagerTaskThrottlerTests.java +++ b/server/src/test/java/org/opensearch/cluster/service/ClusterManagerTaskThrottlerTests.java @@ -69,12 +69,9 @@ public static void afterClass() { public void testDefaults() { ClusterSettings clusterSettings = new ClusterSettings(Settings.builder().build(), ClusterSettings.BUILT_IN_CLUSTER_SETTINGS); - ClusterManagerTaskThrottler throttler = new ClusterManagerTaskThrottler( - Settings.EMPTY, - clusterSettings, - () -> { return clusterService.getMasterService().getMinNodeVersion(); }, - new ClusterManagerThrottlingStats() - ); + ClusterManagerTaskThrottler throttler = new ClusterManagerTaskThrottler(Settings.EMPTY, clusterSettings, () -> { + return clusterService.getMasterService().getMinNodeVersion(); + }, new ClusterManagerThrottlingStats()); throttler.registerClusterManagerTask("put-mapping", true); throttler.registerClusterManagerTask("create-index", true); for (String key : throttler.THROTTLING_TASK_KEYS.keySet()) { @@ -91,12 +88,9 @@ public void testValidateSettingsForDifferentVersion() { ); ClusterSettings clusterSettings = new ClusterSettings(Settings.builder().build(), ClusterSettings.BUILT_IN_CLUSTER_SETTINGS); - ClusterManagerTaskThrottler throttler = new ClusterManagerTaskThrottler( - Settings.EMPTY, - clusterSettings, - () -> { return clusterService.getMasterService().getMinNodeVersion(); }, - new ClusterManagerThrottlingStats() - ); + ClusterManagerTaskThrottler throttler = new ClusterManagerTaskThrottler(Settings.EMPTY, clusterSettings, () -> { + return clusterService.getMasterService().getMinNodeVersion(); + }, new ClusterManagerThrottlingStats()); throttler.registerClusterManagerTask("put-mapping", true); // set some limit for update snapshot tasks @@ -124,12 +118,9 @@ public void testValidateSettingsForTaskWihtoutRetryOnDataNode() { ); ClusterSettings clusterSettings = new ClusterSettings(Settings.builder().build(), ClusterSettings.BUILT_IN_CLUSTER_SETTINGS); - ClusterManagerTaskThrottler throttler = new ClusterManagerTaskThrottler( - Settings.EMPTY, - clusterSettings, - () -> { return clusterService.getMasterService().getMinNodeVersion(); }, - new ClusterManagerThrottlingStats() - ); + ClusterManagerTaskThrottler throttler = new ClusterManagerTaskThrottler(Settings.EMPTY, clusterSettings, () -> { + return clusterService.getMasterService().getMinNodeVersion(); + }, new ClusterManagerThrottlingStats()); throttler.registerClusterManagerTask("put-mapping", false); // set some limit for update snapshot tasks @@ -148,12 +139,9 @@ public void testUpdateSettingsForNullValue() { ); ClusterSettings clusterSettings = new ClusterSettings(Settings.builder().build(), ClusterSettings.BUILT_IN_CLUSTER_SETTINGS); - ClusterManagerTaskThrottler throttler = new ClusterManagerTaskThrottler( - Settings.EMPTY, - clusterSettings, - () -> { return clusterService.getMasterService().getMinNodeVersion(); }, - new ClusterManagerThrottlingStats() - ); + ClusterManagerTaskThrottler throttler = new ClusterManagerTaskThrottler(Settings.EMPTY, clusterSettings, () -> { + return clusterService.getMasterService().getMinNodeVersion(); + }, new ClusterManagerThrottlingStats()); throttler.registerClusterManagerTask("put-mapping", true); // set some limit for put-mapping tasks @@ -181,12 +169,9 @@ public void testSettingsOnBootstrap() { Settings initialSettings = Settings.builder() .put("cluster_manager.throttling.thresholds.put-mapping.value", put_mapping_threshold_value) .build(); - ClusterManagerTaskThrottler throttler = new ClusterManagerTaskThrottler( - initialSettings, - clusterSettings, - () -> { return clusterService.getMasterService().getMinNodeVersion(); }, - new ClusterManagerThrottlingStats() - ); + ClusterManagerTaskThrottler throttler = new ClusterManagerTaskThrottler(initialSettings, clusterSettings, () -> { + return clusterService.getMasterService().getMinNodeVersion(); + }, new ClusterManagerThrottlingStats()); throttler.registerClusterManagerTask("put-mapping", true); // assert that limit is applied on throttler @@ -202,12 +187,9 @@ public void testValidateSettingsForUnknownTask() { ); ClusterSettings clusterSettings = new ClusterSettings(Settings.builder().build(), ClusterSettings.BUILT_IN_CLUSTER_SETTINGS); - ClusterManagerTaskThrottler throttler = new ClusterManagerTaskThrottler( - Settings.EMPTY, - clusterSettings, - () -> { return clusterService.getMasterService().getMinNodeVersion(); }, - new ClusterManagerThrottlingStats() - ); + ClusterManagerTaskThrottler throttler = new ClusterManagerTaskThrottler(Settings.EMPTY, clusterSettings, () -> { + return clusterService.getMasterService().getMinNodeVersion(); + }, new ClusterManagerThrottlingStats()); // set some limit for update snapshot tasks int newLimit = randomIntBetween(1, 10); @@ -224,12 +206,9 @@ public void testUpdateThrottlingLimitForBasicSanity() { ); ClusterSettings clusterSettings = new ClusterSettings(Settings.builder().build(), ClusterSettings.BUILT_IN_CLUSTER_SETTINGS); - ClusterManagerTaskThrottler throttler = new ClusterManagerTaskThrottler( - Settings.EMPTY, - clusterSettings, - () -> { return clusterService.getMasterService().getMinNodeVersion(); }, - new ClusterManagerThrottlingStats() - ); + ClusterManagerTaskThrottler throttler = new ClusterManagerTaskThrottler(Settings.EMPTY, clusterSettings, () -> { + return clusterService.getMasterService().getMinNodeVersion(); + }, new ClusterManagerThrottlingStats()); throttler.registerClusterManagerTask("put-mapping", true); // set some limit for update snapshot tasks @@ -254,12 +233,9 @@ public void testValidateSettingForLimit() { ); ClusterSettings clusterSettings = new ClusterSettings(Settings.builder().build(), ClusterSettings.BUILT_IN_CLUSTER_SETTINGS); - ClusterManagerTaskThrottler throttler = new ClusterManagerTaskThrottler( - Settings.EMPTY, - clusterSettings, - () -> { return clusterService.getMasterService().getMinNodeVersion(); }, - new ClusterManagerThrottlingStats() - ); + ClusterManagerTaskThrottler throttler = new ClusterManagerTaskThrottler(Settings.EMPTY, clusterSettings, () -> { + return clusterService.getMasterService().getMinNodeVersion(); + }, new ClusterManagerThrottlingStats()); throttler.registerClusterManagerTask("put-mapping", true); Settings newSettings = Settings.builder().put("cluster_manager.throttling.thresholds.put-mapping.values", -5).build(); @@ -268,12 +244,9 @@ public void testValidateSettingForLimit() { public void testUpdateLimit() { ClusterSettings clusterSettings = new ClusterSettings(Settings.builder().build(), ClusterSettings.BUILT_IN_CLUSTER_SETTINGS); - ClusterManagerTaskThrottler throttler = new ClusterManagerTaskThrottler( - Settings.EMPTY, - clusterSettings, - () -> { return clusterService.getMasterService().getMinNodeVersion(); }, - new ClusterManagerThrottlingStats() - ); + ClusterManagerTaskThrottler throttler = new ClusterManagerTaskThrottler(Settings.EMPTY, clusterSettings, () -> { + return clusterService.getMasterService().getMinNodeVersion(); + }, new ClusterManagerThrottlingStats()); throttler.registerClusterManagerTask("put-mapping", true); throttler.updateLimit("test", 5); @@ -306,12 +279,9 @@ public void testThrottlingForDisabledThrottlingTask() { ClusterManagerThrottlingStats throttlingStats = new ClusterManagerThrottlingStats(); String taskKey = "test"; ClusterSettings clusterSettings = new ClusterSettings(Settings.builder().build(), ClusterSettings.BUILT_IN_CLUSTER_SETTINGS); - ClusterManagerTaskThrottler throttler = new ClusterManagerTaskThrottler( - Settings.EMPTY, - clusterSettings, - () -> { return clusterService.getMasterService().getMinNodeVersion(); }, - throttlingStats - ); + ClusterManagerTaskThrottler throttler = new ClusterManagerTaskThrottler(Settings.EMPTY, clusterSettings, () -> { + return clusterService.getMasterService().getMinNodeVersion(); + }, throttlingStats); ClusterManagerTaskThrottler.ThrottlingKey throttlingKey = throttler.registerClusterManagerTask(taskKey, false); // adding limit directly in thresholds @@ -339,12 +309,9 @@ public void testThrottlingForInitialStaticSettingAndVersionCheck() { Settings initialSettings = Settings.builder() .put("cluster_manager.throttling.thresholds.put-mapping.value", put_mapping_threshold_value) .build(); - ClusterManagerTaskThrottler throttler = new ClusterManagerTaskThrottler( - initialSettings, - clusterSettings, - () -> { return clusterService.getMasterService().getMinNodeVersion(); }, - throttlingStats - ); + ClusterManagerTaskThrottler throttler = new ClusterManagerTaskThrottler(initialSettings, clusterSettings, () -> { + return clusterService.getMasterService().getMinNodeVersion(); + }, throttlingStats); ClusterManagerTaskThrottler.ThrottlingKey throttlingKey = throttler.registerClusterManagerTask("put-mapping", true); // verifying adding more tasks then threshold passes @@ -370,12 +337,9 @@ public void testThrottling() { ClusterManagerThrottlingStats throttlingStats = new ClusterManagerThrottlingStats(); String taskKey = "test"; ClusterSettings clusterSettings = new ClusterSettings(Settings.builder().build(), ClusterSettings.BUILT_IN_CLUSTER_SETTINGS); - ClusterManagerTaskThrottler throttler = new ClusterManagerTaskThrottler( - Settings.EMPTY, - clusterSettings, - () -> { return clusterService.getMasterService().getMinNodeVersion(); }, - throttlingStats - ); + ClusterManagerTaskThrottler throttler = new ClusterManagerTaskThrottler(Settings.EMPTY, clusterSettings, () -> { + return clusterService.getMasterService().getMinNodeVersion(); + }, throttlingStats); ClusterManagerTaskThrottler.ThrottlingKey throttlingKey = throttler.registerClusterManagerTask(taskKey, true); throttler.updateLimit(taskKey, 5); diff --git a/server/src/test/java/org/opensearch/common/geo/GeoJsonSerializationTests.java b/server/src/test/java/org/opensearch/common/geo/GeoJsonSerializationTests.java index 313a996c3fbf3..21f10aeb91542 100644 --- a/server/src/test/java/org/opensearch/common/geo/GeoJsonSerializationTests.java +++ b/server/src/test/java/org/opensearch/common/geo/GeoJsonSerializationTests.java @@ -102,7 +102,9 @@ private void xContentTest(Supplier instanceSupplier) throws IOExceptio AbstractXContentTestCase.xContentTester( this::createParser, () -> new GeometryWrapper(instanceSupplier.get()), - (geometryWrapper, xContentBuilder) -> { geometryWrapper.toXContent(xContentBuilder, ToXContent.EMPTY_PARAMS); }, + (geometryWrapper, xContentBuilder) -> { + geometryWrapper.toXContent(xContentBuilder, ToXContent.EMPTY_PARAMS); + }, GeometryWrapper::fromXContent ).supportsUnknownFields(true).test(); } diff --git a/server/src/test/java/org/opensearch/common/settings/SettingTests.java b/server/src/test/java/org/opensearch/common/settings/SettingTests.java index 446ed6278697c..005c0d7c38b51 100644 --- a/server/src/test/java/org/opensearch/common/settings/SettingTests.java +++ b/server/src/test/java/org/opensearch/common/settings/SettingTests.java @@ -367,13 +367,9 @@ public void testRegexValidator() throws Exception { } public void testValidatorForFilteredStringSetting() { - final Setting filteredStringSetting = new Setting<>( - "foo.bar", - "foobar", - Function.identity(), - value -> { throw new SettingsException("validate always fails"); }, - Property.Filtered - ); + final Setting filteredStringSetting = new Setting<>("foo.bar", "foobar", Function.identity(), value -> { + throw new SettingsException("validate always fails"); + }, Property.Filtered); final Settings settings = Settings.builder().put(filteredStringSetting.getKey(), filteredStringSetting.getKey() + " value").build(); final IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> filteredStringSetting.get(settings)); @@ -1628,16 +1624,14 @@ public void testGroupSettingUpdaterValidator() { validator ); - IllegalArgumentException illegal = expectThrows( - IllegalArgumentException.class, - () -> { updater.getValue(Settings.builder().put("prefix.foo.suffix", 5).put("abc", 2).build(), Settings.EMPTY); } - ); + IllegalArgumentException illegal = expectThrows(IllegalArgumentException.class, () -> { + updater.getValue(Settings.builder().put("prefix.foo.suffix", 5).put("abc", 2).build(), Settings.EMPTY); + }); assertEquals("foo and 2 can't go together", illegal.getMessage()); - illegal = expectThrows( - IllegalArgumentException.class, - () -> { updater.getValue(Settings.builder().put("prefix.bar.suffix", 6).put("abc", 3).build(), Settings.EMPTY); } - ); + illegal = expectThrows(IllegalArgumentException.class, () -> { + updater.getValue(Settings.builder().put("prefix.bar.suffix", 6).put("abc", 3).build(), Settings.EMPTY); + }); assertEquals("no bar", illegal.getMessage()); Settings s = updater.getValue( diff --git a/server/src/test/java/org/opensearch/common/settings/SettingsTests.java b/server/src/test/java/org/opensearch/common/settings/SettingsTests.java index c86172ac7ce54..be81793fd45ae 100644 --- a/server/src/test/java/org/opensearch/common/settings/SettingsTests.java +++ b/server/src/test/java/org/opensearch/common/settings/SettingsTests.java @@ -605,19 +605,17 @@ public void testYamlLegacyList() throws IOException { public void testIndentation() throws Exception { String yaml = "/org/opensearch/common/settings/loader/indentation-settings.yml"; - OpenSearchParseException e = expectThrows( - OpenSearchParseException.class, - () -> { Settings.builder().loadFromStream(yaml, getClass().getResourceAsStream(yaml), false); } - ); + OpenSearchParseException e = expectThrows(OpenSearchParseException.class, () -> { + Settings.builder().loadFromStream(yaml, getClass().getResourceAsStream(yaml), false); + }); assertTrue(e.getMessage(), e.getMessage().contains("malformed")); } public void testIndentationWithExplicitDocumentStart() throws Exception { String yaml = "/org/opensearch/common/settings/loader/indentation-with-explicit-document-start-settings.yml"; - OpenSearchParseException e = expectThrows( - OpenSearchParseException.class, - () -> { Settings.builder().loadFromStream(yaml, getClass().getResourceAsStream(yaml), false); } - ); + OpenSearchParseException e = expectThrows(OpenSearchParseException.class, () -> { + Settings.builder().loadFromStream(yaml, getClass().getResourceAsStream(yaml), false); + }); assertTrue(e.getMessage(), e.getMessage().contains("malformed")); } diff --git a/server/src/test/java/org/opensearch/discovery/DiscoveryModuleTests.java b/server/src/test/java/org/opensearch/discovery/DiscoveryModuleTests.java index 5588e9c1ceba8..1be312194d336 100644 --- a/server/src/test/java/org/opensearch/discovery/DiscoveryModuleTests.java +++ b/server/src/test/java/org/opensearch/discovery/DiscoveryModuleTests.java @@ -218,10 +218,9 @@ public void testMultipleSeedsProviders() { } public void testLazyConstructionSeedsProvider() { - DummyHostsProviderPlugin plugin = () -> Collections.singletonMap( - "custom", - () -> { throw new AssertionError("created hosts provider which was not selected"); } - ); + DummyHostsProviderPlugin plugin = () -> Collections.singletonMap("custom", () -> { + throw new AssertionError("created hosts provider which was not selected"); + }); newModule(Settings.EMPTY, Collections.singletonList(plugin)); } diff --git a/server/src/test/java/org/opensearch/gateway/GatewayMetaStateTests.java b/server/src/test/java/org/opensearch/gateway/GatewayMetaStateTests.java index d1c177ae5964c..8358dc84b2e0e 100644 --- a/server/src/test/java/org/opensearch/gateway/GatewayMetaStateTests.java +++ b/server/src/test/java/org/opensearch/gateway/GatewayMetaStateTests.java @@ -114,9 +114,9 @@ public void testCustomMetadataNoChange() { public void testIndexTemplateValidation() { Metadata metadata = randomMetadata(); - MetadataUpgrader metadataUpgrader = new MetadataUpgrader( - Collections.singletonList(customs -> { throw new IllegalStateException("template is incompatible"); }) - ); + MetadataUpgrader metadataUpgrader = new MetadataUpgrader(Collections.singletonList(customs -> { + throw new IllegalStateException("template is incompatible"); + })); String message = expectThrows( IllegalStateException.class, () -> GatewayMetaState.upgradeMetadata(metadata, new MockMetadataIndexUpgradeService(false), metadataUpgrader) diff --git a/server/src/test/java/org/opensearch/index/IndexSettingsTests.java b/server/src/test/java/org/opensearch/index/IndexSettingsTests.java index c6bccbe26a846..5c9f76da52b31 100644 --- a/server/src/test/java/org/opensearch/index/IndexSettingsTests.java +++ b/server/src/test/java/org/opensearch/index/IndexSettingsTests.java @@ -101,8 +101,9 @@ public void testSettingsUpdateValidator() { Setting integerSetting = Setting.intSetting("index.test.setting.int", -1, Property.Dynamic, Property.IndexScope); IndexMetadata metadata = newIndexMeta("index", theSettings); IndexSettings settings = newIndexSettings(newIndexMeta("index", theSettings), Settings.EMPTY, integerSetting); - settings.getScopedSettings() - .addSettingsUpdateConsumer(integerSetting, integer::set, (i) -> { if (i == 42) throw new AssertionError("boom"); }); + settings.getScopedSettings().addSettingsUpdateConsumer(integerSetting, integer::set, (i) -> { + if (i == 42) throw new AssertionError("boom"); + }); assertEquals(version, settings.getIndexVersionCreated()); assertEquals("0xdeadbeef", settings.getUUID()); @@ -655,15 +656,15 @@ public void testArchivedSettingsValidation() { } public void testArchiveBrokenIndexSettings() { - Settings settings = IndexScopedSettings.DEFAULT_SCOPED_SETTINGS.archiveUnknownOrInvalidSettings( - Settings.EMPTY, - e -> { assert false : "should not have been invoked, no unknown settings"; }, - (e, ex) -> { assert false : "should not have been invoked, no invalid settings"; } - ); + Settings settings = IndexScopedSettings.DEFAULT_SCOPED_SETTINGS.archiveUnknownOrInvalidSettings(Settings.EMPTY, e -> { + assert false : "should not have been invoked, no unknown settings"; + }, (e, ex) -> { assert false : "should not have been invoked, no invalid settings"; }); assertSame(settings, Settings.EMPTY); settings = IndexScopedSettings.DEFAULT_SCOPED_SETTINGS.archiveUnknownOrInvalidSettings( Settings.builder().put("index.refresh_interval", "-200").build(), - e -> { assert false : "should not have been invoked, no invalid settings"; }, + e -> { + assert false : "should not have been invoked, no invalid settings"; + }, (e, ex) -> { assertThat(e.getKey(), equalTo("index.refresh_interval")); assertThat(e.getValue(), equalTo("-200")); @@ -674,11 +675,9 @@ public void testArchiveBrokenIndexSettings() { assertNull(settings.get("index.refresh_interval")); Settings prevSettings = settings; // no double archive - settings = IndexScopedSettings.DEFAULT_SCOPED_SETTINGS.archiveUnknownOrInvalidSettings( - prevSettings, - e -> { assert false : "should not have been invoked, no unknown settings"; }, - (e, ex) -> { assert false : "should not have been invoked, no invalid settings"; } - ); + settings = IndexScopedSettings.DEFAULT_SCOPED_SETTINGS.archiveUnknownOrInvalidSettings(prevSettings, e -> { + assert false : "should not have been invoked, no unknown settings"; + }, (e, ex) -> { assert false : "should not have been invoked, no invalid settings"; }); assertSame(prevSettings, settings); settings = IndexScopedSettings.DEFAULT_SCOPED_SETTINGS.archiveUnknownOrInvalidSettings( diff --git a/server/src/test/java/org/opensearch/index/analysis/AnalysisRegistryTests.java b/server/src/test/java/org/opensearch/index/analysis/AnalysisRegistryTests.java index cbc189be491cd..739e26ed3d677 100644 --- a/server/src/test/java/org/opensearch/index/analysis/AnalysisRegistryTests.java +++ b/server/src/test/java/org/opensearch/index/analysis/AnalysisRegistryTests.java @@ -475,13 +475,10 @@ public Map> getTokenFilters() { .build(); IndexSettings exceptionSettings = IndexSettingsModule.newIndexSettings("index", indexSettings); - IllegalArgumentException e = expectThrows( - IllegalArgumentException.class, - () -> { - new AnalysisModule(TestEnvironment.newEnvironment(settings), singletonList(plugin)).getAnalysisRegistry() - .build(exceptionSettings); - } - ); + IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> { + new AnalysisModule(TestEnvironment.newEnvironment(settings), singletonList(plugin)).getAnalysisRegistry() + .build(exceptionSettings); + }); assertEquals("Cannot use token filter [exception]", e.getMessage()); } diff --git a/server/src/test/java/org/opensearch/index/analysis/AnalysisTests.java b/server/src/test/java/org/opensearch/index/analysis/AnalysisTests.java index 0446ac78d4efc..d4b825ce09e92 100644 --- a/server/src/test/java/org/opensearch/index/analysis/AnalysisTests.java +++ b/server/src/test/java/org/opensearch/index/analysis/AnalysisTests.java @@ -124,15 +124,9 @@ public void testParseWordListError() throws IOException { writer.write('\n'); } Environment env = TestEnvironment.newEnvironment(nodeSettings); - RuntimeException ex = expectThrows( - RuntimeException.class, - () -> Analysis.parseWordList( - env, - nodeSettings, - "foo.bar", - s -> { throw new RuntimeException("Error while parsing rule = " + s); } - ) - ); + RuntimeException ex = expectThrows(RuntimeException.class, () -> Analysis.parseWordList(env, nodeSettings, "foo.bar", s -> { + throw new RuntimeException("Error while parsing rule = " + s); + })); assertEquals("Line [1]: Error while parsing rule = abcd", ex.getMessage()); } @@ -146,15 +140,9 @@ public void testParseWordListOutsideConfigDirError() throws IOException { } Settings nodeSettings = Settings.builder().put("foo.bar_path", dict).put(Environment.PATH_HOME_SETTING.getKey(), home).build(); Environment env = TestEnvironment.newEnvironment(nodeSettings); - RuntimeException ex = expectThrows( - RuntimeException.class, - () -> Analysis.parseWordList( - env, - nodeSettings, - "foo.bar", - s -> { throw new RuntimeException("Error while parsing rule = " + s); } - ) - ); + RuntimeException ex = expectThrows(RuntimeException.class, () -> Analysis.parseWordList(env, nodeSettings, "foo.bar", s -> { + throw new RuntimeException("Error while parsing rule = " + s); + })); assertEquals("Line [1]: Invalid rule", ex.getMessage()); } } diff --git a/server/src/test/java/org/opensearch/index/engine/CompletionStatsCacheTests.java b/server/src/test/java/org/opensearch/index/engine/CompletionStatsCacheTests.java index d960fa910fde6..74ce2d5bba186 100644 --- a/server/src/test/java/org/opensearch/index/engine/CompletionStatsCacheTests.java +++ b/server/src/test/java/org/opensearch/index/engine/CompletionStatsCacheTests.java @@ -59,9 +59,9 @@ public class CompletionStatsCacheTests extends OpenSearchTestCase { public void testExceptionsAreNotCached() { final AtomicInteger openCount = new AtomicInteger(); - final CompletionStatsCache completionStatsCache = new CompletionStatsCache( - () -> { throw new OpenSearchException("simulated " + openCount.incrementAndGet()); } - ); + final CompletionStatsCache completionStatsCache = new CompletionStatsCache(() -> { + throw new OpenSearchException("simulated " + openCount.incrementAndGet()); + }); assertThat(expectThrows(OpenSearchException.class, completionStatsCache::get).getMessage(), equalTo("simulated 1")); assertThat(expectThrows(OpenSearchException.class, completionStatsCache::get).getMessage(), equalTo("simulated 2")); diff --git a/server/src/test/java/org/opensearch/index/fielddata/IndexFieldDataServiceTests.java b/server/src/test/java/org/opensearch/index/fielddata/IndexFieldDataServiceTests.java index d6fd079ac59e8..94d74c21bc977 100644 --- a/server/src/test/java/org/opensearch/index/fielddata/IndexFieldDataServiceTests.java +++ b/server/src/test/java/org/opensearch/index/fielddata/IndexFieldDataServiceTests.java @@ -327,10 +327,9 @@ private void doTestRequireDocValues(MappedFieldType ft) { if (ft.hasDocValues()) { ifds.getForField(ft, "test", () -> { throw new UnsupportedOperationException(); }); // no exception } else { - IllegalArgumentException e = expectThrows( - IllegalArgumentException.class, - () -> ifds.getForField(ft, "test", () -> { throw new UnsupportedOperationException(); }) - ); + IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> ifds.getForField(ft, "test", () -> { + throw new UnsupportedOperationException(); + })); assertThat(e.getMessage(), containsString("doc values")); } } finally { diff --git a/server/src/test/java/org/opensearch/index/mapper/IdFieldMapperTests.java b/server/src/test/java/org/opensearch/index/mapper/IdFieldMapperTests.java index e897abad405d5..93d0596a9bfb5 100644 --- a/server/src/test/java/org/opensearch/index/mapper/IdFieldMapperTests.java +++ b/server/src/test/java/org/opensearch/index/mapper/IdFieldMapperTests.java @@ -114,10 +114,9 @@ public void testEnableFieldData() throws IOException { .setTransientSettings(Settings.builder().put(IndicesService.INDICES_ID_FIELD_DATA_ENABLED_SETTING.getKey(), false)) .get(); try { - IllegalArgumentException exc = expectThrows( - IllegalArgumentException.class, - () -> ft.fielddataBuilder("test", () -> { throw new UnsupportedOperationException(); }).build(null, null) - ); + IllegalArgumentException exc = expectThrows(IllegalArgumentException.class, () -> ft.fielddataBuilder("test", () -> { + throw new UnsupportedOperationException(); + }).build(null, null)); assertThat(exc.getMessage(), containsString(IndicesService.INDICES_ID_FIELD_DATA_ENABLED_SETTING.getKey())); assertFalse(ft.isAggregatable()); } finally { diff --git a/server/src/test/java/org/opensearch/index/mapper/MapperServiceTests.java b/server/src/test/java/org/opensearch/index/mapper/MapperServiceTests.java index fe16db95112d7..01a901b3cd5cb 100644 --- a/server/src/test/java/org/opensearch/index/mapper/MapperServiceTests.java +++ b/server/src/test/java/org/opensearch/index/mapper/MapperServiceTests.java @@ -340,10 +340,9 @@ public void testFieldNameLengthLimit() throws Throwable { ) ); - IllegalArgumentException e = expectThrows( - IllegalArgumentException.class, - () -> { mapperService.merge("type", mappingUpdate, updateOrPreflight()); } - ); + IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> { + mapperService.merge("type", mappingUpdate, updateOrPreflight()); + }); assertEquals("Field name [" + testString + "] is longer than the limit of [" + maxFieldNameLength + "] characters", e.getMessage()); } @@ -371,10 +370,9 @@ public void testObjectNameLengthLimit() throws Throwable { ) ); - IllegalArgumentException e = expectThrows( - IllegalArgumentException.class, - () -> { mapperService.merge("type", mapping, updateOrPreflight()); } - ); + IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> { + mapperService.merge("type", mapping, updateOrPreflight()); + }); assertEquals("Field name [" + testString + "] is longer than the limit of [" + maxFieldNameLength + "] characters", e.getMessage()); } @@ -406,10 +404,9 @@ public void testAliasFieldNameLengthLimit() throws Throwable { ) ); - IllegalArgumentException e = expectThrows( - IllegalArgumentException.class, - () -> { mapperService.merge("type", mapping, updateOrPreflight()); } - ); + IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> { + mapperService.merge("type", mapping, updateOrPreflight()); + }); assertEquals("Field name [" + testString + "] is longer than the limit of [" + maxFieldNameLength + "] characters", e.getMessage()); } diff --git a/server/src/test/java/org/opensearch/index/mapper/NumberFieldTypeTests.java b/server/src/test/java/org/opensearch/index/mapper/NumberFieldTypeTests.java index 0eeefb113a28d..863e29abaedf7 100644 --- a/server/src/test/java/org/opensearch/index/mapper/NumberFieldTypeTests.java +++ b/server/src/test/java/org/opensearch/index/mapper/NumberFieldTypeTests.java @@ -553,10 +553,9 @@ public void doTestIndexSortRangeQueries(NumberType type, Supplier valueS // Create an index writer configured with the same index sort. NumberFieldType fieldType = new NumberFieldType("field", type); - IndexNumericFieldData fielddata = (IndexNumericFieldData) fieldType.fielddataBuilder( - "index", - () -> { throw new UnsupportedOperationException(); } - ).build(null, null); + IndexNumericFieldData fielddata = (IndexNumericFieldData) fieldType.fielddataBuilder("index", () -> { + throw new UnsupportedOperationException(); + }).build(null, null); SortField sortField = fielddata.sortField(null, MultiValueMode.MIN, null, randomBoolean()); IndexWriterConfig writerConfig = new IndexWriterConfig(); diff --git a/server/src/test/java/org/opensearch/index/mapper/ObjectMapperTests.java b/server/src/test/java/org/opensearch/index/mapper/ObjectMapperTests.java index d6c89342c9df2..07b0ad822209c 100644 --- a/server/src/test/java/org/opensearch/index/mapper/ObjectMapperTests.java +++ b/server/src/test/java/org/opensearch/index/mapper/ObjectMapperTests.java @@ -443,10 +443,9 @@ public void testEmptyName() throws Exception { ); // Empty name not allowed in index created after 5.0 - IllegalArgumentException e = expectThrows( - IllegalArgumentException.class, - () -> { createIndex("test").mapperService().documentMapperParser().parse("", new CompressedXContent(mapping)); } - ); + IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> { + createIndex("test").mapperService().documentMapperParser().parse("", new CompressedXContent(mapping)); + }); assertThat(e.getMessage(), containsString("name cannot be empty string")); } diff --git a/server/src/test/java/org/opensearch/index/mapper/TextFieldMapperTests.java b/server/src/test/java/org/opensearch/index/mapper/TextFieldMapperTests.java index 109fa69eb6c3e..776f2f42780a5 100644 --- a/server/src/test/java/org/opensearch/index/mapper/TextFieldMapperTests.java +++ b/server/src/test/java/org/opensearch/index/mapper/TextFieldMapperTests.java @@ -501,10 +501,9 @@ public void testEagerGlobalOrdinals() throws IOException { public void testFielddata() throws IOException { MapperService disabledMapper = createMapperService(fieldMapping(this::minimalMapping)); - Exception e = expectThrows( - IllegalArgumentException.class, - () -> disabledMapper.fieldType("field").fielddataBuilder("test", () -> { throw new UnsupportedOperationException(); }) - ); + Exception e = expectThrows(IllegalArgumentException.class, () -> disabledMapper.fieldType("field").fielddataBuilder("test", () -> { + throw new UnsupportedOperationException(); + })); assertThat(e.getMessage(), containsString("Text fields are not optimised for operations that require per-document field data")); MapperService enabledMapper = createMapperService(fieldMapping(b -> b.field("type", "text").field("fielddata", true))); diff --git a/server/src/test/java/org/opensearch/index/query/InnerHitBuilderTests.java b/server/src/test/java/org/opensearch/index/query/InnerHitBuilderTests.java index 749f654bd1bc7..bdfc03838dcea 100644 --- a/server/src/test/java/org/opensearch/index/query/InnerHitBuilderTests.java +++ b/server/src/test/java/org/opensearch/index/query/InnerHitBuilderTests.java @@ -237,12 +237,9 @@ static InnerHitBuilder mutate(InnerHitBuilder original) throws IOException { }); modifiers.add(() -> { if (randomBoolean()) { - copy.setScriptFields( - randomValueOtherThan( - copy.getScriptFields(), - () -> { return new HashSet<>(randomListStuff(16, InnerHitBuilderTests::randomScript)); } - ) - ); + copy.setScriptFields(randomValueOtherThan(copy.getScriptFields(), () -> { + return new HashSet<>(randomListStuff(16, InnerHitBuilderTests::randomScript)); + })); } else { SearchSourceBuilder.ScriptField script = randomScript(); copy.addScriptField(script.fieldName(), script.script()); diff --git a/server/src/test/java/org/opensearch/index/search/MultiMatchQueryTests.java b/server/src/test/java/org/opensearch/index/search/MultiMatchQueryTests.java index f0a70b55e0fdd..48d04e2aaa3a6 100644 --- a/server/src/test/java/org/opensearch/index/search/MultiMatchQueryTests.java +++ b/server/src/test/java/org/opensearch/index/search/MultiMatchQueryTests.java @@ -111,12 +111,9 @@ public void setup() throws IOException { } public void testCrossFieldMultiMatchQuery() throws IOException { - QueryShardContext queryShardContext = indexService.newQueryShardContext( - randomInt(20), - null, - () -> { throw new UnsupportedOperationException(); }, - null - ); + QueryShardContext queryShardContext = indexService.newQueryShardContext(randomInt(20), null, () -> { + throw new UnsupportedOperationException(); + }, null); queryShardContext.setAllowUnmappedFields(true); for (float tieBreaker : new float[] { 0.0f, 0.5f }) { Query parsedQuery = multiMatchQuery("banon").field("name.first", 2) @@ -141,14 +138,9 @@ public void testBlendTerms() { Term[] terms = new Term[] { new Term("foo", "baz"), new Term("bar", "baz") }; float[] boosts = new float[] { 2, 3 }; Query expected = BlendedTermQuery.dismaxBlendedQuery(terms, boosts, 1.0f); - Query actual = MultiMatchQuery.blendTerm( - indexService.newQueryShardContext(randomInt(20), null, () -> { throw new UnsupportedOperationException(); }, null), - new BytesRef("baz"), - null, - 1f, - false, - Arrays.asList(new FieldAndBoost(ft1, 2), new FieldAndBoost(ft2, 3)) - ); + Query actual = MultiMatchQuery.blendTerm(indexService.newQueryShardContext(randomInt(20), null, () -> { + throw new UnsupportedOperationException(); + }, null), new BytesRef("baz"), null, 1f, false, Arrays.asList(new FieldAndBoost(ft1, 2), new FieldAndBoost(ft2, 3))); assertEquals(expected, actual); } @@ -160,14 +152,9 @@ public void testBlendTermsWithFieldBoosts() { Term[] terms = new Term[] { new Term("foo", "baz"), new Term("bar", "baz") }; float[] boosts = new float[] { 200, 30 }; Query expected = BlendedTermQuery.dismaxBlendedQuery(terms, boosts, 1.0f); - Query actual = MultiMatchQuery.blendTerm( - indexService.newQueryShardContext(randomInt(20), null, () -> { throw new UnsupportedOperationException(); }, null), - new BytesRef("baz"), - null, - 1f, - false, - Arrays.asList(new FieldAndBoost(ft1, 2), new FieldAndBoost(ft2, 3)) - ); + Query actual = MultiMatchQuery.blendTerm(indexService.newQueryShardContext(randomInt(20), null, () -> { + throw new UnsupportedOperationException(); + }, null), new BytesRef("baz"), null, 1f, false, Arrays.asList(new FieldAndBoost(ft1, 2), new FieldAndBoost(ft2, 3))); assertEquals(expected, actual); } @@ -188,14 +175,9 @@ public Query termQuery(Object value, QueryShardContext context) { ), 1f ); - Query actual = MultiMatchQuery.blendTerm( - indexService.newQueryShardContext(randomInt(20), null, () -> { throw new UnsupportedOperationException(); }, null), - new BytesRef("baz"), - null, - 1f, - true, - Arrays.asList(new FieldAndBoost(ft1, 2), new FieldAndBoost(ft2, 3)) - ); + Query actual = MultiMatchQuery.blendTerm(indexService.newQueryShardContext(randomInt(20), null, () -> { + throw new UnsupportedOperationException(); + }, null), new BytesRef("baz"), null, 1f, true, Arrays.asList(new FieldAndBoost(ft1, 2), new FieldAndBoost(ft2, 3))); assertEquals(expected, actual); } @@ -208,14 +190,9 @@ public Query termQuery(Object value, QueryShardContext context) { }; expectThrows( IllegalArgumentException.class, - () -> MultiMatchQuery.blendTerm( - indexService.newQueryShardContext(randomInt(20), null, () -> { throw new UnsupportedOperationException(); }, null), - new BytesRef("baz"), - null, - 1f, - false, - Arrays.asList(new FieldAndBoost(ft, 1)) - ) + () -> MultiMatchQuery.blendTerm(indexService.newQueryShardContext(randomInt(20), null, () -> { + throw new UnsupportedOperationException(); + }, null), new BytesRef("baz"), null, 1f, false, Arrays.asList(new FieldAndBoost(ft, 1))) ); } @@ -232,24 +209,16 @@ public Query termQuery(Object value, QueryShardContext context) { Query expectedDisjunct1 = BlendedTermQuery.dismaxBlendedQuery(terms, boosts, 1.0f); Query expectedDisjunct2 = new BoostQuery(new MatchAllDocsQuery(), 3); Query expected = new DisjunctionMaxQuery(Arrays.asList(expectedDisjunct2, expectedDisjunct1), 1.0f); - Query actual = MultiMatchQuery.blendTerm( - indexService.newQueryShardContext(randomInt(20), null, () -> { throw new UnsupportedOperationException(); }, null), - new BytesRef("baz"), - null, - 1f, - false, - Arrays.asList(new FieldAndBoost(ft1, 2), new FieldAndBoost(ft2, 3)) - ); + Query actual = MultiMatchQuery.blendTerm(indexService.newQueryShardContext(randomInt(20), null, () -> { + throw new UnsupportedOperationException(); + }, null), new BytesRef("baz"), null, 1f, false, Arrays.asList(new FieldAndBoost(ft1, 2), new FieldAndBoost(ft2, 3))); assertEquals(expected, actual); } public void testMultiMatchCrossFieldsWithSynonyms() throws IOException { - QueryShardContext queryShardContext = indexService.newQueryShardContext( - randomInt(20), - null, - () -> { throw new UnsupportedOperationException(); }, - null - ); + QueryShardContext queryShardContext = indexService.newQueryShardContext(randomInt(20), null, () -> { + throw new UnsupportedOperationException(); + }, null); MultiMatchQuery parser = new MultiMatchQuery(queryShardContext); parser.setAnalyzer(new MockSynonymAnalyzer()); @@ -279,12 +248,9 @@ public void testMultiMatchCrossFieldsWithSynonyms() throws IOException { } public void testMultiMatchCrossFieldsWithSynonymsPhrase() throws IOException { - QueryShardContext queryShardContext = indexService.newQueryShardContext( - randomInt(20), - null, - () -> { throw new UnsupportedOperationException(); }, - null - ); + QueryShardContext queryShardContext = indexService.newQueryShardContext(randomInt(20), null, () -> { + throw new UnsupportedOperationException(); + }, null); MultiMatchQuery parser = new MultiMatchQuery(queryShardContext); parser.setAnalyzer(new MockSynonymAnalyzer()); Map fieldNames = new HashMap<>(); @@ -345,12 +311,9 @@ public void testKeywordSplitQueriesOnWhitespace() throws IOException { .endObject() ); mapperService.merge("type", new CompressedXContent(mapping), MapperService.MergeReason.MAPPING_UPDATE); - QueryShardContext queryShardContext = indexService.newQueryShardContext( - randomInt(20), - null, - () -> { throw new UnsupportedOperationException(); }, - null - ); + QueryShardContext queryShardContext = indexService.newQueryShardContext(randomInt(20), null, () -> { + throw new UnsupportedOperationException(); + }, null); MultiMatchQuery parser = new MultiMatchQuery(queryShardContext); Map fieldNames = new HashMap<>(); fieldNames.put("field", 1.0f); diff --git a/server/src/test/java/org/opensearch/index/shard/GlobalCheckpointListenersTests.java b/server/src/test/java/org/opensearch/index/shard/GlobalCheckpointListenersTests.java index 28e29ec0d0249..1b7bdaf710de4 100644 --- a/server/src/test/java/org/opensearch/index/shard/GlobalCheckpointListenersTests.java +++ b/server/src/test/java/org/opensearch/index/shard/GlobalCheckpointListenersTests.java @@ -625,11 +625,9 @@ public void testFailingListenerAfterTimeout() throws InterruptedException { }).when(mockLogger).warn(any(String.class), any(RuntimeException.class)); final GlobalCheckpointListeners globalCheckpointListeners = new GlobalCheckpointListeners(shardId, scheduler, mockLogger); final TimeValue timeout = TimeValue.timeValueMillis(randomIntBetween(1, 50)); - globalCheckpointListeners.add( - NO_OPS_PERFORMED, - maybeMultipleInvocationProtectingListener((g, e) -> { throw new RuntimeException("failure"); }), - timeout - ); + globalCheckpointListeners.add(NO_OPS_PERFORMED, maybeMultipleInvocationProtectingListener((g, e) -> { + throw new RuntimeException("failure"); + }), timeout); latch.await(); final ArgumentCaptor message = ArgumentCaptor.forClass(String.class); final ArgumentCaptor t = ArgumentCaptor.forClass(RuntimeException.class); diff --git a/server/src/test/java/org/opensearch/index/shard/IndexShardOperationPermitsTests.java b/server/src/test/java/org/opensearch/index/shard/IndexShardOperationPermitsTests.java index 9d73fa3524a8c..6e130c1938b4f 100644 --- a/server/src/test/java/org/opensearch/index/shard/IndexShardOperationPermitsTests.java +++ b/server/src/test/java/org/opensearch/index/shard/IndexShardOperationPermitsTests.java @@ -226,18 +226,12 @@ public void testOperationsIfClosed() { public void testBlockIfClosed() { permits.close(); - expectThrows( - IndexShardClosedException.class, - () -> permits.blockOperations(randomInt(10), TimeUnit.MINUTES, () -> { throw new IllegalArgumentException("fake error"); }) - ); - expectThrows( - IndexShardClosedException.class, - () -> permits.asyncBlockOperations( - wrap(() -> { throw new IllegalArgumentException("fake error"); }), - randomInt(10), - TimeUnit.MINUTES - ) - ); + expectThrows(IndexShardClosedException.class, () -> permits.blockOperations(randomInt(10), TimeUnit.MINUTES, () -> { + throw new IllegalArgumentException("fake error"); + })); + expectThrows(IndexShardClosedException.class, () -> permits.asyncBlockOperations(wrap(() -> { + throw new IllegalArgumentException("fake error"); + }), randomInt(10), TimeUnit.MINUTES)); } public void testOperationsDelayedIfBlock() throws ExecutionException, InterruptedException, TimeoutException { diff --git a/server/src/test/java/org/opensearch/index/shard/IndexShardTests.java b/server/src/test/java/org/opensearch/index/shard/IndexShardTests.java index c84d03a8454d9..9fc360e182439 100644 --- a/server/src/test/java/org/opensearch/index/shard/IndexShardTests.java +++ b/server/src/test/java/org/opensearch/index/shard/IndexShardTests.java @@ -2174,11 +2174,9 @@ public void testRelocatedSegRepError() throws IOException, InterruptedException IndexShardTestCase.updateRoutingEntry(shard, routing); ReplicationFailedException segRepException = expectThrows( ReplicationFailedException.class, - () -> shard.relocated( - routing.getTargetRelocatingShard().allocationId().getId(), - primaryContext -> {}, - () -> { throw new ReplicationFailedException("Segment replication failed"); } - ) + () -> shard.relocated(routing.getTargetRelocatingShard().allocationId().getId(), primaryContext -> {}, () -> { + throw new ReplicationFailedException("Segment replication failed"); + }) ); assertTrue(segRepException.getMessage().equals("Segment replication failed")); closeShards(shard); @@ -2961,11 +2959,9 @@ public void testReaderWrapperWorksWithGlobalOrdinals() throws IOException { new NoneCircuitBreakerService(), shard.mapperService() ); - IndexFieldData.Global ifd = indexFieldDataService.getForField( - foo, - "test", - () -> { throw new UnsupportedOperationException("search lookup not available"); } - ); + IndexFieldData.Global ifd = indexFieldDataService.getForField(foo, "test", () -> { + throw new UnsupportedOperationException("search lookup not available"); + }); FieldDataStats before = shard.fieldData().stats("foo"); assertThat(before.getMemorySizeInBytes(), equalTo(0L)); FieldDataStats after = null; diff --git a/server/src/test/java/org/opensearch/index/shard/SearchOperationListenerTests.java b/server/src/test/java/org/opensearch/index/shard/SearchOperationListenerTests.java index 8d89cc2383aeb..98f86758ea2ca 100644 --- a/server/src/test/java/org/opensearch/index/shard/SearchOperationListenerTests.java +++ b/server/src/test/java/org/opensearch/index/shard/SearchOperationListenerTests.java @@ -138,7 +138,9 @@ public void validateReaderContext(ReaderContext readerContext, TransportRequest SearchOperationListener throwingListener = (SearchOperationListener) Proxy.newProxyInstance( SearchOperationListener.class.getClassLoader(), new Class[] { SearchOperationListener.class }, - (a, b, c) -> { throw new RuntimeException(); } + (a, b, c) -> { + throw new RuntimeException(); + } ); int throwingListeners = 0; final List indexingOperationListeners = new ArrayList<>(Arrays.asList(listener, listener)); diff --git a/server/src/test/java/org/opensearch/index/similarity/ScriptedSimilarityTests.java b/server/src/test/java/org/opensearch/index/similarity/ScriptedSimilarityTests.java index ef935ba64f1ca..f4282b8221c05 100644 --- a/server/src/test/java/org/opensearch/index/similarity/ScriptedSimilarityTests.java +++ b/server/src/test/java/org/opensearch/index/similarity/ScriptedSimilarityTests.java @@ -111,10 +111,9 @@ public double execute( ) { StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); - if (Arrays.stream(stackTraceElements) - .anyMatch( - ste -> { return ste.getClassName().endsWith(".TermScorer") && ste.getMethodName().equals("score"); } - ) == false) { + if (Arrays.stream(stackTraceElements).anyMatch(ste -> { + return ste.getClassName().endsWith(".TermScorer") && ste.getMethodName().equals("score"); + }) == false) { // this might happen when computing max scores return Float.MAX_VALUE; } @@ -210,10 +209,9 @@ public double execute( ) { StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); - if (Arrays.stream(stackTraceElements) - .anyMatch( - ste -> { return ste.getClassName().endsWith(".TermScorer") && ste.getMethodName().equals("score"); } - ) == false) { + if (Arrays.stream(stackTraceElements).anyMatch(ste -> { + return ste.getClassName().endsWith(".TermScorer") && ste.getMethodName().equals("score"); + }) == false) { // this might happen when computing max scores return Float.MAX_VALUE; } diff --git a/server/src/test/java/org/opensearch/index/translog/listener/TranslogListenerTests.java b/server/src/test/java/org/opensearch/index/translog/listener/TranslogListenerTests.java index 1f28e32a6dbec..3a27d26a630d6 100644 --- a/server/src/test/java/org/opensearch/index/translog/listener/TranslogListenerTests.java +++ b/server/src/test/java/org/opensearch/index/translog/listener/TranslogListenerTests.java @@ -98,7 +98,9 @@ public void onFailure(String reason, Exception ex) { TranslogEventListener throwingListener = (TranslogEventListener) Proxy.newProxyInstance( TranslogEventListener.class.getClassLoader(), new Class[] { TranslogEventListener.class }, - (a, b, c) -> { throw new RuntimeException(); } + (a, b, c) -> { + throw new RuntimeException(); + } ); final List translogEventListeners = new LinkedList<>(Arrays.asList(listener, throwingListener, listener)); diff --git a/server/src/test/java/org/opensearch/indices/recovery/PeerRecoveryTargetServiceTests.java b/server/src/test/java/org/opensearch/indices/recovery/PeerRecoveryTargetServiceTests.java index a50089831b3e9..ff4058f953642 100644 --- a/server/src/test/java/org/opensearch/indices/recovery/PeerRecoveryTargetServiceTests.java +++ b/server/src/test/java/org/opensearch/indices/recovery/PeerRecoveryTargetServiceTests.java @@ -148,7 +148,9 @@ public void testWriteFileChunksConcurrently() throws Exception { r.content(), r.lastChunk(), r.totalTranslogOps(), - ActionListener.wrap(ignored -> {}, e -> { throw new AssertionError(e); }) + ActionListener.wrap(ignored -> {}, e -> { + throw new AssertionError(e); + }) ); } } catch (Exception e) { diff --git a/server/src/test/java/org/opensearch/indices/replication/SegmentFileTransferHandlerTests.java b/server/src/test/java/org/opensearch/indices/replication/SegmentFileTransferHandlerTests.java index e13b4ed31fc39..0400d73da4503 100644 --- a/server/src/test/java/org/opensearch/indices/replication/SegmentFileTransferHandlerTests.java +++ b/server/src/test/java/org/opensearch/indices/replication/SegmentFileTransferHandlerTests.java @@ -245,16 +245,13 @@ public void testSendFiles_CorruptIndexException() throws Exception { ); doNothing().when(shard).failShard(anyString(), any()); - assertThrows( - CorruptIndexException.class, - () -> { - handler.handleErrorOnSendFiles( - shard.store(), - new CorruptIndexException("test", "test"), - new StoreFileMetadata[] { SEGMENTS_FILE } - ); - } - ); + assertThrows(CorruptIndexException.class, () -> { + handler.handleErrorOnSendFiles( + shard.store(), + new CorruptIndexException("test", "test"), + new StoreFileMetadata[] { SEGMENTS_FILE } + ); + }); verify(shard, times(1)).failShard(any(), any()); } diff --git a/server/src/test/java/org/opensearch/ingest/CompoundProcessorTests.java b/server/src/test/java/org/opensearch/ingest/CompoundProcessorTests.java index fb0c55fce28f1..b299ac4d66996 100644 --- a/server/src/test/java/org/opensearch/ingest/CompoundProcessorTests.java +++ b/server/src/test/java/org/opensearch/ingest/CompoundProcessorTests.java @@ -75,9 +75,9 @@ public void testEmpty() throws Exception { public void testSingleProcessor() throws Exception { LongSupplier relativeTimeProvider = mock(LongSupplier.class); when(relativeTimeProvider.getAsLong()).thenReturn(0L, TimeUnit.MILLISECONDS.toNanos(1)); - TestProcessor processor = new TestProcessor( - ingestDocument -> { assertStats(0, ingestDocument.getFieldValue("compoundProcessor", CompoundProcessor.class), 1, 0, 0, 0); } - ); + TestProcessor processor = new TestProcessor(ingestDocument -> { + assertStats(0, ingestDocument.getFieldValue("compoundProcessor", CompoundProcessor.class), 1, 0, 0, 0); + }); CompoundProcessor compoundProcessor = new CompoundProcessor(relativeTimeProvider, processor); ingestDocument.setFieldValue("compoundProcessor", compoundProcessor); // ugly hack to assert current count = 1 assertThat(compoundProcessor.getProcessors().size(), equalTo(1)); diff --git a/server/src/test/java/org/opensearch/ingest/ConditionalProcessorTests.java b/server/src/test/java/org/opensearch/ingest/ConditionalProcessorTests.java index d2e4115f50e1d..a383ab9b97918 100644 --- a/server/src/test/java/org/opensearch/ingest/ConditionalProcessorTests.java +++ b/server/src/test/java/org/opensearch/ingest/ConditionalProcessorTests.java @@ -164,11 +164,9 @@ public void testActsOnImmutableData() throws Exception { } public void testPrecompiledError() { - ScriptService scriptService = MockScriptService.singleContext( - IngestConditionalScript.CONTEXT, - code -> { throw new ScriptException("bad script", new ParseException("error", 0), List.of(), "", "lang", null); }, - Map.of() - ); + ScriptService scriptService = MockScriptService.singleContext(IngestConditionalScript.CONTEXT, code -> { + throw new ScriptException("bad script", new ParseException("error", 0), List.of(), "", "lang", null); + }, Map.of()); Script script = new Script(ScriptType.INLINE, "lang", "foo", Map.of()); ScriptException e = expectThrows(ScriptException.class, () -> new ConditionalProcessor(null, null, script, scriptService, null)); assertThat(e.getMessage(), equalTo("bad script")); diff --git a/server/src/test/java/org/opensearch/ingest/PipelineProcessorTests.java b/server/src/test/java/org/opensearch/ingest/PipelineProcessorTests.java index 86e4dd261d408..9f8dda15eeb65 100644 --- a/server/src/test/java/org/opensearch/ingest/PipelineProcessorTests.java +++ b/server/src/test/java/org/opensearch/ingest/PipelineProcessorTests.java @@ -172,25 +172,16 @@ public void testPipelineProcessorWithPipelineChain() throws Exception { pipeline2Id, null, null, - new CompoundProcessor( - true, - Arrays.asList( - new TestProcessor(ingestDocument -> { ingestDocument.setFieldValue(key1, randomInt()); }), - pipeline2Processor - ), - Collections.emptyList() - ), + new CompoundProcessor(true, Arrays.asList(new TestProcessor(ingestDocument -> { + ingestDocument.setFieldValue(key1, randomInt()); + }), pipeline2Processor), Collections.emptyList()), relativeTimeProvider ); relativeTimeProvider = mock(LongSupplier.class); when(relativeTimeProvider.getAsLong()).thenReturn(0L, TimeUnit.MILLISECONDS.toNanos(2)); - Pipeline pipeline3 = new Pipeline( - pipeline3Id, - null, - null, - new CompoundProcessor(new TestProcessor(ingestDocument -> { throw new RuntimeException("error"); })), - relativeTimeProvider - ); + Pipeline pipeline3 = new Pipeline(pipeline3Id, null, null, new CompoundProcessor(new TestProcessor(ingestDocument -> { + throw new RuntimeException("error"); + })), relativeTimeProvider); when(ingestService.getPipeline(pipeline1Id)).thenReturn(pipeline1); when(ingestService.getPipeline(pipeline2Id)).thenReturn(pipeline2); when(ingestService.getPipeline(pipeline3Id)).thenReturn(pipeline3); diff --git a/server/src/test/java/org/opensearch/ingest/TrackingResultProcessorTests.java b/server/src/test/java/org/opensearch/ingest/TrackingResultProcessorTests.java index 343b82e7c034b..16e60cec8c941 100644 --- a/server/src/test/java/org/opensearch/ingest/TrackingResultProcessorTests.java +++ b/server/src/test/java/org/opensearch/ingest/TrackingResultProcessorTests.java @@ -280,14 +280,17 @@ public void testActualCompoundProcessorWithFalseConditional() throws Exception { new HashMap<>(ScriptModule.CORE_CONTEXTS) ); - CompoundProcessor compoundProcessor = new CompoundProcessor( - new TestProcessor(ingestDocument -> { ingestDocument.setFieldValue(key1, randomInt()); }), + CompoundProcessor compoundProcessor = new CompoundProcessor(new TestProcessor(ingestDocument -> { + ingestDocument.setFieldValue(key1, randomInt()); + }), new ConditionalProcessor( randomAlphaOfLength(10), null, new Script(ScriptType.INLINE, Script.DEFAULT_SCRIPT_LANG, scriptName, Collections.emptyMap()), scriptService, - new TestProcessor(ingestDocument -> { ingestDocument.setFieldValue(key2, randomInt()); }) + new TestProcessor(ingestDocument -> { + ingestDocument.setFieldValue(key2, randomInt()); + }) ), new TestProcessor(ingestDocument -> { ingestDocument.setFieldValue(key3, randomInt()); }) ); @@ -331,16 +334,11 @@ public void testActualPipelineProcessor() throws Exception { String key2 = randomAlphaOfLength(10); String key3 = randomAlphaOfLength(10); - Pipeline pipeline = new Pipeline( - pipelineId, - null, - null, - new CompoundProcessor( - new TestProcessor(ingestDocument -> { ingestDocument.setFieldValue(key1, randomInt()); }), - new TestProcessor(ingestDocument -> { ingestDocument.setFieldValue(key2, randomInt()); }), - new TestProcessor(ingestDocument -> { ingestDocument.setFieldValue(key3, randomInt()); }) - ) - ); + Pipeline pipeline = new Pipeline(pipelineId, null, null, new CompoundProcessor(new TestProcessor(ingestDocument -> { + ingestDocument.setFieldValue(key1, randomInt()); + }), new TestProcessor(ingestDocument -> { ingestDocument.setFieldValue(key2, randomInt()); }), new TestProcessor(ingestDocument -> { + ingestDocument.setFieldValue(key3, randomInt()); + }))); when(ingestService.getPipeline(pipelineId)).thenReturn(pipeline); PipelineProcessor pipelineProcessor = factory.create(Collections.emptyMap(), null, null, pipelineConfig); @@ -406,29 +404,24 @@ public void testActualPipelineProcessorWithTrueConditional() throws Exception { new HashMap<>(ScriptModule.CORE_CONTEXTS) ); - Pipeline pipeline1 = new Pipeline( - pipelineId1, - null, - null, - new CompoundProcessor( - new TestProcessor(ingestDocument -> { ingestDocument.setFieldValue(key1, randomInt()); }), - new ConditionalProcessor( - randomAlphaOfLength(10), - null, - new Script(ScriptType.INLINE, Script.DEFAULT_SCRIPT_LANG, scriptName, Collections.emptyMap()), - scriptService, - factory.create(Collections.emptyMap(), "pipeline1", null, pipelineConfig2) - ), - new TestProcessor(ingestDocument -> { ingestDocument.setFieldValue(key3, randomInt()); }) - ) - ); + Pipeline pipeline1 = new Pipeline(pipelineId1, null, null, new CompoundProcessor(new TestProcessor(ingestDocument -> { + ingestDocument.setFieldValue(key1, randomInt()); + }), + new ConditionalProcessor( + randomAlphaOfLength(10), + null, + new Script(ScriptType.INLINE, Script.DEFAULT_SCRIPT_LANG, scriptName, Collections.emptyMap()), + scriptService, + factory.create(Collections.emptyMap(), "pipeline1", null, pipelineConfig2) + ), + new TestProcessor(ingestDocument -> { + ingestDocument.setFieldValue(key3, randomInt()); + }) + )); - Pipeline pipeline2 = new Pipeline( - pipelineId2, - null, - null, - new CompoundProcessor(new TestProcessor(ingestDocument -> { ingestDocument.setFieldValue(key2, randomInt()); })) - ); + Pipeline pipeline2 = new Pipeline(pipelineId2, null, null, new CompoundProcessor(new TestProcessor(ingestDocument -> { + ingestDocument.setFieldValue(key2, randomInt()); + }))); when(ingestService.getPipeline(pipelineId1)).thenReturn(pipeline1); when(ingestService.getPipeline(pipelineId2)).thenReturn(pipeline2); @@ -503,29 +496,24 @@ public void testActualPipelineProcessorWithFalseConditional() throws Exception { new HashMap<>(ScriptModule.CORE_CONTEXTS) ); - Pipeline pipeline1 = new Pipeline( - pipelineId1, - null, - null, - new CompoundProcessor( - new TestProcessor(ingestDocument -> { ingestDocument.setFieldValue(key1, randomInt()); }), - new ConditionalProcessor( - randomAlphaOfLength(10), - null, - new Script(ScriptType.INLINE, Script.DEFAULT_SCRIPT_LANG, scriptName, Collections.emptyMap()), - scriptService, - factory.create(Collections.emptyMap(), null, null, pipelineConfig2) - ), - new TestProcessor(ingestDocument -> { ingestDocument.setFieldValue(key3, randomInt()); }) - ) - ); + Pipeline pipeline1 = new Pipeline(pipelineId1, null, null, new CompoundProcessor(new TestProcessor(ingestDocument -> { + ingestDocument.setFieldValue(key1, randomInt()); + }), + new ConditionalProcessor( + randomAlphaOfLength(10), + null, + new Script(ScriptType.INLINE, Script.DEFAULT_SCRIPT_LANG, scriptName, Collections.emptyMap()), + scriptService, + factory.create(Collections.emptyMap(), null, null, pipelineConfig2) + ), + new TestProcessor(ingestDocument -> { + ingestDocument.setFieldValue(key3, randomInt()); + }) + )); - Pipeline pipeline2 = new Pipeline( - pipelineId2, - null, - null, - new CompoundProcessor(new TestProcessor(ingestDocument -> { ingestDocument.setFieldValue(key2, randomInt()); })) - ); + Pipeline pipeline2 = new Pipeline(pipelineId2, null, null, new CompoundProcessor(new TestProcessor(ingestDocument -> { + ingestDocument.setFieldValue(key2, randomInt()); + }))); when(ingestService.getPipeline(pipelineId1)).thenReturn(pipeline1); when(ingestService.getPipeline(pipelineId2)).thenReturn(pipeline2); @@ -579,20 +567,18 @@ public void testActualPipelineProcessorWithHandledFailure() throws Exception { String key2 = randomAlphaOfLength(10); String key3 = randomAlphaOfLength(10); - Pipeline pipeline = new Pipeline( - pipelineId, - null, - null, + Pipeline pipeline = new Pipeline(pipelineId, null, null, new CompoundProcessor(new TestProcessor(ingestDocument -> { + ingestDocument.setFieldValue(key1, randomInt()); + }), new CompoundProcessor( - new TestProcessor(ingestDocument -> { ingestDocument.setFieldValue(key1, randomInt()); }), - new CompoundProcessor( - false, - Collections.singletonList(new TestProcessor(ingestDocument -> { throw exception; })), - Collections.singletonList(new TestProcessor(ingestDocument -> { ingestDocument.setFieldValue(key2, randomInt()); })) - ), - new TestProcessor(ingestDocument -> { ingestDocument.setFieldValue(key3, randomInt()); }) - ) - ); + false, + Collections.singletonList(new TestProcessor(ingestDocument -> { throw exception; })), + Collections.singletonList(new TestProcessor(ingestDocument -> { + ingestDocument.setFieldValue(key2, randomInt()); + })) + ), + new TestProcessor(ingestDocument -> { ingestDocument.setFieldValue(key3, randomInt()); }) + )); when(ingestService.getPipeline(pipelineId)).thenReturn(pipeline); PipelineProcessor pipelineProcessor = factory.create(Collections.emptyMap(), null, null, pipelineConfig); @@ -650,7 +636,9 @@ public void testActualPipelineProcessorWithUnhandledFailure() throws Exception { null, new CompoundProcessor( new TestProcessor(ingestDocument -> ingestDocument.setFieldValue(key1, randomInt())), - new TestProcessor(ingestDocument -> { throw exception; }) + new TestProcessor(ingestDocument -> { + throw exception; + }) ) ); when(ingestService.getPipeline(pipelineId)).thenReturn(pipeline); @@ -730,12 +718,9 @@ public void testActualPipelineProcessorRepeatedInvocation() throws Exception { String key1 = randomAlphaOfLength(10); PipelineProcessor pipelineProcessor = factory.create(Collections.emptyMap(), null, null, pipelineConfig); - Pipeline pipeline = new Pipeline( - pipelineId, - null, - null, - new CompoundProcessor(new TestProcessor(ingestDocument -> { ingestDocument.setFieldValue(key1, randomInt()); })) - ); + Pipeline pipeline = new Pipeline(pipelineId, null, null, new CompoundProcessor(new TestProcessor(ingestDocument -> { + ingestDocument.setFieldValue(key1, randomInt()); + }))); when(ingestService.getPipeline(pipelineId)).thenReturn(pipeline); // calls the same pipeline twice diff --git a/server/src/test/java/org/opensearch/lucene/misc/search/similarity/LegacyBM25SimilarityTests.java b/server/src/test/java/org/opensearch/lucene/misc/search/similarity/LegacyBM25SimilarityTests.java index 209b0d959c8b0..c58847bb56a3b 100644 --- a/server/src/test/java/org/opensearch/lucene/misc/search/similarity/LegacyBM25SimilarityTests.java +++ b/server/src/test/java/org/opensearch/lucene/misc/search/similarity/LegacyBM25SimilarityTests.java @@ -36,10 +36,9 @@ public class LegacyBM25SimilarityTests extends BaseSimilarityTestCase { public void testIllegalK1() { - IllegalArgumentException expected = expectThrows( - IllegalArgumentException.class, - () -> { new LegacyBM25Similarity(Float.POSITIVE_INFINITY, 0.75f); } - ); + IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> { + new LegacyBM25Similarity(Float.POSITIVE_INFINITY, 0.75f); + }); assertTrue(expected.getMessage().contains("illegal k1 value")); expected = expectThrows(IllegalArgumentException.class, () -> { new LegacyBM25Similarity(-1, 0.75f); }); diff --git a/server/src/test/java/org/opensearch/plugins/PluginsServiceTests.java b/server/src/test/java/org/opensearch/plugins/PluginsServiceTests.java index de8adf3539fe6..6066316bc606b 100644 --- a/server/src/test/java/org/opensearch/plugins/PluginsServiceTests.java +++ b/server/src/test/java/org/opensearch/plugins/PluginsServiceTests.java @@ -922,10 +922,9 @@ public void testNoExtensionConstructors() { class TestExtension implements TestExtensionPoint { private TestExtension() {} } - IllegalStateException e = expectThrows( - IllegalStateException.class, - () -> { PluginsService.createExtension(TestExtension.class, TestExtensionPoint.class, plugin); } - ); + IllegalStateException e = expectThrows(IllegalStateException.class, () -> { + PluginsService.createExtension(TestExtension.class, TestExtensionPoint.class, plugin); + }); assertThat( e, @@ -950,10 +949,9 @@ public TestExtension(TestPlugin plugin) { } } - IllegalStateException e = expectThrows( - IllegalStateException.class, - () -> { PluginsService.createExtension(TestExtension.class, TestExtensionPoint.class, plugin); } - ); + IllegalStateException e = expectThrows(IllegalStateException.class, () -> { + PluginsService.createExtension(TestExtension.class, TestExtensionPoint.class, plugin); + }); assertThat( e, @@ -971,10 +969,9 @@ public TestExtension(TestPlugin plugin) { public void testBadSingleParameterConstructor() { TestPlugin plugin = new TestPlugin(); - IllegalStateException e = expectThrows( - IllegalStateException.class, - () -> { PluginsService.createExtension(BadSingleParameterConstructorExtension.class, TestExtensionPoint.class, plugin); } - ); + IllegalStateException e = expectThrows(IllegalStateException.class, () -> { + PluginsService.createExtension(BadSingleParameterConstructorExtension.class, TestExtensionPoint.class, plugin); + }); assertThat( e, @@ -996,10 +993,9 @@ public void testBadSingleParameterConstructor() { public void testTooManyParametersExtensionConstructors() { TestPlugin plugin = new TestPlugin(); - IllegalStateException e = expectThrows( - IllegalStateException.class, - () -> { PluginsService.createExtension(TooManyParametersConstructorExtension.class, TestExtensionPoint.class, plugin); } - ); + IllegalStateException e = expectThrows(IllegalStateException.class, () -> { + PluginsService.createExtension(TooManyParametersConstructorExtension.class, TestExtensionPoint.class, plugin); + }); assertThat( e, @@ -1019,10 +1015,9 @@ public void testTooManyParametersExtensionConstructors() { public void testThrowingConstructor() { TestPlugin plugin = new TestPlugin(); - IllegalStateException e = expectThrows( - IllegalStateException.class, - () -> { PluginsService.createExtension(ThrowingConstructorExtension.class, TestExtensionPoint.class, plugin); } - ); + IllegalStateException e = expectThrows(IllegalStateException.class, () -> { + PluginsService.createExtension(ThrowingConstructorExtension.class, TestExtensionPoint.class, plugin); + }); assertThat( e, diff --git a/server/src/test/java/org/opensearch/rest/RestControllerTests.java b/server/src/test/java/org/opensearch/rest/RestControllerTests.java index 9c5edee175af8..57ea5e2928cb3 100644 --- a/server/src/test/java/org/opensearch/rest/RestControllerTests.java +++ b/server/src/test/java/org/opensearch/rest/RestControllerTests.java @@ -119,11 +119,9 @@ public void setup() { new BytesRestResponse(RestStatus.OK, BytesRestResponse.TEXT_CONTENT_TYPE, BytesArray.EMPTY) ) ); - restController.registerHandler( - RestRequest.Method.GET, - "/error", - (request, channel, client) -> { throw new IllegalArgumentException("test error"); } - ); + restController.registerHandler(RestRequest.Method.GET, "/error", (request, channel, client) -> { + throw new IllegalArgumentException("test error"); + }); httpServerTransport.start(); } diff --git a/server/src/test/java/org/opensearch/script/ScriptServiceTests.java b/server/src/test/java/org/opensearch/script/ScriptServiceTests.java index f5fc62719564f..0485fc9935f15 100644 --- a/server/src/test/java/org/opensearch/script/ScriptServiceTests.java +++ b/server/src/test/java/org/opensearch/script/ScriptServiceTests.java @@ -391,10 +391,9 @@ public void testDeleteScript() throws Exception { assertNull(scriptMetadata.getStoredScript("_id")); ScriptMetadata errorMetadata = scriptMetadata; - ResourceNotFoundException e = expectThrows( - ResourceNotFoundException.class, - () -> { ScriptMetadata.deleteStoredScript(errorMetadata, "_id"); } - ); + ResourceNotFoundException e = expectThrows(ResourceNotFoundException.class, () -> { + ScriptMetadata.deleteStoredScript(errorMetadata, "_id"); + }); assertEquals("stored script [_id] does not exist and cannot be deleted", e.getMessage()); } @@ -425,24 +424,17 @@ public void testGetStoredScript() throws Exception { public void testMaxSizeLimit() throws Exception { buildScriptService(Settings.builder().put(ScriptService.SCRIPT_MAX_SIZE_IN_BYTES.getKey(), 4).build()); scriptService.compile(new Script(ScriptType.INLINE, "test", "1+1", Collections.emptyMap()), randomFrom(contexts.values())); - IllegalArgumentException iae = expectThrows( - IllegalArgumentException.class, - () -> { - scriptService.compile( - new Script(ScriptType.INLINE, "test", "10+10", Collections.emptyMap()), - randomFrom(contexts.values()) - ); - } - ); + IllegalArgumentException iae = expectThrows(IllegalArgumentException.class, () -> { + scriptService.compile(new Script(ScriptType.INLINE, "test", "10+10", Collections.emptyMap()), randomFrom(contexts.values())); + }); assertEquals("exceeded max allowed inline script size in bytes [4] with size [5] for script [10+10]", iae.getMessage()); clusterSettings.applySettings(Settings.builder().put(ScriptService.SCRIPT_MAX_SIZE_IN_BYTES.getKey(), 6).build()); scriptService.compile(new Script(ScriptType.INLINE, "test", "10+10", Collections.emptyMap()), randomFrom(contexts.values())); clusterSettings.applySettings(Settings.builder().put(ScriptService.SCRIPT_MAX_SIZE_IN_BYTES.getKey(), 5).build()); scriptService.compile(new Script(ScriptType.INLINE, "test", "10+10", Collections.emptyMap()), randomFrom(contexts.values())); - iae = expectThrows( - IllegalArgumentException.class, - () -> { clusterSettings.applySettings(Settings.builder().put(ScriptService.SCRIPT_MAX_SIZE_IN_BYTES.getKey(), 2).build()); } - ); + iae = expectThrows(IllegalArgumentException.class, () -> { + clusterSettings.applySettings(Settings.builder().put(ScriptService.SCRIPT_MAX_SIZE_IN_BYTES.getKey(), 2).build()); + }); assertEquals( "script.max_size_in_bytes cannot be set to [2], stored script [test1] exceeds the new value with a size of [3]", iae.getMessage() @@ -537,10 +529,9 @@ public void testUseContextSettingValue() { assertEquals(ScriptService.SCRIPT_GENERAL_MAX_COMPILATIONS_RATE_SETTING.get(s), ScriptService.USE_CONTEXT_RATE_VALUE); - IllegalArgumentException illegal = expectThrows( - IllegalArgumentException.class, - () -> { ScriptService.SCRIPT_MAX_COMPILATIONS_RATE_SETTING.getAsMap(s); } - ); + IllegalArgumentException illegal = expectThrows(IllegalArgumentException.class, () -> { + ScriptService.SCRIPT_MAX_COMPILATIONS_RATE_SETTING.getAsMap(s); + }); assertEquals("parameter must contain a positive integer and a timevalue, i.e. 10/1m, but was [use-context]", illegal.getMessage()); assertSettingDeprecationsAndWarnings(new Setting[] { SCRIPT_GENERAL_MAX_COMPILATIONS_RATE_SETTING }); diff --git a/server/src/test/java/org/opensearch/search/SearchServiceTests.java b/server/src/test/java/org/opensearch/search/SearchServiceTests.java index e6caf48cf6284..a0747d5ddff14 100644 --- a/server/src/test/java/org/opensearch/search/SearchServiceTests.java +++ b/server/src/test/java/org/opensearch/search/SearchServiceTests.java @@ -741,13 +741,9 @@ public void testOpenScrollContextsConcurrently() throws Exception { public static class FailOnRewriteQueryPlugin extends Plugin implements SearchPlugin { @Override public List> getQueries() { - return singletonList( - new QuerySpec<>( - "fail_on_rewrite_query", - FailOnRewriteQueryBuilder::new, - parseContext -> { throw new UnsupportedOperationException("No query parser for this plugin"); } - ) - ); + return singletonList(new QuerySpec<>("fail_on_rewrite_query", FailOnRewriteQueryBuilder::new, parseContext -> { + throw new UnsupportedOperationException("No query parser for this plugin"); + })); } } diff --git a/server/src/test/java/org/opensearch/search/aggregations/bucket/composite/CompositeAggregatorTests.java b/server/src/test/java/org/opensearch/search/aggregations/bucket/composite/CompositeAggregatorTests.java index 25003e0b84567..eabc4b7764eed 100644 --- a/server/src/test/java/org/opensearch/search/aggregations/bucket/composite/CompositeAggregatorTests.java +++ b/server/src/test/java/org/opensearch/search/aggregations/bucket/composite/CompositeAggregatorTests.java @@ -89,7 +89,9 @@ public void testUnmappedFieldWithTerms() throws Exception { Arrays.asList(new MatchAllDocsQuery(), new DocValuesFieldExistsQuery("keyword")), dataset, () -> new CompositeAggregationBuilder("name", Arrays.asList(new TermsValuesSourceBuilder("unmapped").field("unmapped"))), - (result) -> { assertEquals(0, result.getBuckets().size()); } + (result) -> { + assertEquals(0, result.getBuckets().size()); + } ); testSearchCase( @@ -114,7 +116,9 @@ public void testUnmappedFieldWithTerms() throws Exception { "name", Arrays.asList(new TermsValuesSourceBuilder("unmapped").field("unmapped").missingBucket(true)) ).aggregateAfter(Collections.singletonMap("unmapped", null)), - (result) -> { assertEquals(0, result.getBuckets().size()); } + (result) -> { + assertEquals(0, result.getBuckets().size()); + } ); testSearchCase( @@ -127,7 +131,9 @@ public void testUnmappedFieldWithTerms() throws Exception { new TermsValuesSourceBuilder("unmapped").field("unmapped") ) ), - (result) -> { assertEquals(0, result.getBuckets().size()); } + (result) -> { + assertEquals(0, result.getBuckets().size()); + } ); testSearchCase( diff --git a/server/src/test/java/org/opensearch/search/aggregations/bucket/histogram/NumericHistogramAggregatorTests.java b/server/src/test/java/org/opensearch/search/aggregations/bucket/histogram/NumericHistogramAggregatorTests.java index 9a7546a2f9aea..bb9ed263ca3f6 100644 --- a/server/src/test/java/org/opensearch/search/aggregations/bucket/histogram/NumericHistogramAggregatorTests.java +++ b/server/src/test/java/org/opensearch/search/aggregations/bucket/histogram/NumericHistogramAggregatorTests.java @@ -303,10 +303,9 @@ public void testIncorrectFieldType() throws Exception { try (IndexReader reader = w.getReader()) { IndexSearcher searcher = new IndexSearcher(reader); - expectThrows( - IllegalArgumentException.class, - () -> { searchAndReduce(searcher, new MatchAllDocsQuery(), aggBuilder, keywordField("field")); } - ); + expectThrows(IllegalArgumentException.class, () -> { + searchAndReduce(searcher, new MatchAllDocsQuery(), aggBuilder, keywordField("field")); + }); } } diff --git a/server/src/test/java/org/opensearch/search/aggregations/bucket/histogram/VariableWidthHistogramAggregatorTests.java b/server/src/test/java/org/opensearch/search/aggregations/bucket/histogram/VariableWidthHistogramAggregatorTests.java index 103a1be8595c7..33f2a0b56b5ba 100644 --- a/server/src/test/java/org/opensearch/search/aggregations/bucket/histogram/VariableWidthHistogramAggregatorTests.java +++ b/server/src/test/java/org/opensearch/search/aggregations/bucket/histogram/VariableWidthHistogramAggregatorTests.java @@ -543,7 +543,9 @@ public void testSmallShardSize() throws Exception { List.of(), true, aggregation -> aggregation.field(NUMERIC_FIELD).setNumBuckets(2).setShardSize(2), - histogram -> { fail(); } + histogram -> { + fail(); + } ) ); assertThat(e.getMessage(), equalTo("3/4 of shard_size must be at least buckets but was [1<2] for [_name]")); @@ -571,7 +573,9 @@ public void testSmallInitialBuffer() throws Exception { List.of(), true, aggregation -> aggregation.field(NUMERIC_FIELD).setInitialBuffer(1), - histogram -> { fail(); } + histogram -> { + fail(); + } ) ); assertThat(e.getMessage(), equalTo("initial_buffer must be at least buckets but was [1<10] for [_name]")); diff --git a/server/src/test/java/org/opensearch/search/aggregations/bucket/range/DateRangeAggregatorTests.java b/server/src/test/java/org/opensearch/search/aggregations/bucket/range/DateRangeAggregatorTests.java index e6d7230aa6cb0..9a2ef3de1dfe4 100644 --- a/server/src/test/java/org/opensearch/search/aggregations/bucket/range/DateRangeAggregatorTests.java +++ b/server/src/test/java/org/opensearch/search/aggregations/bucket/range/DateRangeAggregatorTests.java @@ -220,13 +220,9 @@ public void testKeywordField() { IllegalArgumentException e = expectThrows( IllegalArgumentException.class, - () -> testCase( - aggregationBuilder, - new MatchAllDocsQuery(), - iw -> { iw.addDocument(singleton(new SortedSetDocValuesField("string", new BytesRef("foo")))); }, - range -> fail("Should have thrown exception"), - fieldType - ) + () -> testCase(aggregationBuilder, new MatchAllDocsQuery(), iw -> { + iw.addDocument(singleton(new SortedSetDocValuesField("string", new BytesRef("foo")))); + }, range -> fail("Should have thrown exception"), fieldType) ); assertEquals("Field [not_a_number] of type [keyword] is not supported for aggregation [date_range]", e.getMessage()); } diff --git a/server/src/test/java/org/opensearch/search/aggregations/bucket/range/RangeAggregatorTests.java b/server/src/test/java/org/opensearch/search/aggregations/bucket/range/RangeAggregatorTests.java index f1be4d1ede930..8b9bd388eb641 100644 --- a/server/src/test/java/org/opensearch/search/aggregations/bucket/range/RangeAggregatorTests.java +++ b/server/src/test/java/org/opensearch/search/aggregations/bucket/range/RangeAggregatorTests.java @@ -245,13 +245,9 @@ public void testUnsupportedType() { IllegalArgumentException e = expectThrows( IllegalArgumentException.class, - () -> testCase( - aggregationBuilder, - new MatchAllDocsQuery(), - iw -> { iw.addDocument(singleton(new SortedSetDocValuesField("string", new BytesRef("foo")))); }, - range -> fail("Should have thrown exception"), - fieldType - ) + () -> testCase(aggregationBuilder, new MatchAllDocsQuery(), iw -> { + iw.addDocument(singleton(new SortedSetDocValuesField("string", new BytesRef("foo")))); + }, range -> fail("Should have thrown exception"), fieldType) ); assertEquals("Field [not_a_number] of type [keyword] is not supported for aggregation [range]", e.getMessage()); } diff --git a/server/src/test/java/org/opensearch/search/aggregations/bucket/terms/MultiTermsAggregationBuilderTests.java b/server/src/test/java/org/opensearch/search/aggregations/bucket/terms/MultiTermsAggregationBuilderTests.java index 505fb7382ab3b..c0b2b55fefeda 100644 --- a/server/src/test/java/org/opensearch/search/aggregations/bucket/terms/MultiTermsAggregationBuilderTests.java +++ b/server/src/test/java/org/opensearch/search/aggregations/bucket/terms/MultiTermsAggregationBuilderTests.java @@ -91,10 +91,9 @@ protected MultiTermsAggregationBuilder createTestAggregatorBuilder() { } public void testInvalidTermsParams() { - IllegalArgumentException exception = expectThrows( - IllegalArgumentException.class, - () -> { new MultiTermsAggregationBuilder("_name").terms(Collections.singletonList(randomFieldConfig())); } - ); + IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> { + new MultiTermsAggregationBuilder("_name").terms(Collections.singletonList(randomFieldConfig())); + }); assertEquals( "multi term aggregation must has at least 2 terms. Found [1] in [_name] Use terms aggregation for single term aggregation", exception.getMessage() diff --git a/server/src/test/java/org/opensearch/search/aggregations/metrics/HDRPercentilesAggregatorTests.java b/server/src/test/java/org/opensearch/search/aggregations/metrics/HDRPercentilesAggregatorTests.java index bbf7f6cfd9cc2..e08ac840e1785 100644 --- a/server/src/test/java/org/opensearch/search/aggregations/metrics/HDRPercentilesAggregatorTests.java +++ b/server/src/test/java/org/opensearch/search/aggregations/metrics/HDRPercentilesAggregatorTests.java @@ -113,16 +113,9 @@ public void testRangeField() throws IOException { MappedFieldType fieldType = new RangeFieldMapper.RangeFieldType(fieldName, RangeType.DOUBLE); RangeFieldMapper.Range range = new RangeFieldMapper.Range(RangeType.DOUBLE, 1.0D, 5.0D, true, true); BytesRef encodedRange = RangeType.DOUBLE.encodeRanges(Collections.singleton(range)); - expectThrows( - IllegalArgumentException.class, - () -> testCase( - new DocValuesFieldExistsQuery(fieldName), - iw -> { iw.addDocument(singleton(new BinaryDocValuesField(fieldName, encodedRange))); }, - hdr -> {}, - fieldType, - fieldName - ) - ); + expectThrows(IllegalArgumentException.class, () -> testCase(new DocValuesFieldExistsQuery(fieldName), iw -> { + iw.addDocument(singleton(new BinaryDocValuesField(fieldName, encodedRange))); + }, hdr -> {}, fieldType, fieldName)); } public void testNoMatchingField() throws IOException { diff --git a/server/src/test/java/org/opensearch/search/aggregations/metrics/MinAggregatorTests.java b/server/src/test/java/org/opensearch/search/aggregations/metrics/MinAggregatorTests.java index 05b3c5c7e57db..f0273b46ef97e 100644 --- a/server/src/test/java/org/opensearch/search/aggregations/metrics/MinAggregatorTests.java +++ b/server/src/test/java/org/opensearch/search/aggregations/metrics/MinAggregatorTests.java @@ -302,13 +302,9 @@ public void testUnsupportedType() { IllegalArgumentException e = expectThrows( IllegalArgumentException.class, - () -> testCase( - aggregationBuilder, - new MatchAllDocsQuery(), - iw -> { iw.addDocument(singleton(new SortedSetDocValuesField("string", new BytesRef("foo")))); }, - (Consumer) min -> { fail("Should have thrown exception"); }, - fieldType - ) + () -> testCase(aggregationBuilder, new MatchAllDocsQuery(), iw -> { + iw.addDocument(singleton(new SortedSetDocValuesField("string", new BytesRef("foo")))); + }, (Consumer) min -> { fail("Should have thrown exception"); }, fieldType) ); assertEquals("Field [not_a_number] of type [keyword] is not supported for aggregation [min]", e.getMessage()); } diff --git a/server/src/test/java/org/opensearch/search/aggregations/metrics/ScriptedMetricAggregatorTests.java b/server/src/test/java/org/opensearch/search/aggregations/metrics/ScriptedMetricAggregatorTests.java index f2a61521eff1f..6a4ecf01577d8 100644 --- a/server/src/test/java/org/opensearch/search/aggregations/metrics/ScriptedMetricAggregatorTests.java +++ b/server/src/test/java/org/opensearch/search/aggregations/metrics/ScriptedMetricAggregatorTests.java @@ -593,12 +593,9 @@ public void testInitScriptMakesArray() throws IOException { .mapScript(MAP_SCRIPT) .combineScript(COMBINE_SCRIPT) .reduceScript(REDUCE_SCRIPT); - testCase( - aggregationBuilder, - new MatchAllDocsQuery(), - iw -> { iw.addDocument(new Document()); }, - (InternalScriptedMetric r) -> { assertEquals(1, r.aggregation()); } - ); + testCase(aggregationBuilder, new MatchAllDocsQuery(), iw -> { iw.addDocument(new Document()); }, (InternalScriptedMetric r) -> { + assertEquals(1, r.aggregation()); + }); } public void testAsSubAgg() throws IOException { diff --git a/server/src/test/java/org/opensearch/search/suggest/SuggestBuilderTests.java b/server/src/test/java/org/opensearch/search/suggest/SuggestBuilderTests.java index 964d6b0f83f19..a8500bb152b00 100644 --- a/server/src/test/java/org/opensearch/search/suggest/SuggestBuilderTests.java +++ b/server/src/test/java/org/opensearch/search/suggest/SuggestBuilderTests.java @@ -102,11 +102,9 @@ public void testFromXContent() throws IOException { public void testEqualsAndHashcode() throws IOException { for (int runs = 0; runs < NUMBER_OF_RUNS; runs++) { // explicit about type parameters, see: https://bugs.eclipse.org/bugs/show_bug.cgi?id=481649 - EqualsHashCodeTestUtils.checkEqualsAndHashCode( - randomSuggestBuilder(), - original -> { return copyWriteable(original, namedWriteableRegistry, SuggestBuilder::new); }, - this::createMutation - ); + EqualsHashCodeTestUtils.checkEqualsAndHashCode(randomSuggestBuilder(), original -> { + return copyWriteable(original, namedWriteableRegistry, SuggestBuilder::new); + }, this::createMutation); } } diff --git a/server/src/test/java/org/opensearch/transport/TransportActionProxyTests.java b/server/src/test/java/org/opensearch/transport/TransportActionProxyTests.java index 33f5a8d9e852f..0488f249cb09e 100644 --- a/server/src/test/java/org/opensearch/transport/TransportActionProxyTests.java +++ b/server/src/test/java/org/opensearch/transport/TransportActionProxyTests.java @@ -168,12 +168,9 @@ public void testException() throws InterruptedException { }); TransportActionProxy.registerProxyAction(serviceB, "internal:test", SimpleTestResponse::new); serviceB.connectToNode(nodeC); - serviceC.registerRequestHandler( - "internal:test", - ThreadPool.Names.SAME, - SimpleTestRequest::new, - (request, channel, task) -> { throw new OpenSearchException("greetings from TS_C"); } - ); + serviceC.registerRequestHandler("internal:test", ThreadPool.Names.SAME, SimpleTestRequest::new, (request, channel, task) -> { + throw new OpenSearchException("greetings from TS_C"); + }); TransportActionProxy.registerProxyAction(serviceC, "internal:test", SimpleTestResponse::new); CountDownLatch latch = new CountDownLatch(1); diff --git a/server/src/test/java/org/opensearch/transport/TransportServiceHandshakeTests.java b/server/src/test/java/org/opensearch/transport/TransportServiceHandshakeTests.java index c0af5d6e76c59..357d7fffa8df6 100644 --- a/server/src/test/java/org/opensearch/transport/TransportServiceHandshakeTests.java +++ b/server/src/test/java/org/opensearch/transport/TransportServiceHandshakeTests.java @@ -218,10 +218,9 @@ public void testNodeConnectWithDifferentNodeId() { emptySet(), handleB.discoveryNode.getVersion() ); - ConnectTransportException ex = expectThrows( - ConnectTransportException.class, - () -> { handleA.transportService.connectToNode(discoveryNode, TestProfiles.LIGHT_PROFILE); } - ); + ConnectTransportException ex = expectThrows(ConnectTransportException.class, () -> { + handleA.transportService.connectToNode(discoveryNode, TestProfiles.LIGHT_PROFILE); + }); assertThat(ex.getMessage(), containsString("unexpected remote node")); assertFalse(handleA.transportService.nodeConnected(discoveryNode)); } diff --git a/test/framework/src/main/java/org/opensearch/index/mapper/MapperServiceTestCase.java b/test/framework/src/main/java/org/opensearch/index/mapper/MapperServiceTestCase.java index dcc75509b0cf3..30cbe5dcc6091 100644 --- a/test/framework/src/main/java/org/opensearch/index/mapper/MapperServiceTestCase.java +++ b/test/framework/src/main/java/org/opensearch/index/mapper/MapperServiceTestCase.java @@ -155,7 +155,9 @@ protected final MapperService createMapperService(Version version, XContentBuild xContentRegistry(), similarityService, mapperRegistry, - () -> { throw new UnsupportedOperationException(); }, + () -> { + throw new UnsupportedOperationException(); + }, () -> true, scriptService ); @@ -249,9 +251,9 @@ QueryShardContext createQueryShardContext(MapperService mapperService) { inv -> mapperService.simpleMatchToFullName(inv.getArguments()[0].toString()) ); when(queryShardContext.allowExpensiveQueries()).thenReturn(true); - when(queryShardContext.lookup()).thenReturn( - new SearchLookup(mapperService, (ft, s) -> { throw new UnsupportedOperationException("search lookup not available"); }) - ); + when(queryShardContext.lookup()).thenReturn(new SearchLookup(mapperService, (ft, s) -> { + throw new UnsupportedOperationException("search lookup not available"); + })); return queryShardContext; } } diff --git a/test/framework/src/main/java/org/opensearch/index/mapper/MapperTestCase.java b/test/framework/src/main/java/org/opensearch/index/mapper/MapperTestCase.java index c55374b39ac0f..5634482ab7c6b 100644 --- a/test/framework/src/main/java/org/opensearch/index/mapper/MapperTestCase.java +++ b/test/framework/src/main/java/org/opensearch/index/mapper/MapperTestCase.java @@ -286,22 +286,22 @@ protected final List fetchFromDocValues(MapperService mapperService, MappedFi throws IOException { BiFunction, IndexFieldData> fieldDataLookup = (mft, lookupSource) -> mft - .fielddataBuilder("test", () -> { throw new UnsupportedOperationException(); }) + .fielddataBuilder("test", () -> { + throw new UnsupportedOperationException(); + }) .build(new IndexFieldDataCache.None(), new NoneCircuitBreakerService()); SetOnce> result = new SetOnce<>(); - withLuceneIndex( - mapperService, - iw -> { iw.addDocument(mapperService.documentMapper().parse(source(b -> b.field(ft.name(), sourceValue))).rootDoc()); }, - iw -> { - SearchLookup lookup = new SearchLookup(mapperService, fieldDataLookup); - ValueFetcher valueFetcher = new DocValueFetcher(format, lookup.doc().getForField(ft)); - IndexSearcher searcher = newSearcher(iw); - LeafReaderContext context = searcher.getIndexReader().leaves().get(0); - lookup.source().setSegmentAndDocument(context, 0); - valueFetcher.setNextReader(context); - result.set(valueFetcher.fetchValues(lookup.source())); - } - ); + withLuceneIndex(mapperService, iw -> { + iw.addDocument(mapperService.documentMapper().parse(source(b -> b.field(ft.name(), sourceValue))).rootDoc()); + }, iw -> { + SearchLookup lookup = new SearchLookup(mapperService, fieldDataLookup); + ValueFetcher valueFetcher = new DocValueFetcher(format, lookup.doc().getForField(ft)); + IndexSearcher searcher = newSearcher(iw); + LeafReaderContext context = searcher.getIndexReader().leaves().get(0); + lookup.source().setSegmentAndDocument(context, 0); + valueFetcher.setNextReader(context); + result.set(valueFetcher.fetchValues(lookup.source())); + }); return result.get(); } diff --git a/test/framework/src/main/java/org/opensearch/index/replication/OpenSearchIndexLevelReplicationTestCase.java b/test/framework/src/main/java/org/opensearch/index/replication/OpenSearchIndexLevelReplicationTestCase.java index 8df57ccad85cc..e349fbdd6f1fc 100644 --- a/test/framework/src/main/java/org/opensearch/index/replication/OpenSearchIndexLevelReplicationTestCase.java +++ b/test/framework/src/main/java/org/opensearch/index/replication/OpenSearchIndexLevelReplicationTestCase.java @@ -237,7 +237,9 @@ protected class ReplicationGroup implements AutoCloseable, Iterable (shardId, primaryAllocationId, primaryTerm, retentionLeases) -> syncRetentionLeases( shardId, retentionLeases, - ActionListener.wrap(r -> {}, e -> { throw new AssertionError("failed to background sync retention lease", e); }) + ActionListener.wrap(r -> {}, e -> { + throw new AssertionError("failed to background sync retention lease", e); + }) ) ); diff --git a/test/framework/src/main/java/org/opensearch/index/seqno/RetentionLeaseUtils.java b/test/framework/src/main/java/org/opensearch/index/seqno/RetentionLeaseUtils.java index bf06b481a2377..8216f1053a60b 100644 --- a/test/framework/src/main/java/org/opensearch/index/seqno/RetentionLeaseUtils.java +++ b/test/framework/src/main/java/org/opensearch/index/seqno/RetentionLeaseUtils.java @@ -53,13 +53,8 @@ public static Map toMapExcludingPeerRecoveryRetentionLea return retentionLeases.leases() .stream() .filter(l -> ReplicationTracker.PEER_RECOVERY_RETENTION_LEASE_SOURCE.equals(l.source()) == false) - .collect( - Collectors.toMap( - RetentionLease::id, - Function.identity(), - (o1, o2) -> { throw new AssertionError("unexpectedly merging " + o1 + " and " + o2); }, - LinkedHashMap::new - ) - ); + .collect(Collectors.toMap(RetentionLease::id, Function.identity(), (o1, o2) -> { + throw new AssertionError("unexpectedly merging " + o1 + " and " + o2); + }, LinkedHashMap::new)); } } diff --git a/test/framework/src/main/java/org/opensearch/test/AbstractBuilderTestCase.java b/test/framework/src/main/java/org/opensearch/test/AbstractBuilderTestCase.java index a873449828210..3eb56c9451c97 100644 --- a/test/framework/src/main/java/org/opensearch/test/AbstractBuilderTestCase.java +++ b/test/framework/src/main/java/org/opensearch/test/AbstractBuilderTestCase.java @@ -369,12 +369,9 @@ private static class ServiceHolder implements Closeable { boolean registerType ) throws IOException { this.nowInMillis = nowInMillis; - Environment env = InternalSettingsPreparer.prepareEnvironment( - nodeSettings, - emptyMap(), - null, - () -> { throw new AssertionError("node.name must be set"); } - ); + Environment env = InternalSettingsPreparer.prepareEnvironment(nodeSettings, emptyMap(), null, () -> { + throw new AssertionError("node.name must be set"); + }); PluginsService pluginsService; pluginsService = new PluginsService(nodeSettings, null, env.modulesDir(), env.pluginsDir(), plugins); diff --git a/test/framework/src/main/java/org/opensearch/test/AbstractQueryTestCase.java b/test/framework/src/main/java/org/opensearch/test/AbstractQueryTestCase.java index 21d689e93c0db..33d292ddb65cd 100644 --- a/test/framework/src/main/java/org/opensearch/test/AbstractQueryTestCase.java +++ b/test/framework/src/main/java/org/opensearch/test/AbstractQueryTestCase.java @@ -732,7 +732,8 @@ protected static String getRandomRewriteMethod() { .getPreferredName(); } else { rewrite = randomFrom(QueryParsers.TOP_TERMS, QueryParsers.TOP_TERMS_BOOST, QueryParsers.TOP_TERMS_BLENDED_FREQS) - .getPreferredName() + "1"; + .getPreferredName() + + "1"; } return rewrite; } diff --git a/test/framework/src/main/java/org/opensearch/transport/AbstractSimpleTransportTestCase.java b/test/framework/src/main/java/org/opensearch/transport/AbstractSimpleTransportTestCase.java index e4b98124ea441..106d2ae15917f 100644 --- a/test/framework/src/main/java/org/opensearch/transport/AbstractSimpleTransportTestCase.java +++ b/test/framework/src/main/java/org/opensearch/transport/AbstractSimpleTransportTestCase.java @@ -2108,7 +2108,9 @@ public void testRegisterHandlerTwice() { "internal:action1", randomFrom(ThreadPool.Names.SAME, ThreadPool.Names.GENERIC), TestRequest::new, - (request, message, task) -> { throw new AssertionError("boom"); } + (request, message, task) -> { + throw new AssertionError("boom"); + } ); expectThrows( IllegalArgumentException.class, @@ -2116,7 +2118,9 @@ public void testRegisterHandlerTwice() { "internal:action1", randomFrom(ThreadPool.Names.SAME, ThreadPool.Names.GENERIC), TestRequest::new, - (request, message, task) -> { throw new AssertionError("boom"); } + (request, message, task) -> { + throw new AssertionError("boom"); + } ) ); @@ -2124,7 +2128,9 @@ public void testRegisterHandlerTwice() { "internal:action1", randomFrom(ThreadPool.Names.SAME, ThreadPool.Names.GENERIC), TestRequest::new, - (request, message, task) -> { throw new AssertionError("boom"); } + (request, message, task) -> { + throw new AssertionError("boom"); + } ); }