From 33e70a98863e10c766b78df5075f60d744c1b560 Mon Sep 17 00:00:00 2001 From: Owais Kazi Date: Thu, 21 Oct 2021 13:13:38 -0700 Subject: [PATCH] Run spotless and exclude checkstyle on client module (#1392) Signed-off-by: Owais Kazi --- .../resources/checkstyle_suppressions.xml | 14 +- .../client/benchmark/AbstractBenchmark.java | 29 +- .../client/benchmark/BenchmarkRunner.java | 32 +- .../client/benchmark/metrics/Metrics.java | 22 +- .../benchmark/metrics/MetricsCalculator.java | 40 +- .../benchmark/ops/bulk/BulkBenchmarkTask.java | 27 +- .../ops/search/SearchBenchmarkTask.java | 9 +- .../benchmark/rest/RestClientBenchmark.java | 8 +- .../opensearch/plugin/noop/NoopPlugin.java | 16 +- .../noop/action/bulk/RestNoopBulkAction.java | 38 +- .../action/bulk/TransportNoopBulkAction.java | 7 +- .../action/search/RestNoopSearchAction.java | 17 +- .../search/TransportNoopSearchAction.java | 27 +- .../org/opensearch/client/ClusterClient.java | 221 ++- .../client/ClusterRequestConverters.java | 17 +- .../org/opensearch/client/IndicesClient.java | 1359 +++++++++++---- .../client/IndicesRequestConverters.java | 93 +- .../org/opensearch/client/IngestClient.java | 94 +- .../client/IngestRequestConverters.java | 10 +- .../client/NodesResponseHeader.java | 34 +- .../opensearch/client/RequestConverters.java | 114 +- .../client/RestHighLevelClient.java | 1034 ++++++++---- .../opensearch/client/RethrottleRequest.java | 4 +- .../org/opensearch/client/SnapshotClient.java | 311 +++- .../client/SnapshotRequestConverters.java | 17 +- .../client/SyncedFlushResponse.java | 39 +- .../org/opensearch/client/TasksClient.java | 48 +- .../client/TasksRequestConverters.java | 13 +- .../org/opensearch/client/Validatable.java | 3 +- .../client/cluster/ProxyModeInfo.java | 8 +- .../client/cluster/RemoteConnectionInfo.java | 40 +- .../client/cluster/SniffModeInfo.java | 6 +- .../client/core/AcknowledgedResponse.java | 7 +- .../client/core/BroadcastResponse.java | 38 +- .../opensearch/client/core/CountRequest.java | 19 +- .../opensearch/client/core/CountResponse.java | 34 +- .../client/core/GetSourceRequest.java | 3 +- .../client/core/IndexerJobStats.java | 94 +- .../opensearch/client/core/IndexerState.java | 1 - .../opensearch/client/core/MainRequest.java | 3 +- .../opensearch/client/core/MainResponse.java | 82 +- .../client/core/MultiTermVectorsResponse.java | 12 +- .../opensearch/client/core/PageParams.java | 9 +- .../core/ShardsAcknowledgedResponse.java | 8 +- .../client/core/TermVectorsRequest.java | 15 +- .../client/core/TermVectorsResponse.java | 84 +- .../client/indices/AnalyzeRequest.java | 9 +- .../client/indices/AnalyzeResponse.java | 31 +- .../client/indices/CloseIndexResponse.java | 45 +- .../client/indices/CreateIndexRequest.java | 16 +- .../client/indices/CreateIndexResponse.java | 7 +- .../opensearch/client/indices/DataStream.java | 44 +- .../indices/DataStreamsStatsResponse.java | 114 +- .../client/indices/DetailAnalyzeResponse.java | 70 +- .../GetComponentTemplatesResponse.java | 21 +- .../GetComposableIndexTemplatesResponse.java | 21 +- .../client/indices/GetDataStreamResponse.java | 1 - .../indices/GetFieldMappingsResponse.java | 45 +- .../client/indices/GetIndexRequest.java | 1 - .../client/indices/GetIndexResponse.java | 24 +- .../indices/GetIndexTemplatesResponse.java | 14 +- .../client/indices/GetMappingsResponse.java | 9 +- .../client/indices/IndexTemplateMetadata.java | 72 +- .../indices/PutIndexTemplateRequest.java | 37 +- .../client/indices/ResizeResponse.java | 7 +- .../SimulateIndexTemplateResponse.java | 36 +- .../indices/rollover/RolloverRequest.java | 6 +- .../indices/rollover/RolloverResponse.java | 37 +- ...xecuteSnapshotLifecyclePolicyResponse.java | 8 +- ...cuteSnapshotLifecycleRetentionRequest.java | 3 +- .../client/slm/SnapshotInvocationRecord.java | 14 +- ...pshotLifecycleManagementStatusRequest.java | 3 +- .../client/slm/SnapshotLifecyclePolicy.java | 45 +- .../slm/SnapshotLifecyclePolicyMetadata.java | 81 +- .../client/slm/SnapshotLifecycleStats.java | 76 +- .../slm/SnapshotRetentionConfiguration.java | 31 +- .../client/slm/StartSLMRequest.java | 3 +- .../opensearch/client/slm/StopSLMRequest.java | 3 +- .../client/tasks/CancelTasksRequest.java | 46 +- .../client/tasks/CancelTasksResponse.java | 40 +- .../client/tasks/GetTaskRequest.java | 8 +- .../client/tasks/GetTaskResponse.java | 7 +- .../client/tasks/ListTasksResponse.java | 45 +- .../org/opensearch/client/tasks/NodeData.java | 59 +- .../client/tasks/OpenSearchException.java | 30 +- .../opensearch/client/tasks/TaskGroup.java | 14 +- .../org/opensearch/client/tasks/TaskId.java | 4 +- .../org/opensearch/client/tasks/TaskInfo.java | 70 +- .../client/tasks/TaskOperationFailure.java | 39 +- .../client/tasks/TaskSubmissionResponse.java | 4 +- .../client/AbstractRequestTestCase.java | 5 +- .../client/AbstractResponseTestCase.java | 3 +- .../opensearch/client/BulkProcessorIT.java | 203 ++- .../client/BulkProcessorRetryIT.java | 19 +- .../BulkRequestWithGlobalParametersIT.java | 95 +- .../opensearch/client/ClusterClientIT.java | 153 +- .../client/ClusterRequestConvertersTests.java | 1 - .../java/org/opensearch/client/CrudIT.java | 398 +++-- .../CustomRestHighLevelClientTests.java | 45 +- .../client/GetAliasesResponseTests.java | 78 +- .../HighLevelRestClientCompressionIT.java | 4 +- .../opensearch/client/IndicesClientIT.java | 1501 +++++++++++------ .../client/IndicesRequestConvertersTests.java | 270 ++- .../org/opensearch/client/IngestClientIT.java | 97 +- .../client/IngestRequestConvertersTests.java | 3 +- .../client/MockRestHighLevelTests.java | 9 +- .../client/NodesResponseHeaderTestUtils.java | 1 - ...OpenSearchRestHighLevelClientTestCase.java | 129 +- .../org/opensearch/client/RankEvalIT.java | 13 +- .../java/org/opensearch/client/ReindexIT.java | 114 +- .../client/RequestConvertersTests.java | 264 +-- .../client/RestHighLevelClientExtTests.java | 22 +- .../client/RestHighLevelClientTests.java | 497 ++++-- .../java/org/opensearch/client/SearchIT.java | 465 ++--- .../org/opensearch/client/SnapshotIT.java | 136 +- .../SnapshotRequestConvertersTests.java | 5 +- .../opensearch/client/StoredScriptsIT.java | 46 +- .../client/SyncedFlushResponseTests.java | 97 +- .../java/org/opensearch/client/TasksIT.java | 25 +- .../client/TasksRequestConvertersTests.java | 15 +- .../opensearch/client/TimedRequestTests.java | 8 +- .../opensearch/client/UpdateByQueryIT.java | 84 +- .../cluster/RemoteInfoResponseTests.java | 36 +- .../core/AcknowledgedResponseTests.java | 9 +- .../client/core/BroadcastResponseTests.java | 14 +- .../client/core/CountRequestTests.java | 21 +- .../client/core/CountResponseTests.java | 51 +- .../client/core/GetSourceResponseTests.java | 3 +- .../client/core/MainResponseTests.java | 22 +- .../core/MultiTermVectorsResponseTests.java | 9 +- .../core/ShardsAcknowledgedResponseTests.java | 8 +- .../client/core/TermVectorsResponseTests.java | 64 +- .../core/tasks/GetTaskResponseTests.java | 17 +- .../documentation/CRUDDocumentationIT.java | 206 +-- .../ClusterClientDocumentationIT.java | 35 +- .../IndicesClientDocumentationIT.java | 198 +-- .../IngestClientDocumentationIT.java | 28 +- .../QueryDSLDocumentationTests.java | 20 +- .../documentation/SearchDocumentationIT.java | 261 ++- .../SnapshotClientDocumentationIT.java | 1 - .../StoredScriptsDocumentationIT.java | 22 +- .../TasksClientDocumentationIT.java | 1 - .../client/indices/AnalyzeRequestTests.java | 3 +- .../client/indices/AnalyzeResponseTests.java | 28 +- .../indices/CloseIndexRequestTests.java | 2 +- .../indices/CloseIndexResponseTests.java | 50 +- .../indices/CreateIndexRequestTests.java | 6 +- .../DataStreamsStatsResponseTests.java | 30 +- .../GetComponentTemplatesResponseTests.java | 16 +- ...ComposableIndexTemplatesResponseTests.java | 6 +- .../GetFieldMappingsResponseTests.java | 9 +- .../client/indices/GetIndexResponseTests.java | 12 +- .../GetIndexTemplatesResponseTests.java | 46 +- .../indices/GetMappingsResponseTests.java | 10 +- .../indices/PutIndexTemplateRequestTests.java | 14 +- .../indices/PutMappingRequestTests.java | 6 +- .../indices/RandomCreateIndexGenerator.java | 7 +- .../client/indices/ResizeRequestTests.java | 21 +- .../client/indices/ResizeResponseTests.java | 11 +- .../rollover/RolloverRequestTests.java | 6 +- .../rollover/RolloverResponseTests.java | 9 +- .../tasks/CancelTasksResponseTests.java | 72 +- .../tasks/OpenSearchExceptionTests.java | 33 +- .../tasks/TaskSubmissionResponseTests.java | 6 +- .../org/opensearch/client/Cancellable.java | 3 +- .../org/opensearch/client/DeadHostState.java | 24 +- .../client/HasAttributeNodeSelector.java | 3 +- .../HeapBufferedAsyncResponseConsumer.java | 5 +- .../HttpAsyncResponseConsumerFactory.java | 2 +- .../main/java/org/opensearch/client/Node.java | 5 +- .../org/opensearch/client/NodeSelector.java | 4 +- ...tentCredentialsAuthenticationStrategy.java | 9 +- .../PreferHasAttributeNodeSelector.java | 3 +- .../java/org/opensearch/client/Request.java | 10 +- .../org/opensearch/client/RequestLogger.java | 32 +- .../org/opensearch/client/RequestOptions.java | 27 +- .../java/org/opensearch/client/Response.java | 38 +- .../opensearch/client/ResponseException.java | 3 +- .../org/opensearch/client/RestClient.java | 99 +- .../opensearch/client/RestClientBuilder.java | 29 +- .../opensearch/client/DeadHostStateTests.java | 20 +- .../FailureTrackingResponseListenerTests.java | 2 +- .../client/HasAttributeNodeSelectorTests.java | 12 +- ...eapBufferedAsyncResponseConsumerTests.java | 27 +- .../client/HostsTrackingFailureListener.java | 2 +- .../opensearch/client/NodeSelectorTests.java | 12 +- .../java/org/opensearch/client/NodeTests.java | 128 +- .../PreferHasAttributeNodeSelectorTests.java | 10 +- .../opensearch/client/RequestLoggerTests.java | 54 +- .../client/RequestOptionsTests.java | 38 +- .../org/opensearch/client/RequestTests.java | 59 +- .../client/ResponseExceptionTests.java | 11 +- .../client/RestClientBuilderIntegTests.java | 19 +- .../client/RestClientBuilderTests.java | 30 +- .../RestClientMultipleHostsIntegTests.java | 18 +- .../client/RestClientMultipleHostsTests.java | 80 +- .../RestClientSingleHostIntegTests.java | 51 +- .../client/RestClientSingleHostTests.java | 118 +- .../opensearch/client/RestClientTests.java | 51 +- .../client/sniff/OpenSearchNodesSniffer.java | 38 +- .../org/opensearch/client/sniff/Sniffer.java | 14 +- .../OpenSearchNodesSnifferParseTests.java | 66 +- .../sniff/OpenSearchNodesSnifferTests.java | 36 +- .../sniff/SniffOnFailureListenerTests.java | 6 +- .../client/sniff/SnifferBuilderTests.java | 10 +- .../opensearch/client/sniff/SnifferTests.java | 79 +- .../opensearch/client/RestClientTestCase.java | 16 +- .../opensearch/client/RestClientTestUtil.java | 4 +- .../client/PreBuiltTransportClient.java | 16 +- .../client/PreBuiltTransportClientTests.java | 15 +- gradle/formatting.gradle | 7 - 211 files changed, 8038 insertions(+), 5001 deletions(-) diff --git a/buildSrc/src/main/resources/checkstyle_suppressions.xml b/buildSrc/src/main/resources/checkstyle_suppressions.xml index f7c5d5defb7..c065ca576ea 100644 --- a/buildSrc/src/main/resources/checkstyle_suppressions.xml +++ b/buildSrc/src/main/resources/checkstyle_suppressions.xml @@ -17,23 +17,15 @@ - + + + - - - - - - - - - - diff --git a/client/benchmark/src/main/java/org/opensearch/client/benchmark/AbstractBenchmark.java b/client/benchmark/src/main/java/org/opensearch/client/benchmark/AbstractBenchmark.java index f4d3f34ba29..de9d075cb9a 100644 --- a/client/benchmark/src/main/java/org/opensearch/client/benchmark/AbstractBenchmark.java +++ b/client/benchmark/src/main/java/org/opensearch/client/benchmark/AbstractBenchmark.java @@ -77,8 +77,7 @@ public abstract class AbstractBenchmark { @SuppressForbidden(reason = "system out is ok for a command line tool") private void runBulkIndexBenchmark(String[] args) throws Exception { if (args.length != 7) { - System.err.println( - "usage: 'bulk' benchmarkTargetHostIp indexFilePath indexName typeName numberOfDocuments bulkSize"); + System.err.println("usage: 'bulk' benchmarkTargetHostIp indexFilePath indexName typeName numberOfDocuments bulkSize"); System.exit(1); } String benchmarkTargetHost = args[1]; @@ -95,9 +94,11 @@ public abstract class AbstractBenchmark { T client = client(benchmarkTargetHost); - BenchmarkRunner benchmark = new BenchmarkRunner(warmupIterations, iterations, - new BulkBenchmarkTask( - bulkRequestExecutor(client, indexName, typeName), indexFilePath, warmupIterations, iterations, bulkSize)); + BenchmarkRunner benchmark = new BenchmarkRunner( + warmupIterations, + iterations, + new BulkBenchmarkTask(bulkRequestExecutor(client, indexName, typeName), indexFilePath, warmupIterations, iterations, bulkSize) + ); try { runTrials(() -> { @@ -113,8 +114,7 @@ public abstract class AbstractBenchmark { @SuppressForbidden(reason = "system out is ok for a command line tool") private void runSearchBenchmark(String[] args) throws Exception { if (args.length != 5) { - System.err.println( - "usage: 'search' benchmarkTargetHostIp indexName searchRequestBody throughputRates"); + System.err.println("usage: 'search' benchmarkTargetHostIp indexName searchRequestBody throughputRates"); System.exit(1); } String benchmarkTargetHost = args[1]; @@ -127,12 +127,19 @@ public abstract class AbstractBenchmark { try { runTrials(() -> { for (int throughput : throughputRates) { - //GC between trials to reduce the likelihood of a GC occurring in the middle of a trial. + // GC between trials to reduce the likelihood of a GC occurring in the middle of a trial. runGc(); - BenchmarkRunner benchmark = new BenchmarkRunner(SEARCH_BENCHMARK_ITERATIONS, SEARCH_BENCHMARK_ITERATIONS, + BenchmarkRunner benchmark = new BenchmarkRunner( + SEARCH_BENCHMARK_ITERATIONS, + SEARCH_BENCHMARK_ITERATIONS, new SearchBenchmarkTask( - searchRequestExecutor(client, indexName), searchBody, SEARCH_BENCHMARK_ITERATIONS, - SEARCH_BENCHMARK_ITERATIONS, throughput)); + searchRequestExecutor(client, indexName), + searchBody, + SEARCH_BENCHMARK_ITERATIONS, + SEARCH_BENCHMARK_ITERATIONS, + throughput + ) + ); System.out.printf("Target throughput = %d ops / s%n", throughput); benchmark.run(); } diff --git a/client/benchmark/src/main/java/org/opensearch/client/benchmark/BenchmarkRunner.java b/client/benchmark/src/main/java/org/opensearch/client/benchmark/BenchmarkRunner.java index 9fb9e569402..4beb82b939b 100644 --- a/client/benchmark/src/main/java/org/opensearch/client/benchmark/BenchmarkRunner.java +++ b/client/benchmark/src/main/java/org/opensearch/client/benchmark/BenchmarkRunner.java @@ -55,8 +55,12 @@ public final class BenchmarkRunner { @SuppressForbidden(reason = "system out is ok for a command line tool") public void run() { SampleRecorder recorder = new SampleRecorder(iterations); - System.out.printf("Running %s with %d warmup iterations and %d iterations.%n", - task.getClass().getSimpleName(), warmupIterations, iterations); + System.out.printf( + "Running %s with %d warmup iterations and %d iterations.%n", + task.getClass().getSimpleName(), + warmupIterations, + iterations + ); try { task.setUp(recorder); @@ -78,14 +82,26 @@ public final class BenchmarkRunner { for (Metrics metrics : summaryMetrics) { String throughput = String.format(Locale.ROOT, "Throughput [ops/s]: %f", metrics.throughput); - String serviceTimes = String.format(Locale.ROOT, + String serviceTimes = String.format( + Locale.ROOT, "Service time [ms]: p50 = %f, p90 = %f, p95 = %f, p99 = %f, p99.9 = %f, p99.99 = %f", - metrics.serviceTimeP50, metrics.serviceTimeP90, metrics.serviceTimeP95, - metrics.serviceTimeP99, metrics.serviceTimeP999, metrics.serviceTimeP9999); - String latencies = String.format(Locale.ROOT, + metrics.serviceTimeP50, + metrics.serviceTimeP90, + metrics.serviceTimeP95, + metrics.serviceTimeP99, + metrics.serviceTimeP999, + metrics.serviceTimeP9999 + ); + String latencies = String.format( + Locale.ROOT, "Latency [ms]: p50 = %f, p90 = %f, p95 = %f, p99 = %f, p99.9 = %f, p99.99 = %f", - metrics.latencyP50, metrics.latencyP90, metrics.latencyP95, - metrics.latencyP99, metrics.latencyP999, metrics.latencyP9999); + metrics.latencyP50, + metrics.latencyP90, + metrics.latencyP95, + metrics.latencyP99, + metrics.latencyP999, + metrics.latencyP9999 + ); int lineLength = Math.max(serviceTimes.length(), latencies.length()); diff --git a/client/benchmark/src/main/java/org/opensearch/client/benchmark/metrics/Metrics.java b/client/benchmark/src/main/java/org/opensearch/client/benchmark/metrics/Metrics.java index 31c3e298abe..93bf01d1264 100644 --- a/client/benchmark/src/main/java/org/opensearch/client/benchmark/metrics/Metrics.java +++ b/client/benchmark/src/main/java/org/opensearch/client/benchmark/metrics/Metrics.java @@ -49,10 +49,24 @@ public final class Metrics { public final double latencyP999; public final double latencyP9999; - public Metrics(String operation, long successCount, long errorCount, double throughput, - double serviceTimeP50, double serviceTimeP90, double serviceTimeP95, double serviceTimeP99, - double serviceTimeP999, double serviceTimeP9999, double latencyP50, double latencyP90, - double latencyP95, double latencyP99, double latencyP999, double latencyP9999) { + public Metrics( + String operation, + long successCount, + long errorCount, + double throughput, + double serviceTimeP50, + double serviceTimeP90, + double serviceTimeP95, + double serviceTimeP99, + double serviceTimeP999, + double serviceTimeP9999, + double latencyP50, + double latencyP90, + double latencyP95, + double latencyP99, + double latencyP999, + double latencyP9999 + ) { this.operation = operation; this.successCount = successCount; this.errorCount = errorCount; diff --git a/client/benchmark/src/main/java/org/opensearch/client/benchmark/metrics/MetricsCalculator.java b/client/benchmark/src/main/java/org/opensearch/client/benchmark/metrics/MetricsCalculator.java index 80cd62298bb..b64ea8143d7 100644 --- a/client/benchmark/src/main/java/org/opensearch/client/benchmark/metrics/MetricsCalculator.java +++ b/client/benchmark/src/main/java/org/opensearch/client/benchmark/metrics/MetricsCalculator.java @@ -75,24 +75,28 @@ public final class MetricsCalculator { it++; } - metrics.add(new Metrics(operationAndMetrics.getKey(), - samples.stream().filter((r) -> r.isSuccess()).count(), - samples.stream().filter((r) -> !r.isSuccess()).count(), - // throughput calculation is based on the total (Wall clock) time it took to generate all samples - calculateThroughput(samples.size(), latestEnd - firstStart), - // convert ns -> ms without losing precision - StatUtils.percentile(serviceTimes, 50.0d) / TimeUnit.MILLISECONDS.toNanos(1L), - StatUtils.percentile(serviceTimes, 90.0d) / TimeUnit.MILLISECONDS.toNanos(1L), - StatUtils.percentile(serviceTimes, 95.0d) / TimeUnit.MILLISECONDS.toNanos(1L), - StatUtils.percentile(serviceTimes, 99.0d) / TimeUnit.MILLISECONDS.toNanos(1L), - StatUtils.percentile(serviceTimes, 99.9d) / TimeUnit.MILLISECONDS.toNanos(1L), - StatUtils.percentile(serviceTimes, 99.99d) / TimeUnit.MILLISECONDS.toNanos(1L), - StatUtils.percentile(latencies, 50.0d) / TimeUnit.MILLISECONDS.toNanos(1L), - StatUtils.percentile(latencies, 90.0d) / TimeUnit.MILLISECONDS.toNanos(1L), - StatUtils.percentile(latencies, 95.0d) / TimeUnit.MILLISECONDS.toNanos(1L), - StatUtils.percentile(latencies, 99.0d) / TimeUnit.MILLISECONDS.toNanos(1L), - StatUtils.percentile(latencies, 99.9d) / TimeUnit.MILLISECONDS.toNanos(1L), - StatUtils.percentile(latencies, 99.99d) / TimeUnit.MILLISECONDS.toNanos(1L))); + metrics.add( + new Metrics( + operationAndMetrics.getKey(), + samples.stream().filter((r) -> r.isSuccess()).count(), + samples.stream().filter((r) -> !r.isSuccess()).count(), + // throughput calculation is based on the total (Wall clock) time it took to generate all samples + calculateThroughput(samples.size(), latestEnd - firstStart), + // convert ns -> ms without losing precision + StatUtils.percentile(serviceTimes, 50.0d) / TimeUnit.MILLISECONDS.toNanos(1L), + StatUtils.percentile(serviceTimes, 90.0d) / TimeUnit.MILLISECONDS.toNanos(1L), + StatUtils.percentile(serviceTimes, 95.0d) / TimeUnit.MILLISECONDS.toNanos(1L), + StatUtils.percentile(serviceTimes, 99.0d) / TimeUnit.MILLISECONDS.toNanos(1L), + StatUtils.percentile(serviceTimes, 99.9d) / TimeUnit.MILLISECONDS.toNanos(1L), + StatUtils.percentile(serviceTimes, 99.99d) / TimeUnit.MILLISECONDS.toNanos(1L), + StatUtils.percentile(latencies, 50.0d) / TimeUnit.MILLISECONDS.toNanos(1L), + StatUtils.percentile(latencies, 90.0d) / TimeUnit.MILLISECONDS.toNanos(1L), + StatUtils.percentile(latencies, 95.0d) / TimeUnit.MILLISECONDS.toNanos(1L), + StatUtils.percentile(latencies, 99.0d) / TimeUnit.MILLISECONDS.toNanos(1L), + StatUtils.percentile(latencies, 99.9d) / TimeUnit.MILLISECONDS.toNanos(1L), + StatUtils.percentile(latencies, 99.99d) / TimeUnit.MILLISECONDS.toNanos(1L) + ) + ); } return metrics; } diff --git a/client/benchmark/src/main/java/org/opensearch/client/benchmark/ops/bulk/BulkBenchmarkTask.java b/client/benchmark/src/main/java/org/opensearch/client/benchmark/ops/bulk/BulkBenchmarkTask.java index 56b59c6f6e8..459cba1ce5f 100644 --- a/client/benchmark/src/main/java/org/opensearch/client/benchmark/ops/bulk/BulkBenchmarkTask.java +++ b/client/benchmark/src/main/java/org/opensearch/client/benchmark/ops/bulk/BulkBenchmarkTask.java @@ -62,8 +62,13 @@ public class BulkBenchmarkTask implements BenchmarkTask { private LoadGenerator generator; private ExecutorService executorService; - public BulkBenchmarkTask(BulkRequestExecutor requestExecutor, String indexFilePath, int warmupIterations, int measurementIterations, - int bulkSize) { + public BulkBenchmarkTask( + BulkRequestExecutor requestExecutor, + String indexFilePath, + int warmupIterations, + int measurementIterations, + int bulkSize + ) { this.requestExecutor = requestExecutor; this.indexFilePath = indexFilePath; this.warmupIterations = warmupIterations; @@ -86,11 +91,11 @@ public class BulkBenchmarkTask implements BenchmarkTask { @Override @SuppressForbidden(reason = "system out is ok for a command line tool") - public void run() throws Exception { + public void run() throws Exception { generator.execute(); // when the generator is done, there are no more data -> shutdown client executorService.shutdown(); - //We need to wait until the queue is drained + // We need to wait until the queue is drained final boolean finishedNormally = executorService.awaitTermination(20, TimeUnit.MINUTES); if (finishedNormally == false) { System.err.println("Background tasks are still running after timeout on enclosing pool. Forcing pool shutdown."); @@ -100,7 +105,7 @@ public class BulkBenchmarkTask implements BenchmarkTask { @Override public void tearDown() { - //no op + // no op } private static final class LoadGenerator { @@ -146,7 +151,6 @@ public class BulkBenchmarkTask implements BenchmarkTask { } } - private static final class BulkIndexer implements Runnable { private static final Logger logger = LogManager.getLogger(BulkIndexer.class); @@ -156,8 +160,13 @@ public class BulkBenchmarkTask implements BenchmarkTask { private final BulkRequestExecutor bulkRequestExecutor; private final SampleRecorder sampleRecorder; - BulkIndexer(BlockingQueue> bulkData, int warmupIterations, int measurementIterations, - SampleRecorder sampleRecorder, BulkRequestExecutor bulkRequestExecutor) { + BulkIndexer( + BlockingQueue> bulkData, + int warmupIterations, + int measurementIterations, + SampleRecorder sampleRecorder, + BulkRequestExecutor bulkRequestExecutor + ) { this.bulkData = bulkData; this.warmupIterations = warmupIterations; this.measurementIterations = measurementIterations; @@ -176,7 +185,7 @@ public class BulkBenchmarkTask implements BenchmarkTask { Thread.currentThread().interrupt(); return; } - //measure only service time, latency is not that interesting for a throughput benchmark + // measure only service time, latency is not that interesting for a throughput benchmark long start = System.nanoTime(); try { success = bulkRequestExecutor.bulkIndex(currentBulk); diff --git a/client/benchmark/src/main/java/org/opensearch/client/benchmark/ops/search/SearchBenchmarkTask.java b/client/benchmark/src/main/java/org/opensearch/client/benchmark/ops/search/SearchBenchmarkTask.java index 4a373149873..3b232cb3bdb 100644 --- a/client/benchmark/src/main/java/org/opensearch/client/benchmark/ops/search/SearchBenchmarkTask.java +++ b/client/benchmark/src/main/java/org/opensearch/client/benchmark/ops/search/SearchBenchmarkTask.java @@ -46,8 +46,13 @@ public class SearchBenchmarkTask implements BenchmarkTask { private SampleRecorder sampleRecorder; - public SearchBenchmarkTask(SearchRequestExecutor searchRequestExecutor, String body, int warmupIterations, - int measurementIterations, int targetThroughput) { + public SearchBenchmarkTask( + SearchRequestExecutor searchRequestExecutor, + String body, + int warmupIterations, + int measurementIterations, + int targetThroughput + ) { this.searchRequestExecutor = searchRequestExecutor; this.searchRequestBody = body; this.warmupIterations = warmupIterations; diff --git a/client/benchmark/src/main/java/org/opensearch/client/benchmark/rest/RestClientBenchmark.java b/client/benchmark/src/main/java/org/opensearch/client/benchmark/rest/RestClientBenchmark.java index 8d44142b0ce..073fd5eab5c 100644 --- a/client/benchmark/src/main/java/org/opensearch/client/benchmark/rest/RestClientBenchmark.java +++ b/client/benchmark/src/main/java/org/opensearch/client/benchmark/rest/RestClientBenchmark.java @@ -56,10 +56,10 @@ public final class RestClientBenchmark extends AbstractBenchmark { @Override protected RestClient client(String benchmarkTargetHost) { - return RestClient - .builder(new HttpHost(benchmarkTargetHost, 9200)) - .setHttpClientConfigCallback(b -> b.setDefaultHeaders( - Collections.singleton(new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "gzip")))) + return RestClient.builder(new HttpHost(benchmarkTargetHost, 9200)) + .setHttpClientConfigCallback( + b -> b.setDefaultHeaders(Collections.singleton(new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "gzip"))) + ) .setRequestConfigCallback(b -> b.setContentCompressionEnabled(true)) .build(); } diff --git a/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/NoopPlugin.java b/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/NoopPlugin.java index 250825379c5..e9d0fff2a9d 100644 --- a/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/NoopPlugin.java +++ b/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/NoopPlugin.java @@ -64,11 +64,15 @@ public class NoopPlugin extends Plugin implements ActionPlugin { } @Override - public List getRestHandlers(Settings settings, RestController restController, ClusterSettings clusterSettings, - IndexScopedSettings indexScopedSettings, SettingsFilter settingsFilter, IndexNameExpressionResolver indexNameExpressionResolver, - Supplier nodesInCluster) { - return Arrays.asList( - new RestNoopBulkAction(), - new RestNoopSearchAction()); + public List getRestHandlers( + Settings settings, + RestController restController, + ClusterSettings clusterSettings, + IndexScopedSettings indexScopedSettings, + SettingsFilter settingsFilter, + IndexNameExpressionResolver indexNameExpressionResolver, + Supplier nodesInCluster + ) { + return Arrays.asList(new RestNoopBulkAction(), new RestNoopSearchAction()); } } diff --git a/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/action/bulk/RestNoopBulkAction.java b/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/action/bulk/RestNoopBulkAction.java index 81eb77bfd44..8f42744aeb5 100644 --- a/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/action/bulk/RestNoopBulkAction.java +++ b/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/action/bulk/RestNoopBulkAction.java @@ -62,13 +62,16 @@ public class RestNoopBulkAction extends BaseRestHandler { @Override public List routes() { - return unmodifiableList(asList( - new Route(POST, "/_noop_bulk"), - new Route(PUT, "/_noop_bulk"), - new Route(POST, "/{index}/_noop_bulk"), - new Route(PUT, "/{index}/_noop_bulk"), - new Route(POST, "/{index}/{type}/_noop_bulk"), - new Route(PUT, "/{index}/{type}/_noop_bulk"))); + return unmodifiableList( + asList( + new Route(POST, "/_noop_bulk"), + new Route(PUT, "/_noop_bulk"), + new Route(POST, "/{index}/_noop_bulk"), + new Route(PUT, "/{index}/_noop_bulk"), + new Route(POST, "/{index}/{type}/_noop_bulk"), + new Route(PUT, "/{index}/{type}/_noop_bulk") + ) + ); } @Override @@ -91,8 +94,17 @@ public class RestNoopBulkAction extends BaseRestHandler { } bulkRequest.timeout(request.paramAsTime("timeout", BulkShardRequest.DEFAULT_TIMEOUT)); bulkRequest.setRefreshPolicy(request.param("refresh")); - bulkRequest.add(request.requiredContent(), defaultIndex, defaultType, defaultRouting, - null, defaultPipeline, defaultRequireAlias, true, request.getXContentType()); + bulkRequest.add( + request.requiredContent(), + defaultIndex, + defaultType, + defaultRouting, + null, + defaultPipeline, + defaultRequireAlias, + true, + request.getXContentType() + ); // short circuit the call to the transport layer return channel -> { @@ -102,12 +114,14 @@ public class RestNoopBulkAction extends BaseRestHandler { } private static class BulkRestBuilderListener extends RestBuilderListener { - private final BulkItemResponse ITEM_RESPONSE = new BulkItemResponse(1, DocWriteRequest.OpType.UPDATE, - new UpdateResponse(new ShardId("mock", "", 1), "mock_type", "1", 0L, 1L, 1L, DocWriteResponse.Result.CREATED)); + private final BulkItemResponse ITEM_RESPONSE = new BulkItemResponse( + 1, + DocWriteRequest.OpType.UPDATE, + new UpdateResponse(new ShardId("mock", "", 1), "mock_type", "1", 0L, 1L, 1L, DocWriteResponse.Result.CREATED) + ); private final RestRequest request; - BulkRestBuilderListener(RestChannel channel, RestRequest request) { super(channel); this.request = request; diff --git a/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/action/bulk/TransportNoopBulkAction.java b/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/action/bulk/TransportNoopBulkAction.java index 3b3743a2281..53fa96b592e 100644 --- a/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/action/bulk/TransportNoopBulkAction.java +++ b/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/action/bulk/TransportNoopBulkAction.java @@ -46,8 +46,11 @@ import org.opensearch.tasks.Task; import org.opensearch.transport.TransportService; public class TransportNoopBulkAction extends HandledTransportAction { - private static final BulkItemResponse ITEM_RESPONSE = new BulkItemResponse(1, DocWriteRequest.OpType.UPDATE, - new UpdateResponse(new ShardId("mock", "", 1), "mock_type", "1", 0L, 1L, 1L, DocWriteResponse.Result.CREATED)); + private static final BulkItemResponse ITEM_RESPONSE = new BulkItemResponse( + 1, + DocWriteRequest.OpType.UPDATE, + new UpdateResponse(new ShardId("mock", "", 1), "mock_type", "1", 0L, 1L, 1L, DocWriteResponse.Result.CREATED) + ); @Inject public TransportNoopBulkAction(TransportService transportService, ActionFilters actionFilters) { diff --git a/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/action/search/RestNoopSearchAction.java b/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/action/search/RestNoopSearchAction.java index 12ad7f3f254..3f7be044653 100644 --- a/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/action/search/RestNoopSearchAction.java +++ b/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/action/search/RestNoopSearchAction.java @@ -48,13 +48,16 @@ public class RestNoopSearchAction extends BaseRestHandler { @Override public List routes() { - return unmodifiableList(asList( - new Route(GET, "/_noop_search"), - new Route(POST, "/_noop_search"), - new Route(GET, "/{index}/_noop_search"), - new Route(POST, "/{index}/_noop_search"), - new Route(GET, "/{index}/{type}/_noop_search"), - new Route(POST, "/{index}/{type}/_noop_search"))); + return unmodifiableList( + asList( + new Route(GET, "/_noop_search"), + new Route(POST, "/_noop_search"), + new Route(GET, "/{index}/_noop_search"), + new Route(POST, "/{index}/_noop_search"), + new Route(GET, "/{index}/{type}/_noop_search"), + new Route(POST, "/{index}/{type}/_noop_search") + ) + ); } @Override diff --git a/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/action/search/TransportNoopSearchAction.java b/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/action/search/TransportNoopSearchAction.java index 557aaa4d5e2..77668a030ee 100644 --- a/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/action/search/TransportNoopSearchAction.java +++ b/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/action/search/TransportNoopSearchAction.java @@ -59,12 +59,25 @@ public class TransportNoopSearchAction extends HandledTransportAction listener) { - listener.onResponse(new SearchResponse(new InternalSearchResponse( - new SearchHits( - new SearchHit[0], new TotalHits(0L, TotalHits.Relation.EQUAL_TO), 0.0f), - InternalAggregations.EMPTY, - new Suggest(Collections.emptyList()), - new SearchProfileShardResults(Collections.emptyMap()), false, false, 1), - "", 1, 1, 0, 0, ShardSearchFailure.EMPTY_ARRAY, SearchResponse.Clusters.EMPTY)); + listener.onResponse( + new SearchResponse( + new InternalSearchResponse( + new SearchHits(new SearchHit[0], new TotalHits(0L, TotalHits.Relation.EQUAL_TO), 0.0f), + InternalAggregations.EMPTY, + new Suggest(Collections.emptyList()), + new SearchProfileShardResults(Collections.emptyMap()), + false, + false, + 1 + ), + "", + 1, + 1, + 0, + 0, + ShardSearchFailure.EMPTY_ARRAY, + SearchResponse.Clusters.EMPTY + ) + ); } } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/ClusterClient.java b/client/rest-high-level/src/main/java/org/opensearch/client/ClusterClient.java index 6c79e0145da..10cfec94978 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/ClusterClient.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/ClusterClient.java @@ -73,9 +73,14 @@ public final class ClusterClient { * @throws IOException in case there is a problem sending the request or parsing back the response */ public ClusterUpdateSettingsResponse putSettings(ClusterUpdateSettingsRequest clusterUpdateSettingsRequest, RequestOptions options) - throws IOException { - return restHighLevelClient.performRequestAndParseEntity(clusterUpdateSettingsRequest, ClusterRequestConverters::clusterPutSettings, - options, ClusterUpdateSettingsResponse::fromXContent, emptySet()); + throws IOException { + return restHighLevelClient.performRequestAndParseEntity( + clusterUpdateSettingsRequest, + ClusterRequestConverters::clusterPutSettings, + options, + ClusterUpdateSettingsResponse::fromXContent, + emptySet() + ); } /** @@ -86,11 +91,19 @@ public final class ClusterClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable putSettingsAsync(ClusterUpdateSettingsRequest clusterUpdateSettingsRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(clusterUpdateSettingsRequest, - ClusterRequestConverters::clusterPutSettings, - options, ClusterUpdateSettingsResponse::fromXContent, listener, emptySet()); + public Cancellable putSettingsAsync( + ClusterUpdateSettingsRequest clusterUpdateSettingsRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + clusterUpdateSettingsRequest, + ClusterRequestConverters::clusterPutSettings, + options, + ClusterUpdateSettingsResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -103,8 +116,13 @@ public final class ClusterClient { */ public ClusterGetSettingsResponse getSettings(ClusterGetSettingsRequest clusterGetSettingsRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(clusterGetSettingsRequest, ClusterRequestConverters::clusterGetSettings, - options, ClusterGetSettingsResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + clusterGetSettingsRequest, + ClusterRequestConverters::clusterGetSettings, + options, + ClusterGetSettingsResponse::fromXContent, + emptySet() + ); } /** @@ -115,11 +133,19 @@ public final class ClusterClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable getSettingsAsync(ClusterGetSettingsRequest clusterGetSettingsRequest, RequestOptions options, - ActionListener listener) { + public Cancellable getSettingsAsync( + ClusterGetSettingsRequest clusterGetSettingsRequest, + RequestOptions options, + ActionListener listener + ) { return restHighLevelClient.performRequestAsyncAndParseEntity( - clusterGetSettingsRequest, ClusterRequestConverters::clusterGetSettings, - options, ClusterGetSettingsResponse::fromXContent, listener, emptySet()); + clusterGetSettingsRequest, + ClusterRequestConverters::clusterGetSettings, + options, + ClusterGetSettingsResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -133,8 +159,13 @@ public final class ClusterClient { * @throws IOException in case there is a problem sending the request or parsing back the response */ public ClusterHealthResponse health(ClusterHealthRequest healthRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(healthRequest, ClusterRequestConverters::clusterHealth, options, - ClusterHealthResponse::fromXContent, singleton(RestStatus.REQUEST_TIMEOUT.getStatus())); + return restHighLevelClient.performRequestAndParseEntity( + healthRequest, + ClusterRequestConverters::clusterHealth, + options, + ClusterHealthResponse::fromXContent, + singleton(RestStatus.REQUEST_TIMEOUT.getStatus()) + ); } /** @@ -146,10 +177,19 @@ public final class ClusterClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable healthAsync(ClusterHealthRequest healthRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(healthRequest, ClusterRequestConverters::clusterHealth, options, - ClusterHealthResponse::fromXContent, listener, singleton(RestStatus.REQUEST_TIMEOUT.getStatus())); + public Cancellable healthAsync( + ClusterHealthRequest healthRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + healthRequest, + ClusterRequestConverters::clusterHealth, + options, + ClusterHealthResponse::fromXContent, + listener, + singleton(RestStatus.REQUEST_TIMEOUT.getStatus()) + ); } /** @@ -161,8 +201,13 @@ public final class ClusterClient { * @throws IOException in case there is a problem sending the request or parsing back the response */ public RemoteInfoResponse remoteInfo(RemoteInfoRequest request, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(request, ClusterRequestConverters::remoteInfo, options, - RemoteInfoResponse::fromXContent, singleton(RestStatus.REQUEST_TIMEOUT.getStatus())); + return restHighLevelClient.performRequestAndParseEntity( + request, + ClusterRequestConverters::remoteInfo, + options, + RemoteInfoResponse::fromXContent, + singleton(RestStatus.REQUEST_TIMEOUT.getStatus()) + ); } /** @@ -173,10 +218,15 @@ public final class ClusterClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable remoteInfoAsync(RemoteInfoRequest request, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(request, ClusterRequestConverters::remoteInfo, options, - RemoteInfoResponse::fromXContent, listener, singleton(RestStatus.REQUEST_TIMEOUT.getStatus())); + public Cancellable remoteInfoAsync(RemoteInfoRequest request, RequestOptions options, ActionListener listener) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + request, + ClusterRequestConverters::remoteInfo, + options, + RemoteInfoResponse::fromXContent, + listener, + singleton(RestStatus.REQUEST_TIMEOUT.getStatus()) + ); } /** @@ -187,8 +237,13 @@ public final class ClusterClient { * @throws IOException in case there is a problem sending the request or parsing back the response */ public AcknowledgedResponse deleteComponentTemplate(DeleteComponentTemplateRequest req, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(req, ClusterRequestConverters::deleteComponentTemplate, - options, AcknowledgedResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + req, + ClusterRequestConverters::deleteComponentTemplate, + options, + AcknowledgedResponse::fromXContent, + emptySet() + ); } /** @@ -199,10 +254,19 @@ public final class ClusterClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable deleteComponentTemplateAsync(DeleteComponentTemplateRequest request, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(request, ClusterRequestConverters::deleteComponentTemplate, - options, AcknowledgedResponse::fromXContent, listener, emptySet()); + public Cancellable deleteComponentTemplateAsync( + DeleteComponentTemplateRequest request, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + request, + ClusterRequestConverters::deleteComponentTemplate, + options, + AcknowledgedResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -213,10 +277,15 @@ public final class ClusterClient { * @return the response * @throws IOException in case there is a problem sending the request or parsing back the response */ - public AcknowledgedResponse putComponentTemplate(PutComponentTemplateRequest putComponentTemplateRequest, - RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(putComponentTemplateRequest, ClusterRequestConverters::putComponentTemplate, - options, AcknowledgedResponse::fromXContent, emptySet()); + public AcknowledgedResponse putComponentTemplate(PutComponentTemplateRequest putComponentTemplateRequest, RequestOptions options) + throws IOException { + return restHighLevelClient.performRequestAndParseEntity( + putComponentTemplateRequest, + ClusterRequestConverters::putComponentTemplate, + options, + AcknowledgedResponse::fromXContent, + emptySet() + ); } /** @@ -227,10 +296,19 @@ public final class ClusterClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable putComponentTemplateAsync(PutComponentTemplateRequest putComponentTemplateRequest, - RequestOptions options, ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(putComponentTemplateRequest, - ClusterRequestConverters::putComponentTemplate, options, AcknowledgedResponse::fromXContent, listener, emptySet()); + public Cancellable putComponentTemplateAsync( + PutComponentTemplateRequest putComponentTemplateRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + putComponentTemplateRequest, + ClusterRequestConverters::putComponentTemplate, + options, + AcknowledgedResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -240,10 +318,17 @@ public final class ClusterClient { * @return the response * @throws IOException in case there is a problem sending the request or parsing back the response */ - public GetComponentTemplatesResponse getComponentTemplate(GetComponentTemplatesRequest getComponentTemplatesRequest, - RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(getComponentTemplatesRequest, - ClusterRequestConverters::getComponentTemplates, options, GetComponentTemplatesResponse::fromXContent, emptySet()); + public GetComponentTemplatesResponse getComponentTemplate( + GetComponentTemplatesRequest getComponentTemplatesRequest, + RequestOptions options + ) throws IOException { + return restHighLevelClient.performRequestAndParseEntity( + getComponentTemplatesRequest, + ClusterRequestConverters::getComponentTemplates, + options, + GetComponentTemplatesResponse::fromXContent, + emptySet() + ); } /** @@ -253,10 +338,19 @@ public final class ClusterClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable getComponentTemplateAsync(GetComponentTemplatesRequest getComponentTemplatesRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(getComponentTemplatesRequest, - ClusterRequestConverters::getComponentTemplates, options, GetComponentTemplatesResponse::fromXContent, listener, emptySet()); + public Cancellable getComponentTemplateAsync( + GetComponentTemplatesRequest getComponentTemplatesRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + getComponentTemplatesRequest, + ClusterRequestConverters::getComponentTemplates, + options, + GetComponentTemplatesResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -267,10 +361,15 @@ public final class ClusterClient { * @return true if any index templates in the request exist, false otherwise * @throws IOException in case there is a problem sending the request or parsing back the response */ - public boolean existsComponentTemplate(ComponentTemplatesExistRequest componentTemplatesRequest, - RequestOptions options) throws IOException { - return restHighLevelClient.performRequest(componentTemplatesRequest, - ClusterRequestConverters::componentTemplatesExist, options, RestHighLevelClient::convertExistsResponse, emptySet()); + public boolean existsComponentTemplate(ComponentTemplatesExistRequest componentTemplatesRequest, RequestOptions options) + throws IOException { + return restHighLevelClient.performRequest( + componentTemplatesRequest, + ClusterRequestConverters::componentTemplatesExist, + options, + RestHighLevelClient::convertExistsResponse, + emptySet() + ); } /** @@ -280,11 +379,19 @@ public final class ClusterClient { * @param listener the listener to be notified upon request completion. The listener will be called with the value {@code true} * @return cancellable that may be used to cancel the request */ - public Cancellable existsComponentTemplateAsync(ComponentTemplatesExistRequest componentTemplatesRequest, - RequestOptions options, - ActionListener listener) { + public Cancellable existsComponentTemplateAsync( + ComponentTemplatesExistRequest componentTemplatesRequest, + RequestOptions options, + ActionListener listener + ) { - return restHighLevelClient.performRequestAsync(componentTemplatesRequest, - ClusterRequestConverters::componentTemplatesExist, options, RestHighLevelClient::convertExistsResponse, listener, emptySet()); + return restHighLevelClient.performRequestAsync( + componentTemplatesRequest, + ClusterRequestConverters::componentTemplatesExist, + options, + RestHighLevelClient::convertExistsResponse, + listener, + emptySet() + ); } } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/ClusterRequestConverters.java b/client/rest-high-level/src/main/java/org/opensearch/client/ClusterRequestConverters.java index d593f1c5325..1cf52ac4169 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/ClusterRequestConverters.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/ClusterRequestConverters.java @@ -76,14 +76,12 @@ final class ClusterRequestConverters { static Request clusterHealth(ClusterHealthRequest healthRequest) { String[] indices = healthRequest.indices() == null ? Strings.EMPTY_ARRAY : healthRequest.indices(); - String endpoint = new RequestConverters.EndpointBuilder() - .addPathPartAsIs("_cluster/health") + String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_cluster/health") .addCommaSeparatedPathParts(indices) .build(); Request request = new Request(HttpGet.METHOD_NAME, endpoint); - RequestConverters.Params params = new RequestConverters.Params() - .withWaitForStatus(healthRequest.waitForStatus()) + RequestConverters.Params params = new RequestConverters.Params().withWaitForStatus(healthRequest.waitForStatus()) .withWaitForNoRelocatingShards(healthRequest.waitForNoRelocatingShards()) .withWaitForNoInitializingShards(healthRequest.waitForNoInitializingShards()) .withWaitForActiveShards(healthRequest.waitForActiveShards(), ActiveShardCount.NONE) @@ -103,7 +101,8 @@ final class ClusterRequestConverters { static Request putComponentTemplate(PutComponentTemplateRequest putComponentTemplateRequest) throws IOException { String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_component_template") - .addPathPart(putComponentTemplateRequest.name()).build(); + .addPathPart(putComponentTemplateRequest.name()) + .build(); Request request = new Request(HttpPut.METHOD_NAME, endpoint); RequestConverters.Params params = new RequestConverters.Params(); params.withMasterTimeout(putComponentTemplateRequest.masterNodeTimeout()); @@ -118,9 +117,8 @@ final class ClusterRequestConverters { return request; } - static Request getComponentTemplates(GetComponentTemplatesRequest getComponentTemplatesRequest){ - final String endpoint = new RequestConverters.EndpointBuilder() - .addPathPartAsIs("_component_template") + static Request getComponentTemplates(GetComponentTemplatesRequest getComponentTemplatesRequest) { + final String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_component_template") .addPathPart(getComponentTemplatesRequest.name()) .build(); final Request request = new Request(HttpGet.METHOD_NAME, endpoint); @@ -132,8 +130,7 @@ final class ClusterRequestConverters { } static Request componentTemplatesExist(ComponentTemplatesExistRequest componentTemplatesRequest) { - final String endpoint = new RequestConverters.EndpointBuilder() - .addPathPartAsIs("_component_template") + final String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_component_template") .addPathPart(componentTemplatesRequest.name()) .build(); final Request request = new Request(HttpHead.METHOD_NAME, endpoint); diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/IndicesClient.java b/client/rest-high-level/src/main/java/org/opensearch/client/IndicesClient.java index f497dbfd76d..dcff976106b 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/IndicesClient.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/IndicesClient.java @@ -32,8 +32,6 @@ package org.opensearch.client; -import org.opensearch.client.Cancellable; -import org.opensearch.client.RequestOptions; import org.opensearch.action.ActionListener; import org.opensearch.action.admin.indices.alias.IndicesAliasesRequest; import org.opensearch.action.admin.indices.alias.get.GetAliasesRequest; @@ -118,8 +116,13 @@ public final class IndicesClient { * @throws IOException in case there is a problem sending the request or parsing back the response */ public AcknowledgedResponse delete(DeleteIndexRequest deleteIndexRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(deleteIndexRequest, IndicesRequestConverters::deleteIndex, options, - AcknowledgedResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + deleteIndexRequest, + IndicesRequestConverters::deleteIndex, + options, + AcknowledgedResponse::fromXContent, + emptySet() + ); } /** @@ -130,11 +133,19 @@ public final class IndicesClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable deleteAsync(DeleteIndexRequest deleteIndexRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(deleteIndexRequest, - IndicesRequestConverters::deleteIndex, options, - AcknowledgedResponse::fromXContent, listener, emptySet()); + public Cancellable deleteAsync( + DeleteIndexRequest deleteIndexRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + deleteIndexRequest, + IndicesRequestConverters::deleteIndex, + options, + AcknowledgedResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -145,10 +156,14 @@ public final class IndicesClient { * @return the response * @throws IOException in case there is a problem sending the request or parsing back the response */ - public CreateIndexResponse create(CreateIndexRequest createIndexRequest, - RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(createIndexRequest, IndicesRequestConverters::createIndex, options, - CreateIndexResponse::fromXContent, emptySet()); + public CreateIndexResponse create(CreateIndexRequest createIndexRequest, RequestOptions options) throws IOException { + return restHighLevelClient.performRequestAndParseEntity( + createIndexRequest, + IndicesRequestConverters::createIndex, + options, + CreateIndexResponse::fromXContent, + emptySet() + ); } /** @@ -159,11 +174,19 @@ public final class IndicesClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable createAsync(CreateIndexRequest createIndexRequest, - RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(createIndexRequest, IndicesRequestConverters::createIndex, options, - CreateIndexResponse::fromXContent, listener, emptySet()); + public Cancellable createAsync( + CreateIndexRequest createIndexRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + createIndexRequest, + IndicesRequestConverters::createIndex, + options, + CreateIndexResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -175,10 +198,15 @@ public final class IndicesClient { * @return the response * @throws IOException in case there is a problem sending the request or parsing back the response */ - public AcknowledgedResponse createDataStream(CreateDataStreamRequest createDataStreamRequest, - RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(createDataStreamRequest, IndicesRequestConverters::putDataStream, options, - AcknowledgedResponse::fromXContent, emptySet()); + public AcknowledgedResponse createDataStream(CreateDataStreamRequest createDataStreamRequest, RequestOptions options) + throws IOException { + return restHighLevelClient.performRequestAndParseEntity( + createDataStreamRequest, + IndicesRequestConverters::putDataStream, + options, + AcknowledgedResponse::fromXContent, + emptySet() + ); } /** @@ -190,11 +218,19 @@ public final class IndicesClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable createDataStreamAsync(CreateDataStreamRequest createDataStreamRequest, - RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(createDataStreamRequest, IndicesRequestConverters::putDataStream, - options, AcknowledgedResponse::fromXContent, listener, emptySet()); + public Cancellable createDataStreamAsync( + CreateDataStreamRequest createDataStreamRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + createDataStreamRequest, + IndicesRequestConverters::putDataStream, + options, + AcknowledgedResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -206,10 +242,15 @@ public final class IndicesClient { * @return the response * @throws IOException in case there is a problem sending the request or parsing back the response */ - public AcknowledgedResponse deleteDataStream(DeleteDataStreamRequest deleteDataStreamRequest, - RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(deleteDataStreamRequest, IndicesRequestConverters::deleteDataStream, - options, AcknowledgedResponse::fromXContent, emptySet()); + public AcknowledgedResponse deleteDataStream(DeleteDataStreamRequest deleteDataStreamRequest, RequestOptions options) + throws IOException { + return restHighLevelClient.performRequestAndParseEntity( + deleteDataStreamRequest, + IndicesRequestConverters::deleteDataStream, + options, + AcknowledgedResponse::fromXContent, + emptySet() + ); } /** @@ -221,10 +262,19 @@ public final class IndicesClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable deleteDataStreamAsync(DeleteDataStreamRequest deleteDataStreamRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(deleteDataStreamRequest, IndicesRequestConverters::deleteDataStream, - options, AcknowledgedResponse::fromXContent, listener, emptySet()); + public Cancellable deleteDataStreamAsync( + DeleteDataStreamRequest deleteDataStreamRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + deleteDataStreamRequest, + IndicesRequestConverters::deleteDataStream, + options, + AcknowledgedResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -236,8 +286,13 @@ public final class IndicesClient { * @throws IOException in case there is a problem sending the request or parsing back the response */ public GetDataStreamResponse getDataStream(GetDataStreamRequest dataStreamRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(dataStreamRequest, IndicesRequestConverters::getDataStreams, options, - GetDataStreamResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + dataStreamRequest, + IndicesRequestConverters::getDataStreams, + options, + GetDataStreamResponse::fromXContent, + emptySet() + ); } /** @@ -248,10 +303,19 @@ public final class IndicesClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable getDataStreamAsync(GetDataStreamRequest dataStreamRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(dataStreamRequest, IndicesRequestConverters::getDataStreams, options, - GetDataStreamResponse::fromXContent, listener, emptySet()); + public Cancellable getDataStreamAsync( + GetDataStreamRequest dataStreamRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + dataStreamRequest, + IndicesRequestConverters::getDataStreams, + options, + GetDataStreamResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -265,8 +329,13 @@ public final class IndicesClient { */ public DataStreamsStatsResponse dataStreamsStats(DataStreamsStatsRequest dataStreamsStatsRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(dataStreamsStatsRequest, IndicesRequestConverters::dataStreamsStats, - options, DataStreamsStatsResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + dataStreamsStatsRequest, + IndicesRequestConverters::dataStreamsStats, + options, + DataStreamsStatsResponse::fromXContent, + emptySet() + ); } /** @@ -278,10 +347,19 @@ public final class IndicesClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable dataStreamsStatsAsync(DataStreamsStatsRequest dataStreamsStatsRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(dataStreamsStatsRequest, IndicesRequestConverters::dataStreamsStats, - options, DataStreamsStatsResponse::fromXContent, listener, emptySet()); + public Cancellable dataStreamsStatsAsync( + DataStreamsStatsRequest dataStreamsStatsRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + dataStreamsStatsRequest, + IndicesRequestConverters::dataStreamsStats, + options, + DataStreamsStatsResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -298,11 +376,16 @@ public final class IndicesClient { */ @Deprecated public org.opensearch.action.admin.indices.create.CreateIndexResponse create( - org.opensearch.action.admin.indices.create.CreateIndexRequest createIndexRequest, - RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(createIndexRequest, - IndicesRequestConverters::createIndex, options, - org.opensearch.action.admin.indices.create.CreateIndexResponse::fromXContent, emptySet()); + org.opensearch.action.admin.indices.create.CreateIndexRequest createIndexRequest, + RequestOptions options + ) throws IOException { + return restHighLevelClient.performRequestAndParseEntity( + createIndexRequest, + IndicesRequestConverters::createIndex, + options, + org.opensearch.action.admin.indices.create.CreateIndexResponse::fromXContent, + emptySet() + ); } /** @@ -318,12 +401,19 @@ public final class IndicesClient { * @return cancellable that may be used to cancel the request */ @Deprecated - public Cancellable createAsync(org.opensearch.action.admin.indices.create.CreateIndexRequest createIndexRequest, - RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(createIndexRequest, - IndicesRequestConverters::createIndex, options, - org.opensearch.action.admin.indices.create.CreateIndexResponse::fromXContent, listener, emptySet()); + public Cancellable createAsync( + org.opensearch.action.admin.indices.create.CreateIndexRequest createIndexRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + createIndexRequest, + IndicesRequestConverters::createIndex, + options, + org.opensearch.action.admin.indices.create.CreateIndexResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -335,8 +425,13 @@ public final class IndicesClient { * @throws IOException in case there is a problem sending the request or parsing back the response */ public AcknowledgedResponse putMapping(PutMappingRequest putMappingRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(putMappingRequest, IndicesRequestConverters::putMapping, options, - AcknowledgedResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + putMappingRequest, + IndicesRequestConverters::putMapping, + options, + AcknowledgedResponse::fromXContent, + emptySet() + ); } /** @@ -347,10 +442,19 @@ public final class IndicesClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable putMappingAsync(PutMappingRequest putMappingRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(putMappingRequest, IndicesRequestConverters::putMapping, options, - AcknowledgedResponse::fromXContent, listener, emptySet()); + public Cancellable putMappingAsync( + PutMappingRequest putMappingRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + putMappingRequest, + IndicesRequestConverters::putMapping, + options, + AcknowledgedResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -365,10 +469,17 @@ public final class IndicesClient { * {@link #putMapping(PutMappingRequest, RequestOptions)} should be used instead, which accepts a new request object. */ @Deprecated - public AcknowledgedResponse putMapping(org.opensearch.action.admin.indices.mapping.put.PutMappingRequest putMappingRequest, - RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(putMappingRequest, IndicesRequestConverters::putMapping, options, - AcknowledgedResponse::fromXContent, emptySet()); + public AcknowledgedResponse putMapping( + org.opensearch.action.admin.indices.mapping.put.PutMappingRequest putMappingRequest, + RequestOptions options + ) throws IOException { + return restHighLevelClient.performRequestAndParseEntity( + putMappingRequest, + IndicesRequestConverters::putMapping, + options, + AcknowledgedResponse::fromXContent, + emptySet() + ); } /** @@ -384,11 +495,19 @@ public final class IndicesClient { * @return cancellable that may be used to cancel the request */ @Deprecated - public Cancellable putMappingAsync(org.opensearch.action.admin.indices.mapping.put.PutMappingRequest putMappingRequest, - RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(putMappingRequest, IndicesRequestConverters::putMapping, options, - AcknowledgedResponse::fromXContent, listener, emptySet()); + public Cancellable putMappingAsync( + org.opensearch.action.admin.indices.mapping.put.PutMappingRequest putMappingRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + putMappingRequest, + IndicesRequestConverters::putMapping, + options, + AcknowledgedResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -400,11 +519,13 @@ public final class IndicesClient { * @throws IOException in case there is a problem sending the request or parsing back the response */ public GetMappingsResponse getMapping(GetMappingsRequest getMappingsRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(getMappingsRequest, + return restHighLevelClient.performRequestAndParseEntity( + getMappingsRequest, IndicesRequestConverters::getMappings, options, GetMappingsResponse::fromXContent, - emptySet()); + emptySet() + ); } /** @@ -415,14 +536,19 @@ public final class IndicesClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable getMappingAsync(GetMappingsRequest getMappingsRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(getMappingsRequest, + public Cancellable getMappingAsync( + GetMappingsRequest getMappingsRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + getMappingsRequest, IndicesRequestConverters::getMappings, options, GetMappingsResponse::fromXContent, listener, - emptySet()); + emptySet() + ); } /** @@ -439,13 +565,16 @@ public final class IndicesClient { */ @Deprecated public org.opensearch.action.admin.indices.mapping.get.GetMappingsResponse getMapping( - org.opensearch.action.admin.indices.mapping.get.GetMappingsRequest getMappingsRequest, - RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(getMappingsRequest, + org.opensearch.action.admin.indices.mapping.get.GetMappingsRequest getMappingsRequest, + RequestOptions options + ) throws IOException { + return restHighLevelClient.performRequestAndParseEntity( + getMappingsRequest, IndicesRequestConverters::getMappings, options, org.opensearch.action.admin.indices.mapping.get.GetMappingsResponse::fromXContent, - emptySet()); + emptySet() + ); } /** @@ -461,15 +590,19 @@ public final class IndicesClient { * @return cancellable that may be used to cancel the request */ @Deprecated - public Cancellable getMappingAsync(org.opensearch.action.admin.indices.mapping.get.GetMappingsRequest getMappingsRequest, - RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(getMappingsRequest, + public Cancellable getMappingAsync( + org.opensearch.action.admin.indices.mapping.get.GetMappingsRequest getMappingsRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + getMappingsRequest, IndicesRequestConverters::getMappings, options, org.opensearch.action.admin.indices.mapping.get.GetMappingsResponse::fromXContent, listener, - emptySet()); + emptySet() + ); } /** @@ -486,10 +619,16 @@ public final class IndicesClient { */ @Deprecated public org.opensearch.action.admin.indices.mapping.get.GetFieldMappingsResponse getFieldMapping( - org.opensearch.action.admin.indices.mapping.get.GetFieldMappingsRequest getFieldMappingsRequest, - RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(getFieldMappingsRequest, IndicesRequestConverters::getFieldMapping, - options, org.opensearch.action.admin.indices.mapping.get.GetFieldMappingsResponse::fromXContent, emptySet()); + org.opensearch.action.admin.indices.mapping.get.GetFieldMappingsRequest getFieldMappingsRequest, + RequestOptions options + ) throws IOException { + return restHighLevelClient.performRequestAndParseEntity( + getFieldMappingsRequest, + IndicesRequestConverters::getFieldMapping, + options, + org.opensearch.action.admin.indices.mapping.get.GetFieldMappingsResponse::fromXContent, + emptySet() + ); } /** @@ -508,11 +647,16 @@ public final class IndicesClient { public Cancellable getFieldMappingAsync( org.opensearch.action.admin.indices.mapping.get.GetFieldMappingsRequest getFieldMappingsRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(getFieldMappingsRequest, - IndicesRequestConverters::getFieldMapping, options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + getFieldMappingsRequest, + IndicesRequestConverters::getFieldMapping, + options, org.opensearch.action.admin.indices.mapping.get.GetFieldMappingsResponse::fromXContent, - listener, emptySet()); + listener, + emptySet() + ); } /** @@ -523,10 +667,14 @@ public final class IndicesClient { * @return the response * @throws IOException in case there is a problem sending the request or parsing back the response */ - public GetFieldMappingsResponse getFieldMapping(GetFieldMappingsRequest getFieldMappingsRequest, - RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(getFieldMappingsRequest, IndicesRequestConverters::getFieldMapping, - options, GetFieldMappingsResponse::fromXContent, emptySet() + public GetFieldMappingsResponse getFieldMapping(GetFieldMappingsRequest getFieldMappingsRequest, RequestOptions options) + throws IOException { + return restHighLevelClient.performRequestAndParseEntity( + getFieldMappingsRequest, + IndicesRequestConverters::getFieldMapping, + options, + GetFieldMappingsResponse::fromXContent, + emptySet() ); } @@ -538,11 +686,19 @@ public final class IndicesClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable getFieldMappingAsync(GetFieldMappingsRequest getFieldMappingsRequest, - RequestOptions options, ActionListener listener) { + public Cancellable getFieldMappingAsync( + GetFieldMappingsRequest getFieldMappingsRequest, + RequestOptions options, + ActionListener listener + ) { return restHighLevelClient.performRequestAsyncAndParseEntity( - getFieldMappingsRequest, IndicesRequestConverters::getFieldMapping, options, - GetFieldMappingsResponse::fromXContent, listener, emptySet()); + getFieldMappingsRequest, + IndicesRequestConverters::getFieldMapping, + options, + GetFieldMappingsResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -554,8 +710,13 @@ public final class IndicesClient { * @throws IOException in case there is a problem sending the request or parsing back the response */ public AcknowledgedResponse updateAliases(IndicesAliasesRequest indicesAliasesRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(indicesAliasesRequest, IndicesRequestConverters::updateAliases, options, - AcknowledgedResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + indicesAliasesRequest, + IndicesRequestConverters::updateAliases, + options, + AcknowledgedResponse::fromXContent, + emptySet() + ); } /** @@ -566,11 +727,19 @@ public final class IndicesClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable updateAliasesAsync(IndicesAliasesRequest indicesAliasesRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(indicesAliasesRequest, - IndicesRequestConverters::updateAliases, options, - AcknowledgedResponse::fromXContent, listener, emptySet()); + public Cancellable updateAliasesAsync( + IndicesAliasesRequest indicesAliasesRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + indicesAliasesRequest, + IndicesRequestConverters::updateAliases, + options, + AcknowledgedResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -582,8 +751,13 @@ public final class IndicesClient { * @throws IOException in case there is a problem sending the request or parsing back the response */ public OpenIndexResponse open(OpenIndexRequest openIndexRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(openIndexRequest, IndicesRequestConverters::openIndex, options, - OpenIndexResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + openIndexRequest, + IndicesRequestConverters::openIndex, + options, + OpenIndexResponse::fromXContent, + emptySet() + ); } /** @@ -595,8 +769,14 @@ public final class IndicesClient { * @return cancellable that may be used to cancel the request */ public Cancellable openAsync(OpenIndexRequest openIndexRequest, RequestOptions options, ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(openIndexRequest, IndicesRequestConverters::openIndex, options, - OpenIndexResponse::fromXContent, listener, emptySet()); + return restHighLevelClient.performRequestAsyncAndParseEntity( + openIndexRequest, + IndicesRequestConverters::openIndex, + options, + OpenIndexResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -608,8 +788,13 @@ public final class IndicesClient { * @throws IOException in case there is a problem sending the request or parsing back the response */ public CloseIndexResponse close(CloseIndexRequest closeIndexRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(closeIndexRequest, IndicesRequestConverters::closeIndex, options, - CloseIndexResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + closeIndexRequest, + IndicesRequestConverters::closeIndex, + options, + CloseIndexResponse::fromXContent, + emptySet() + ); } /** @@ -620,14 +805,21 @@ public final class IndicesClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable closeAsync(CloseIndexRequest closeIndexRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(closeIndexRequest, - IndicesRequestConverters::closeIndex, options, - CloseIndexResponse::fromXContent, listener, emptySet()); + public Cancellable closeAsync( + CloseIndexRequest closeIndexRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + closeIndexRequest, + IndicesRequestConverters::closeIndex, + options, + CloseIndexResponse::fromXContent, + listener, + emptySet() + ); } - /** * Checks if one or more aliases exist using the Aliases Exist API. * @@ -637,8 +829,13 @@ public final class IndicesClient { * @throws IOException in case there is a problem sending the request */ public boolean existsAlias(GetAliasesRequest getAliasesRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequest(getAliasesRequest, IndicesRequestConverters::existsAlias, options, - RestHighLevelClient::convertExistsResponse, emptySet()); + return restHighLevelClient.performRequest( + getAliasesRequest, + IndicesRequestConverters::existsAlias, + options, + RestHighLevelClient::convertExistsResponse, + emptySet() + ); } /** @@ -650,8 +847,14 @@ public final class IndicesClient { * @return cancellable that may be used to cancel the request */ public Cancellable existsAliasAsync(GetAliasesRequest getAliasesRequest, RequestOptions options, ActionListener listener) { - return restHighLevelClient.performRequestAsync(getAliasesRequest, IndicesRequestConverters::existsAlias, options, - RestHighLevelClient::convertExistsResponse, listener, emptySet()); + return restHighLevelClient.performRequestAsync( + getAliasesRequest, + IndicesRequestConverters::existsAlias, + options, + RestHighLevelClient::convertExistsResponse, + listener, + emptySet() + ); } /** @@ -663,8 +866,13 @@ public final class IndicesClient { * @throws IOException in case there is a problem sending the request or parsing back the response */ public RefreshResponse refresh(RefreshRequest refreshRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(refreshRequest, IndicesRequestConverters::refresh, options, - RefreshResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + refreshRequest, + IndicesRequestConverters::refresh, + options, + RefreshResponse::fromXContent, + emptySet() + ); } /** @@ -676,8 +884,14 @@ public final class IndicesClient { * @return cancellable that may be used to cancel the request */ public Cancellable refreshAsync(RefreshRequest refreshRequest, RequestOptions options, ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(refreshRequest, IndicesRequestConverters::refresh, options, - RefreshResponse::fromXContent, listener, emptySet()); + return restHighLevelClient.performRequestAsyncAndParseEntity( + refreshRequest, + IndicesRequestConverters::refresh, + options, + RefreshResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -689,8 +903,13 @@ public final class IndicesClient { * @throws IOException in case there is a problem sending the request or parsing back the response */ public FlushResponse flush(FlushRequest flushRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(flushRequest, IndicesRequestConverters::flush, options, - FlushResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + flushRequest, + IndicesRequestConverters::flush, + options, + FlushResponse::fromXContent, + emptySet() + ); } /** @@ -702,8 +921,14 @@ public final class IndicesClient { * @return cancellable that may be used to cancel the request */ public Cancellable flushAsync(FlushRequest flushRequest, RequestOptions options, ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(flushRequest, IndicesRequestConverters::flush, options, - FlushResponse::fromXContent, listener, emptySet()); + return restHighLevelClient.performRequestAsyncAndParseEntity( + flushRequest, + IndicesRequestConverters::flush, + options, + FlushResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -718,8 +943,13 @@ public final class IndicesClient { */ @Deprecated public SyncedFlushResponse flushSynced(SyncedFlushRequest syncedFlushRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(syncedFlushRequest, IndicesRequestConverters::flushSynced, options, - SyncedFlushResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + syncedFlushRequest, + IndicesRequestConverters::flushSynced, + options, + SyncedFlushResponse::fromXContent, + emptySet() + ); } /** @@ -733,10 +963,19 @@ public final class IndicesClient { * Use {@link #flushAsync(FlushRequest, RequestOptions, ActionListener)} instead. */ @Deprecated - public Cancellable flushSyncedAsync(SyncedFlushRequest syncedFlushRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(syncedFlushRequest, IndicesRequestConverters::flushSynced, options, - SyncedFlushResponse::fromXContent, listener, emptySet()); + public Cancellable flushSyncedAsync( + SyncedFlushRequest syncedFlushRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + syncedFlushRequest, + IndicesRequestConverters::flushSynced, + options, + SyncedFlushResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -748,8 +987,13 @@ public final class IndicesClient { * @throws IOException in case there is a problem sending the request or parsing back the response */ public GetSettingsResponse getSettings(GetSettingsRequest getSettingsRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(getSettingsRequest, IndicesRequestConverters::getSettings, options, - GetSettingsResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + getSettingsRequest, + IndicesRequestConverters::getSettings, + options, + GetSettingsResponse::fromXContent, + emptySet() + ); } /** @@ -760,10 +1004,19 @@ public final class IndicesClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable getSettingsAsync(GetSettingsRequest getSettingsRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(getSettingsRequest, IndicesRequestConverters::getSettings, options, - GetSettingsResponse::fromXContent, listener, emptySet()); + public Cancellable getSettingsAsync( + GetSettingsRequest getSettingsRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + getSettingsRequest, + IndicesRequestConverters::getSettings, + options, + GetSettingsResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -775,8 +1028,13 @@ public final class IndicesClient { * @throws IOException in case there is a problem sending the request or parsing back the response */ public GetIndexResponse get(GetIndexRequest getIndexRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(getIndexRequest, IndicesRequestConverters::getIndex, options, - GetIndexResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + getIndexRequest, + IndicesRequestConverters::getIndex, + options, + GetIndexResponse::fromXContent, + emptySet() + ); } /** @@ -787,10 +1045,15 @@ public final class IndicesClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable getAsync(GetIndexRequest getIndexRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(getIndexRequest, IndicesRequestConverters::getIndex, options, - GetIndexResponse::fromXContent, listener, emptySet()); + public Cancellable getAsync(GetIndexRequest getIndexRequest, RequestOptions options, ActionListener listener) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + getIndexRequest, + IndicesRequestConverters::getIndex, + options, + GetIndexResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -805,9 +1068,16 @@ public final class IndicesClient { */ @Deprecated public org.opensearch.action.admin.indices.get.GetIndexResponse get( - org.opensearch.action.admin.indices.get.GetIndexRequest getIndexRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(getIndexRequest, IndicesRequestConverters::getIndex, options, - org.opensearch.action.admin.indices.get.GetIndexResponse::fromXContent, emptySet()); + org.opensearch.action.admin.indices.get.GetIndexRequest getIndexRequest, + RequestOptions options + ) throws IOException { + return restHighLevelClient.performRequestAndParseEntity( + getIndexRequest, + IndicesRequestConverters::getIndex, + options, + org.opensearch.action.admin.indices.get.GetIndexResponse::fromXContent, + emptySet() + ); } /** @@ -821,10 +1091,19 @@ public final class IndicesClient { * @return cancellable that may be used to cancel the request */ @Deprecated - public Cancellable getAsync(org.opensearch.action.admin.indices.get.GetIndexRequest getIndexRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(getIndexRequest, IndicesRequestConverters::getIndex, options, - org.opensearch.action.admin.indices.get.GetIndexResponse::fromXContent, listener, emptySet()); + public Cancellable getAsync( + org.opensearch.action.admin.indices.get.GetIndexRequest getIndexRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + getIndexRequest, + IndicesRequestConverters::getIndex, + options, + org.opensearch.action.admin.indices.get.GetIndexResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -850,8 +1129,13 @@ public final class IndicesClient { * @throws IOException in case there is a problem sending the request or parsing back the response */ public ForceMergeResponse forcemerge(ForceMergeRequest forceMergeRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(forceMergeRequest, IndicesRequestConverters::forceMerge, options, - ForceMergeResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + forceMergeRequest, + IndicesRequestConverters::forceMerge, + options, + ForceMergeResponse::fromXContent, + emptySet() + ); } /** @@ -864,8 +1148,11 @@ public final class IndicesClient { * @return cancellable that may be used to cancel the request */ @Deprecated - public Cancellable forceMergeAsync(ForceMergeRequest forceMergeRequest, RequestOptions options, - ActionListener listener) { + public Cancellable forceMergeAsync( + ForceMergeRequest forceMergeRequest, + RequestOptions options, + ActionListener listener + ) { return forcemergeAsync(forceMergeRequest, options, listener); } @@ -877,11 +1164,19 @@ public final class IndicesClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable forcemergeAsync(ForceMergeRequest forceMergeRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(forceMergeRequest, - IndicesRequestConverters::forceMerge, options, - ForceMergeResponse::fromXContent, listener, emptySet()); + public Cancellable forcemergeAsync( + ForceMergeRequest forceMergeRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + forceMergeRequest, + IndicesRequestConverters::forceMerge, + options, + ForceMergeResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -892,10 +1187,15 @@ public final class IndicesClient { * @return the response * @throws IOException in case there is a problem sending the request or parsing back the response */ - public ClearIndicesCacheResponse clearCache(ClearIndicesCacheRequest clearIndicesCacheRequest, - RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(clearIndicesCacheRequest, IndicesRequestConverters::clearCache, options, - ClearIndicesCacheResponse::fromXContent, emptySet()); + public ClearIndicesCacheResponse clearCache(ClearIndicesCacheRequest clearIndicesCacheRequest, RequestOptions options) + throws IOException { + return restHighLevelClient.performRequestAndParseEntity( + clearIndicesCacheRequest, + IndicesRequestConverters::clearCache, + options, + ClearIndicesCacheResponse::fromXContent, + emptySet() + ); } /** @@ -906,11 +1206,19 @@ public final class IndicesClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable clearCacheAsync(ClearIndicesCacheRequest clearIndicesCacheRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(clearIndicesCacheRequest, - IndicesRequestConverters::clearCache, options, - ClearIndicesCacheResponse::fromXContent, listener, emptySet()); + public Cancellable clearCacheAsync( + ClearIndicesCacheRequest clearIndicesCacheRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + clearIndicesCacheRequest, + IndicesRequestConverters::clearCache, + options, + ClearIndicesCacheResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -941,12 +1249,12 @@ public final class IndicesClient { */ public Cancellable existsAsync(GetIndexRequest request, RequestOptions options, ActionListener listener) { return restHighLevelClient.performRequestAsync( - request, - IndicesRequestConverters::indicesExist, - options, - RestHighLevelClient::convertExistsResponse, - listener, - Collections.emptySet() + request, + IndicesRequestConverters::indicesExist, + options, + RestHighLevelClient::convertExistsResponse, + listener, + Collections.emptySet() ); } @@ -982,15 +1290,18 @@ public final class IndicesClient { * @return cancellable that may be used to cancel the request */ @Deprecated - public Cancellable existsAsync(org.opensearch.action.admin.indices.get.GetIndexRequest request, RequestOptions options, - ActionListener listener) { + public Cancellable existsAsync( + org.opensearch.action.admin.indices.get.GetIndexRequest request, + RequestOptions options, + ActionListener listener + ) { return restHighLevelClient.performRequestAsync( - request, - IndicesRequestConverters::indicesExist, - options, - RestHighLevelClient::convertExistsResponse, - listener, - Collections.emptySet() + request, + IndicesRequestConverters::indicesExist, + options, + RestHighLevelClient::convertExistsResponse, + listener, + Collections.emptySet() ); } @@ -1003,8 +1314,13 @@ public final class IndicesClient { * @throws IOException in case there is a problem sending the request or parsing back the response */ public ResizeResponse shrink(ResizeRequest resizeRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(resizeRequest, IndicesRequestConverters::shrink, options, - ResizeResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + resizeRequest, + IndicesRequestConverters::shrink, + options, + ResizeResponse::fromXContent, + emptySet() + ); } /** @@ -1018,9 +1334,16 @@ public final class IndicesClient { */ @Deprecated public org.opensearch.action.admin.indices.shrink.ResizeResponse shrink( - org.opensearch.action.admin.indices.shrink.ResizeRequest resizeRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(resizeRequest, IndicesRequestConverters::shrink, options, - org.opensearch.action.admin.indices.shrink.ResizeResponse::fromXContent, emptySet()); + org.opensearch.action.admin.indices.shrink.ResizeRequest resizeRequest, + RequestOptions options + ) throws IOException { + return restHighLevelClient.performRequestAndParseEntity( + resizeRequest, + IndicesRequestConverters::shrink, + options, + org.opensearch.action.admin.indices.shrink.ResizeResponse::fromXContent, + emptySet() + ); } /** @@ -1032,8 +1355,14 @@ public final class IndicesClient { * @return cancellable that may be used to cancel the request */ public Cancellable shrinkAsync(ResizeRequest resizeRequest, RequestOptions options, ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(resizeRequest, IndicesRequestConverters::shrink, options, - ResizeResponse::fromXContent, listener, emptySet()); + return restHighLevelClient.performRequestAsyncAndParseEntity( + resizeRequest, + IndicesRequestConverters::shrink, + options, + ResizeResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -1046,10 +1375,19 @@ public final class IndicesClient { * @deprecated use {@link #shrinkAsync(ResizeRequest, RequestOptions, ActionListener)} */ @Deprecated - public Cancellable shrinkAsync(org.opensearch.action.admin.indices.shrink.ResizeRequest resizeRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(resizeRequest, IndicesRequestConverters::shrink, options, - org.opensearch.action.admin.indices.shrink.ResizeResponse::fromXContent, listener, emptySet()); + public Cancellable shrinkAsync( + org.opensearch.action.admin.indices.shrink.ResizeRequest resizeRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + resizeRequest, + IndicesRequestConverters::shrink, + options, + org.opensearch.action.admin.indices.shrink.ResizeResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -1061,8 +1399,13 @@ public final class IndicesClient { * @throws IOException in case there is a problem sending the request or parsing back the response */ public ResizeResponse split(ResizeRequest resizeRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(resizeRequest, IndicesRequestConverters::split, options, - ResizeResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + resizeRequest, + IndicesRequestConverters::split, + options, + ResizeResponse::fromXContent, + emptySet() + ); } /** @@ -1076,9 +1419,16 @@ public final class IndicesClient { */ @Deprecated public org.opensearch.action.admin.indices.shrink.ResizeResponse split( - org.opensearch.action.admin.indices.shrink.ResizeRequest resizeRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(resizeRequest, IndicesRequestConverters::split, options, - org.opensearch.action.admin.indices.shrink.ResizeResponse::fromXContent, emptySet()); + org.opensearch.action.admin.indices.shrink.ResizeRequest resizeRequest, + RequestOptions options + ) throws IOException { + return restHighLevelClient.performRequestAndParseEntity( + resizeRequest, + IndicesRequestConverters::split, + options, + org.opensearch.action.admin.indices.shrink.ResizeResponse::fromXContent, + emptySet() + ); } /** @@ -1090,8 +1440,14 @@ public final class IndicesClient { * @return cancellable that may be used to cancel the request */ public Cancellable splitAsync(ResizeRequest resizeRequest, RequestOptions options, ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(resizeRequest, IndicesRequestConverters::split, options, - ResizeResponse::fromXContent, listener, emptySet()); + return restHighLevelClient.performRequestAsyncAndParseEntity( + resizeRequest, + IndicesRequestConverters::split, + options, + ResizeResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -1104,10 +1460,19 @@ public final class IndicesClient { * @deprecated use {@link #splitAsync(ResizeRequest, RequestOptions, ActionListener)} */ @Deprecated - public Cancellable splitAsync(org.opensearch.action.admin.indices.shrink.ResizeRequest resizeRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(resizeRequest, IndicesRequestConverters::split, options, - org.opensearch.action.admin.indices.shrink.ResizeResponse::fromXContent, listener, emptySet()); + public Cancellable splitAsync( + org.opensearch.action.admin.indices.shrink.ResizeRequest resizeRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + resizeRequest, + IndicesRequestConverters::split, + options, + org.opensearch.action.admin.indices.shrink.ResizeResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -1119,8 +1484,13 @@ public final class IndicesClient { * @throws IOException in case there is a problem sending the request or parsing back the response */ public ResizeResponse clone(ResizeRequest resizeRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(resizeRequest, IndicesRequestConverters::clone, options, - ResizeResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + resizeRequest, + IndicesRequestConverters::clone, + options, + ResizeResponse::fromXContent, + emptySet() + ); } /** @@ -1134,9 +1504,16 @@ public final class IndicesClient { */ @Deprecated public org.opensearch.action.admin.indices.shrink.ResizeResponse clone( - org.opensearch.action.admin.indices.shrink.ResizeRequest resizeRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(resizeRequest, IndicesRequestConverters::clone, options, - org.opensearch.action.admin.indices.shrink.ResizeResponse::fromXContent, emptySet()); + org.opensearch.action.admin.indices.shrink.ResizeRequest resizeRequest, + RequestOptions options + ) throws IOException { + return restHighLevelClient.performRequestAndParseEntity( + resizeRequest, + IndicesRequestConverters::clone, + options, + org.opensearch.action.admin.indices.shrink.ResizeResponse::fromXContent, + emptySet() + ); } /** @@ -1148,8 +1525,14 @@ public final class IndicesClient { * @return cancellable that may be used to cancel the request */ public Cancellable cloneAsync(ResizeRequest resizeRequest, RequestOptions options, ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(resizeRequest, IndicesRequestConverters::clone, options, - ResizeResponse::fromXContent, listener, emptySet()); + return restHighLevelClient.performRequestAsyncAndParseEntity( + resizeRequest, + IndicesRequestConverters::clone, + options, + ResizeResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -1162,10 +1545,19 @@ public final class IndicesClient { * @deprecated use {@link #cloneAsync(ResizeRequest, RequestOptions, ActionListener)} */ @Deprecated - public Cancellable cloneAsync(org.opensearch.action.admin.indices.shrink.ResizeRequest resizeRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(resizeRequest, IndicesRequestConverters::clone, options, - org.opensearch.action.admin.indices.shrink.ResizeResponse::fromXContent, listener, emptySet()); + public Cancellable cloneAsync( + org.opensearch.action.admin.indices.shrink.ResizeRequest resizeRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + resizeRequest, + IndicesRequestConverters::clone, + options, + org.opensearch.action.admin.indices.shrink.ResizeResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -1177,8 +1569,13 @@ public final class IndicesClient { * @throws IOException in case there is a problem sending the request or parsing back the response */ public RolloverResponse rollover(RolloverRequest rolloverRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(rolloverRequest, IndicesRequestConverters::rollover, options, - RolloverResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + rolloverRequest, + IndicesRequestConverters::rollover, + options, + RolloverResponse::fromXContent, + emptySet() + ); } /** @@ -1190,11 +1587,16 @@ public final class IndicesClient { * @return cancellable that may be used to cancel the request */ public Cancellable rolloverAsync(RolloverRequest rolloverRequest, RequestOptions options, ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(rolloverRequest, IndicesRequestConverters::rollover, options, - RolloverResponse::fromXContent, listener, emptySet()); + return restHighLevelClient.performRequestAsyncAndParseEntity( + rolloverRequest, + IndicesRequestConverters::rollover, + options, + RolloverResponse::fromXContent, + listener, + emptySet() + ); } - /** * Rolls over an index using the Rollover Index API. * @@ -1208,10 +1610,16 @@ public final class IndicesClient { */ @Deprecated public org.opensearch.action.admin.indices.rollover.RolloverResponse rollover( - org.opensearch.action.admin.indices.rollover.RolloverRequest rolloverRequest, - RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(rolloverRequest, IndicesRequestConverters::rollover, options, - org.opensearch.action.admin.indices.rollover.RolloverResponse::fromXContent, emptySet()); + org.opensearch.action.admin.indices.rollover.RolloverRequest rolloverRequest, + RequestOptions options + ) throws IOException { + return restHighLevelClient.performRequestAndParseEntity( + rolloverRequest, + IndicesRequestConverters::rollover, + options, + org.opensearch.action.admin.indices.rollover.RolloverResponse::fromXContent, + emptySet() + ); } /** @@ -1227,11 +1635,19 @@ public final class IndicesClient { * @return cancellable that may be used to cancel the request */ @Deprecated - public Cancellable rolloverAsync(org.opensearch.action.admin.indices.rollover.RolloverRequest rolloverRequest, - RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(rolloverRequest, IndicesRequestConverters::rollover, options, - org.opensearch.action.admin.indices.rollover.RolloverResponse::fromXContent, listener, emptySet()); + public Cancellable rolloverAsync( + org.opensearch.action.admin.indices.rollover.RolloverRequest rolloverRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + rolloverRequest, + IndicesRequestConverters::rollover, + options, + org.opensearch.action.admin.indices.rollover.RolloverResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -1243,8 +1659,13 @@ public final class IndicesClient { * @throws IOException in case there is a problem sending the request or parsing back the response */ public GetAliasesResponse getAlias(GetAliasesRequest getAliasesRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(getAliasesRequest, IndicesRequestConverters::getAlias, options, - GetAliasesResponse::fromXContent, singleton(RestStatus.NOT_FOUND.getStatus())); + return restHighLevelClient.performRequestAndParseEntity( + getAliasesRequest, + IndicesRequestConverters::getAlias, + options, + GetAliasesResponse::fromXContent, + singleton(RestStatus.NOT_FOUND.getStatus()) + ); } /** @@ -1255,11 +1676,19 @@ public final class IndicesClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable getAliasAsync(GetAliasesRequest getAliasesRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(getAliasesRequest, - IndicesRequestConverters::getAlias, options, - GetAliasesResponse::fromXContent, listener, singleton(RestStatus.NOT_FOUND.getStatus())); + public Cancellable getAliasAsync( + GetAliasesRequest getAliasesRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + getAliasesRequest, + IndicesRequestConverters::getAlias, + options, + GetAliasesResponse::fromXContent, + listener, + singleton(RestStatus.NOT_FOUND.getStatus()) + ); } /** @@ -1271,8 +1700,13 @@ public final class IndicesClient { * @throws IOException in case there is a problem sending the request or parsing back the response */ public AcknowledgedResponse putSettings(UpdateSettingsRequest updateSettingsRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(updateSettingsRequest, IndicesRequestConverters::indexPutSettings, options, - AcknowledgedResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + updateSettingsRequest, + IndicesRequestConverters::indexPutSettings, + options, + AcknowledgedResponse::fromXContent, + emptySet() + ); } /** @@ -1283,14 +1717,21 @@ public final class IndicesClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable putSettingsAsync(UpdateSettingsRequest updateSettingsRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(updateSettingsRequest, - IndicesRequestConverters::indexPutSettings, options, - AcknowledgedResponse::fromXContent, listener, emptySet()); + public Cancellable putSettingsAsync( + UpdateSettingsRequest updateSettingsRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + updateSettingsRequest, + IndicesRequestConverters::indexPutSettings, + options, + AcknowledgedResponse::fromXContent, + listener, + emptySet() + ); } - /** * Puts an index template using the Index Templates API. * @@ -1303,10 +1744,16 @@ public final class IndicesClient { */ @Deprecated public AcknowledgedResponse putTemplate( - org.opensearch.action.admin.indices.template.put.PutIndexTemplateRequest putIndexTemplateRequest, - RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(putIndexTemplateRequest, IndicesRequestConverters::putTemplate, options, - AcknowledgedResponse::fromXContent, emptySet()); + org.opensearch.action.admin.indices.template.put.PutIndexTemplateRequest putIndexTemplateRequest, + RequestOptions options + ) throws IOException { + return restHighLevelClient.performRequestAndParseEntity( + putIndexTemplateRequest, + IndicesRequestConverters::putTemplate, + options, + AcknowledgedResponse::fromXContent, + emptySet() + ); } /** @@ -1322,14 +1769,20 @@ public final class IndicesClient { */ @Deprecated public Cancellable putTemplateAsync( - org.opensearch.action.admin.indices.template.put.PutIndexTemplateRequest putIndexTemplateRequest, - RequestOptions options, ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(putIndexTemplateRequest, - IndicesRequestConverters::putTemplate, options, - AcknowledgedResponse::fromXContent, listener, emptySet()); + org.opensearch.action.admin.indices.template.put.PutIndexTemplateRequest putIndexTemplateRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + putIndexTemplateRequest, + IndicesRequestConverters::putTemplate, + options, + AcknowledgedResponse::fromXContent, + listener, + emptySet() + ); } - /** * Puts an index template using the Index Templates API. * @@ -1338,11 +1791,14 @@ public final class IndicesClient { * @return the response * @throws IOException in case there is a problem sending the request or parsing back the response */ - public AcknowledgedResponse putTemplate( - PutIndexTemplateRequest putIndexTemplateRequest, - RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(putIndexTemplateRequest, IndicesRequestConverters::putTemplate, options, - AcknowledgedResponse::fromXContent, emptySet()); + public AcknowledgedResponse putTemplate(PutIndexTemplateRequest putIndexTemplateRequest, RequestOptions options) throws IOException { + return restHighLevelClient.performRequestAndParseEntity( + putIndexTemplateRequest, + IndicesRequestConverters::putTemplate, + options, + AcknowledgedResponse::fromXContent, + emptySet() + ); } /** @@ -1353,11 +1809,19 @@ public final class IndicesClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable putTemplateAsync(PutIndexTemplateRequest putIndexTemplateRequest, - RequestOptions options, ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(putIndexTemplateRequest, - IndicesRequestConverters::putTemplate, options, - AcknowledgedResponse::fromXContent, listener, emptySet()); + public Cancellable putTemplateAsync( + PutIndexTemplateRequest putIndexTemplateRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + putIndexTemplateRequest, + IndicesRequestConverters::putTemplate, + options, + AcknowledgedResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -1370,8 +1834,13 @@ public final class IndicesClient { */ public AcknowledgedResponse putIndexTemplate(PutComposableIndexTemplateRequest putIndexTemplateRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(putIndexTemplateRequest, IndicesRequestConverters::putIndexTemplate, - options, AcknowledgedResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + putIndexTemplateRequest, + IndicesRequestConverters::putIndexTemplate, + options, + AcknowledgedResponse::fromXContent, + emptySet() + ); } /** @@ -1382,10 +1851,19 @@ public final class IndicesClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable putIndexTemplateAsync(PutComposableIndexTemplateRequest putIndexTemplateRequest, - RequestOptions options, ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(putIndexTemplateRequest, IndicesRequestConverters::putIndexTemplate, - options, AcknowledgedResponse::fromXContent, listener, emptySet()); + public Cancellable putIndexTemplateAsync( + PutComposableIndexTemplateRequest putIndexTemplateRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + putIndexTemplateRequest, + IndicesRequestConverters::putIndexTemplate, + options, + AcknowledgedResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -1398,10 +1876,17 @@ public final class IndicesClient { * @return the response * @throws IOException in case there is a problem sending the request or parsing back the response */ - public SimulateIndexTemplateResponse simulateIndexTemplate(SimulateIndexTemplateRequest simulateIndexTemplateRequest, - RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(simulateIndexTemplateRequest, - IndicesRequestConverters::simulateIndexTemplate, options, SimulateIndexTemplateResponse::fromXContent, emptySet()); + public SimulateIndexTemplateResponse simulateIndexTemplate( + SimulateIndexTemplateRequest simulateIndexTemplateRequest, + RequestOptions options + ) throws IOException { + return restHighLevelClient.performRequestAndParseEntity( + simulateIndexTemplateRequest, + IndicesRequestConverters::simulateIndexTemplate, + options, + SimulateIndexTemplateResponse::fromXContent, + emptySet() + ); } /** @@ -1413,10 +1898,19 @@ public final class IndicesClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable simulateIndexTemplateAsync(SimulateIndexTemplateRequest simulateIndexTemplateRequest, - RequestOptions options, ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(simulateIndexTemplateRequest, - IndicesRequestConverters::simulateIndexTemplate, options, SimulateIndexTemplateResponse::fromXContent, listener, emptySet()); + public Cancellable simulateIndexTemplateAsync( + SimulateIndexTemplateRequest simulateIndexTemplateRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + simulateIndexTemplateRequest, + IndicesRequestConverters::simulateIndexTemplate, + options, + SimulateIndexTemplateResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -1428,11 +1922,14 @@ public final class IndicesClient { * @return the response * @throws IOException in case there is a problem sending the request or parsing back the response */ - public ValidateQueryResponse validateQuery(ValidateQueryRequest validateQueryRequest, - RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(validateQueryRequest, - IndicesRequestConverters::validateQuery, options, - ValidateQueryResponse::fromXContent, emptySet()); + public ValidateQueryResponse validateQuery(ValidateQueryRequest validateQueryRequest, RequestOptions options) throws IOException { + return restHighLevelClient.performRequestAndParseEntity( + validateQueryRequest, + IndicesRequestConverters::validateQuery, + options, + ValidateQueryResponse::fromXContent, + emptySet() + ); } /** @@ -1444,11 +1941,19 @@ public final class IndicesClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable validateQueryAsync(ValidateQueryRequest validateQueryRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(validateQueryRequest, - IndicesRequestConverters::validateQuery, options, - ValidateQueryResponse::fromXContent, listener, emptySet()); + public Cancellable validateQueryAsync( + ValidateQueryRequest validateQueryRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + validateQueryRequest, + IndicesRequestConverters::validateQuery, + options, + ValidateQueryResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -1464,11 +1969,16 @@ public final class IndicesClient { */ @Deprecated public org.opensearch.action.admin.indices.template.get.GetIndexTemplatesResponse getTemplate( - GetIndexTemplatesRequest getIndexTemplatesRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(getIndexTemplatesRequest, + GetIndexTemplatesRequest getIndexTemplatesRequest, + RequestOptions options + ) throws IOException { + return restHighLevelClient.performRequestAndParseEntity( + getIndexTemplatesRequest, IndicesRequestConverters::getTemplatesWithDocumentTypes, options, - org.opensearch.action.admin.indices.template.get.GetIndexTemplatesResponse::fromXContent, emptySet()); + org.opensearch.action.admin.indices.template.get.GetIndexTemplatesResponse::fromXContent, + emptySet() + ); } /** @@ -1479,10 +1989,17 @@ public final class IndicesClient { * @return the response * @throws IOException in case there is a problem sending the request or parsing back the response */ - public GetComposableIndexTemplatesResponse getIndexTemplate(GetComposableIndexTemplateRequest getIndexTemplatesRequest, - RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(getIndexTemplatesRequest, IndicesRequestConverters::getIndexTemplates, - options, GetComposableIndexTemplatesResponse::fromXContent, emptySet()); + public GetComposableIndexTemplatesResponse getIndexTemplate( + GetComposableIndexTemplateRequest getIndexTemplatesRequest, + RequestOptions options + ) throws IOException { + return restHighLevelClient.performRequestAndParseEntity( + getIndexTemplatesRequest, + IndicesRequestConverters::getIndexTemplates, + options, + GetComposableIndexTemplatesResponse::fromXContent, + emptySet() + ); } /** @@ -1493,10 +2010,19 @@ public final class IndicesClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable getIndexTemplateAsync(GetComposableIndexTemplateRequest getIndexTemplatesRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(getIndexTemplatesRequest, - IndicesRequestConverters::getIndexTemplates, options, GetComposableIndexTemplatesResponse::fromXContent, listener, emptySet()); + public Cancellable getIndexTemplateAsync( + GetComposableIndexTemplateRequest getIndexTemplatesRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + getIndexTemplatesRequest, + IndicesRequestConverters::getIndexTemplates, + options, + GetComposableIndexTemplatesResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -1507,11 +2033,15 @@ public final class IndicesClient { * @return the response * @throws IOException in case there is a problem sending the request or parsing back the response */ - public GetIndexTemplatesResponse getIndexTemplate(GetIndexTemplatesRequest getIndexTemplatesRequest, - RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(getIndexTemplatesRequest, + public GetIndexTemplatesResponse getIndexTemplate(GetIndexTemplatesRequest getIndexTemplatesRequest, RequestOptions options) + throws IOException { + return restHighLevelClient.performRequestAndParseEntity( + getIndexTemplatesRequest, IndicesRequestConverters::getTemplates, - options, GetIndexTemplatesResponse::fromXContent, emptySet()); + options, + GetIndexTemplatesResponse::fromXContent, + emptySet() + ); } /** @@ -1526,13 +2056,19 @@ public final class IndicesClient { * @return cancellable that may be used to cancel the request */ @Deprecated - public Cancellable getTemplateAsync(GetIndexTemplatesRequest getIndexTemplatesRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(getIndexTemplatesRequest, + public Cancellable getTemplateAsync( + GetIndexTemplatesRequest getIndexTemplatesRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + getIndexTemplatesRequest, IndicesRequestConverters::getTemplatesWithDocumentTypes, options, org.opensearch.action.admin.indices.template.get.GetIndexTemplatesResponse::fromXContent, - listener, emptySet()); + listener, + emptySet() + ); } /** @@ -1543,11 +2079,19 @@ public final class IndicesClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable getIndexTemplateAsync(GetIndexTemplatesRequest getIndexTemplatesRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(getIndexTemplatesRequest, + public Cancellable getIndexTemplateAsync( + GetIndexTemplatesRequest getIndexTemplatesRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + getIndexTemplatesRequest, IndicesRequestConverters::getTemplates, - options, GetIndexTemplatesResponse::fromXContent, listener, emptySet()); + options, + GetIndexTemplatesResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -1558,11 +2102,14 @@ public final class IndicesClient { * @return true if any index templates in the request exist, false otherwise * @throws IOException in case there is a problem sending the request or parsing back the response */ - public boolean existsTemplate(IndexTemplatesExistRequest indexTemplatesRequest, - RequestOptions options) throws IOException { - return restHighLevelClient.performRequest(indexTemplatesRequest, - IndicesRequestConverters::templatesExist, options, - RestHighLevelClient::convertExistsResponse, emptySet()); + public boolean existsTemplate(IndexTemplatesExistRequest indexTemplatesRequest, RequestOptions options) throws IOException { + return restHighLevelClient.performRequest( + indexTemplatesRequest, + IndicesRequestConverters::templatesExist, + options, + RestHighLevelClient::convertExistsResponse, + emptySet() + ); } /** @@ -1572,13 +2119,20 @@ public final class IndicesClient { * @param listener the listener to be notified upon request completion. The listener will be called with the value {@code true} * @return cancellable that may be used to cancel the request */ - public Cancellable existsTemplateAsync(IndexTemplatesExistRequest indexTemplatesExistRequest, - RequestOptions options, - ActionListener listener) { + public Cancellable existsTemplateAsync( + IndexTemplatesExistRequest indexTemplatesExistRequest, + RequestOptions options, + ActionListener listener + ) { - return restHighLevelClient.performRequestAsync(indexTemplatesExistRequest, - IndicesRequestConverters::templatesExist, options, - RestHighLevelClient::convertExistsResponse, listener, emptySet()); + return restHighLevelClient.performRequestAsync( + indexTemplatesExistRequest, + IndicesRequestConverters::templatesExist, + options, + RestHighLevelClient::convertExistsResponse, + listener, + emptySet() + ); } /** @@ -1589,11 +2143,15 @@ public final class IndicesClient { * @return true if any index templates in the request exist, false otherwise * @throws IOException in case there is a problem sending the request or parsing back the response */ - public boolean existsIndexTemplate(ComposableIndexTemplateExistRequest indexTemplatesRequest, - RequestOptions options) throws IOException { - return restHighLevelClient.performRequest(indexTemplatesRequest, - IndicesRequestConverters::templatesExist, options, - RestHighLevelClient::convertExistsResponse, emptySet()); + public boolean existsIndexTemplate(ComposableIndexTemplateExistRequest indexTemplatesRequest, RequestOptions options) + throws IOException { + return restHighLevelClient.performRequest( + indexTemplatesRequest, + IndicesRequestConverters::templatesExist, + options, + RestHighLevelClient::convertExistsResponse, + emptySet() + ); } /** @@ -1603,13 +2161,20 @@ public final class IndicesClient { * @param listener the listener to be notified upon request completion. The listener will be called with the value {@code true} * @return cancellable that may be used to cancel the request */ - public Cancellable existsIndexTemplateAsync(ComposableIndexTemplateExistRequest indexTemplatesExistRequest, - RequestOptions options, - ActionListener listener) { + public Cancellable existsIndexTemplateAsync( + ComposableIndexTemplateExistRequest indexTemplatesExistRequest, + RequestOptions options, + ActionListener listener + ) { - return restHighLevelClient.performRequestAsync(indexTemplatesExistRequest, - IndicesRequestConverters::templatesExist, options, - RestHighLevelClient::convertExistsResponse, listener, emptySet()); + return restHighLevelClient.performRequestAsync( + indexTemplatesExistRequest, + IndicesRequestConverters::templatesExist, + options, + RestHighLevelClient::convertExistsResponse, + listener, + emptySet() + ); } /** @@ -1619,8 +2184,13 @@ public final class IndicesClient { * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized */ public AnalyzeResponse analyze(AnalyzeRequest request, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(request, IndicesRequestConverters::analyze, options, - AnalyzeResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + request, + IndicesRequestConverters::analyze, + options, + AnalyzeResponse::fromXContent, + emptySet() + ); } /** @@ -1631,10 +2201,15 @@ public final class IndicesClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable analyzeAsync(AnalyzeRequest request, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(request, IndicesRequestConverters::analyze, options, - AnalyzeResponse::fromXContent, listener, emptySet()); + public Cancellable analyzeAsync(AnalyzeRequest request, RequestOptions options, ActionListener listener) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + request, + IndicesRequestConverters::analyze, + options, + AnalyzeResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -1645,8 +2220,13 @@ public final class IndicesClient { * @throws IOException in case there is a problem sending the request or parsing back the response */ public AcknowledgedResponse deleteTemplate(DeleteIndexTemplateRequest request, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(request, IndicesRequestConverters::deleteTemplate, - options, AcknowledgedResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + request, + IndicesRequestConverters::deleteTemplate, + options, + AcknowledgedResponse::fromXContent, + emptySet() + ); } /** @@ -1657,10 +2237,19 @@ public final class IndicesClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable deleteTemplateAsync(DeleteIndexTemplateRequest request, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(request, IndicesRequestConverters::deleteTemplate, - options, AcknowledgedResponse::fromXContent, listener, emptySet()); + public Cancellable deleteTemplateAsync( + DeleteIndexTemplateRequest request, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + request, + IndicesRequestConverters::deleteTemplate, + options, + AcknowledgedResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -1670,10 +2259,15 @@ public final class IndicesClient { * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized * @throws IOException in case there is a problem sending the request or parsing back the response */ - public AcknowledgedResponse deleteIndexTemplate(DeleteComposableIndexTemplateRequest request, - RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(request, IndicesRequestConverters::deleteIndexTemplate, - options, AcknowledgedResponse::fromXContent, emptySet()); + public AcknowledgedResponse deleteIndexTemplate(DeleteComposableIndexTemplateRequest request, RequestOptions options) + throws IOException { + return restHighLevelClient.performRequestAndParseEntity( + request, + IndicesRequestConverters::deleteIndexTemplate, + options, + AcknowledgedResponse::fromXContent, + emptySet() + ); } /** @@ -1684,10 +2278,19 @@ public final class IndicesClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable deleteIndexTemplateAsync(DeleteComposableIndexTemplateRequest request, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(request, IndicesRequestConverters::deleteIndexTemplate, - options, AcknowledgedResponse::fromXContent, listener, emptySet()); + public Cancellable deleteIndexTemplateAsync( + DeleteComposableIndexTemplateRequest request, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + request, + IndicesRequestConverters::deleteIndexTemplate, + options, + AcknowledgedResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -1695,10 +2298,15 @@ public final class IndicesClient { * @param request the request * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized */ - public org.opensearch.client.core.AcknowledgedResponse deleteAlias(DeleteAliasRequest request, - RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(request, IndicesRequestConverters::deleteAlias, options, - org.opensearch.client.core.AcknowledgedResponse::fromXContent, emptySet()); + public org.opensearch.client.core.AcknowledgedResponse deleteAlias(DeleteAliasRequest request, RequestOptions options) + throws IOException { + return restHighLevelClient.performRequestAndParseEntity( + request, + IndicesRequestConverters::deleteAlias, + options, + org.opensearch.client.core.AcknowledgedResponse::fromXContent, + emptySet() + ); } /** @@ -1708,9 +2316,18 @@ public final class IndicesClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable deleteAliasAsync(DeleteAliasRequest request, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(request, IndicesRequestConverters::deleteAlias, options, - org.opensearch.client.core.AcknowledgedResponse::fromXContent, listener, emptySet()); + public Cancellable deleteAliasAsync( + DeleteAliasRequest request, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + request, + IndicesRequestConverters::deleteAlias, + options, + org.opensearch.client.core.AcknowledgedResponse::fromXContent, + listener, + emptySet() + ); } } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/IndicesRequestConverters.java b/client/rest-high-level/src/main/java/org/opensearch/client/IndicesRequestConverters.java index 9a4089120b8..920b7343ddc 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/IndicesRequestConverters.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/IndicesRequestConverters.java @@ -37,7 +37,6 @@ import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpHead; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; -import org.opensearch.client.Request; import org.opensearch.action.admin.indices.alias.IndicesAliasesRequest; import org.opensearch.action.admin.indices.alias.get.GetAliasesRequest; import org.opensearch.action.admin.indices.cache.clear.ClearIndicesCacheRequest; @@ -88,7 +87,8 @@ final class IndicesRequestConverters { static Request putDataStream(CreateDataStreamRequest createDataStreamRequest) { String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_data_stream") - .addPathPart(createDataStreamRequest.getName()).build(); + .addPathPart(createDataStreamRequest.getName()) + .build(); Request request = new Request(HttpPut.METHOD_NAME, endpoint); return request; } @@ -101,8 +101,7 @@ final class IndicesRequestConverters { } static Request getDataStreams(GetDataStreamRequest dataStreamRequest) { - final String endpoint = new RequestConverters.EndpointBuilder() - .addPathPartAsIs("_data_stream") + final String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_data_stream") .addPathPart(dataStreamRequest.getName()) .build(); return new Request(HttpGet.METHOD_NAME, endpoint); @@ -110,8 +109,7 @@ final class IndicesRequestConverters { static Request dataStreamsStats(DataStreamsStatsRequest dataStreamsStatsRequest) { String[] expressions = dataStreamsStatsRequest.indices() == null ? Strings.EMPTY_ARRAY : dataStreamsStatsRequest.indices(); - final String endpoint = new RequestConverters.EndpointBuilder() - .addPathPartAsIs("_data_stream") + final String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_data_stream") .addCommaSeparatedPathParts(expressions) .addPathPartAsIs("_stats") .build(); @@ -156,8 +154,7 @@ final class IndicesRequestConverters { } static Request createIndex(CreateIndexRequest createIndexRequest) throws IOException { - String endpoint = new RequestConverters.EndpointBuilder() - .addPathPart(createIndexRequest.index()).build(); + String endpoint = new RequestConverters.EndpointBuilder().addPathPart(createIndexRequest.index()).build(); Request request = new Request(HttpPut.METHOD_NAME, endpoint); RequestConverters.Params parameters = new RequestConverters.Params(); @@ -169,8 +166,7 @@ final class IndicesRequestConverters { return request; } - static Request createIndex(org.opensearch.action.admin.indices.create.CreateIndexRequest createIndexRequest) - throws IOException { + static Request createIndex(org.opensearch.action.admin.indices.create.CreateIndexRequest createIndexRequest) throws IOException { String endpoint = RequestConverters.endpoint(createIndexRequest.indices()); Request request = new Request(HttpPut.METHOD_NAME, endpoint); @@ -195,7 +191,6 @@ final class IndicesRequestConverters { return request; } - static Request putMapping(PutMappingRequest putMappingRequest) throws IOException { Request request = new Request(HttpPut.METHOD_NAME, RequestConverters.endpoint(putMappingRequest.indices(), "_mapping")); @@ -219,8 +214,10 @@ final class IndicesRequestConverters { throw new IllegalArgumentException("concreteIndex cannot be set on PutMapping requests made over the REST API"); } - Request request = new Request(HttpPut.METHOD_NAME, RequestConverters.endpoint(putMappingRequest.indices(), - "_mapping", putMappingRequest.type())); + Request request = new Request( + HttpPut.METHOD_NAME, + RequestConverters.endpoint(putMappingRequest.indices(), "_mapping", putMappingRequest.type()) + ); RequestConverters.Params parameters = new RequestConverters.Params(); parameters.withTimeout(putMappingRequest.timeout()); @@ -264,8 +261,7 @@ final class IndicesRequestConverters { String[] indices = getFieldMappingsRequest.indices() == null ? Strings.EMPTY_ARRAY : getFieldMappingsRequest.indices(); String[] fields = getFieldMappingsRequest.fields() == null ? Strings.EMPTY_ARRAY : getFieldMappingsRequest.fields(); - String endpoint = new RequestConverters.EndpointBuilder() - .addCommaSeparatedPathParts(indices) + String endpoint = new RequestConverters.EndpointBuilder().addCommaSeparatedPathParts(indices) .addPathPartAsIs("_mapping") .addPathPartAsIs("field") .addCommaSeparatedPathParts(fields) @@ -287,8 +283,10 @@ final class IndicesRequestConverters { String[] fields = getFieldMappingsRequest.fields() == null ? Strings.EMPTY_ARRAY : getFieldMappingsRequest.fields(); String endpoint = new RequestConverters.EndpointBuilder().addCommaSeparatedPathParts(indices) - .addPathPartAsIs("_mapping").addCommaSeparatedPathParts(types) - .addPathPartAsIs("field").addCommaSeparatedPathParts(fields) + .addPathPartAsIs("_mapping") + .addCommaSeparatedPathParts(types) + .addPathPartAsIs("field") + .addCommaSeparatedPathParts(fields) .build(); Request request = new Request(HttpGet.METHOD_NAME, endpoint); @@ -347,7 +345,7 @@ final class IndicesRequestConverters { } static Request clearCache(ClearIndicesCacheRequest clearIndicesCacheRequest) { - String[] indices = clearIndicesCacheRequest.indices() == null ? Strings.EMPTY_ARRAY :clearIndicesCacheRequest.indices(); + String[] indices = clearIndicesCacheRequest.indices() == null ? Strings.EMPTY_ARRAY : clearIndicesCacheRequest.indices(); Request request = new Request(HttpPost.METHOD_NAME, RequestConverters.endpoint(indices, "_cache/clear")); RequestConverters.Params parameters = new RequestConverters.Params(); @@ -361,8 +359,8 @@ final class IndicesRequestConverters { } static Request existsAlias(GetAliasesRequest getAliasesRequest) { - if ((getAliasesRequest.indices() == null || getAliasesRequest.indices().length == 0) && - (getAliasesRequest.aliases() == null || getAliasesRequest.aliases().length == 0)) { + if ((getAliasesRequest.indices() == null || getAliasesRequest.indices().length == 0) + && (getAliasesRequest.aliases() == null || getAliasesRequest.aliases().length == 0)) { throw new IllegalArgumentException("existsAlias requires at least an alias or an index"); } String[] indices = getAliasesRequest.indices() == null ? Strings.EMPTY_ARRAY : getAliasesRequest.indices(); @@ -418,8 +416,9 @@ final class IndicesRequestConverters { private static Request resize(ResizeRequest resizeRequest, ResizeType type) throws IOException { String endpoint = new RequestConverters.EndpointBuilder().addPathPart(resizeRequest.getSourceIndex()) - .addPathPartAsIs("_" + type.name().toLowerCase(Locale.ROOT)) - .addPathPart(resizeRequest.getTargetIndex()).build(); + .addPathPartAsIs("_" + type.name().toLowerCase(Locale.ROOT)) + .addPathPart(resizeRequest.getTargetIndex()) + .build(); Request request = new Request(HttpPut.METHOD_NAME, endpoint); RequestConverters.Params params = new RequestConverters.Params(); @@ -435,7 +434,8 @@ final class IndicesRequestConverters { private static Request resize(org.opensearch.action.admin.indices.shrink.ResizeRequest resizeRequest) throws IOException { String endpoint = new RequestConverters.EndpointBuilder().addPathPart(resizeRequest.getSourceIndex()) .addPathPartAsIs("_" + resizeRequest.getResizeType().name().toLowerCase(Locale.ROOT)) - .addPathPart(resizeRequest.getTargetIndexRequest().index()).build(); + .addPathPart(resizeRequest.getTargetIndexRequest().index()) + .build(); Request request = new Request(HttpPut.METHOD_NAME, endpoint); RequestConverters.Params params = new RequestConverters.Params(); @@ -448,8 +448,10 @@ final class IndicesRequestConverters { } static Request rollover(RolloverRequest rolloverRequest) throws IOException { - String endpoint = new RequestConverters.EndpointBuilder().addPathPart(rolloverRequest.getAlias()).addPathPartAsIs("_rollover") - .addPathPart(rolloverRequest.getNewIndexName()).build(); + String endpoint = new RequestConverters.EndpointBuilder().addPathPart(rolloverRequest.getAlias()) + .addPathPartAsIs("_rollover") + .addPathPart(rolloverRequest.getNewIndexName()) + .build(); Request request = new Request(HttpPost.METHOD_NAME, endpoint); RequestConverters.Params params = new RequestConverters.Params(); @@ -467,7 +469,9 @@ final class IndicesRequestConverters { @Deprecated static Request rollover(org.opensearch.action.admin.indices.rollover.RolloverRequest rolloverRequest) throws IOException { String endpoint = new RequestConverters.EndpointBuilder().addPathPart(rolloverRequest.getRolloverTarget()) - .addPathPartAsIs("_rollover").addPathPart(rolloverRequest.getNewIndexName()).build(); + .addPathPartAsIs("_rollover") + .addPathPart(rolloverRequest.getNewIndexName()) + .build(); Request request = new Request(HttpPost.METHOD_NAME, endpoint); RequestConverters.Params params = new RequestConverters.Params(); @@ -597,9 +601,10 @@ final class IndicesRequestConverters { */ @Deprecated static Request putTemplate(org.opensearch.action.admin.indices.template.put.PutIndexTemplateRequest putIndexTemplateRequest) - throws IOException { + throws IOException { String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_template") - .addPathPart(putIndexTemplateRequest.name()).build(); + .addPathPart(putIndexTemplateRequest.name()) + .build(); Request request = new Request(HttpPut.METHOD_NAME, endpoint); RequestConverters.Params params = new RequestConverters.Params(); params.withMasterTimeout(putIndexTemplateRequest.masterNodeTimeout()); @@ -617,7 +622,8 @@ final class IndicesRequestConverters { static Request putTemplate(PutIndexTemplateRequest putIndexTemplateRequest) throws IOException { String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_template") - .addPathPart(putIndexTemplateRequest.name()).build(); + .addPathPart(putIndexTemplateRequest.name()) + .build(); Request request = new Request(HttpPut.METHOD_NAME, endpoint); RequestConverters.Params params = new RequestConverters.Params(); params.withMasterTimeout(putIndexTemplateRequest.masterNodeTimeout()); @@ -634,7 +640,8 @@ final class IndicesRequestConverters { static Request putIndexTemplate(PutComposableIndexTemplateRequest putIndexTemplateRequest) throws IOException { String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_index_template") - .addPathPart(putIndexTemplateRequest.name()).build(); + .addPathPart(putIndexTemplateRequest.name()) + .build(); Request request = new Request(HttpPut.METHOD_NAME, endpoint); RequestConverters.Params params = new RequestConverters.Params(); params.withMasterTimeout(putIndexTemplateRequest.masterNodeTimeout()); @@ -651,7 +658,8 @@ final class IndicesRequestConverters { static Request simulateIndexTemplate(SimulateIndexTemplateRequest simulateIndexTemplateRequest) throws IOException { String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_index_template", "_simulate_index") - .addPathPart(simulateIndexTemplateRequest.indexName()).build(); + .addPathPart(simulateIndexTemplateRequest.indexName()) + .build(); Request request = new Request(HttpPost.METHOD_NAME, endpoint); RequestConverters.Params params = new RequestConverters.Params(); params.withMasterTimeout(simulateIndexTemplateRequest.masterNodeTimeout()); @@ -663,8 +671,9 @@ final class IndicesRequestConverters { if (Strings.hasText(putComposableIndexTemplateRequest.cause())) { params.putParam("cause", putComposableIndexTemplateRequest.cause()); } - request.setEntity(RequestConverters.createEntity(putComposableIndexTemplateRequest, - RequestConverters.REQUEST_BODY_CONTENT_TYPE)); + request.setEntity( + RequestConverters.createEntity(putComposableIndexTemplateRequest, RequestConverters.REQUEST_BODY_CONTENT_TYPE) + ); } request.addParameters(params.asMap()); return request; @@ -707,8 +716,7 @@ final class IndicesRequestConverters { } private static Request getTemplates(GetIndexTemplatesRequest getIndexTemplatesRequest, boolean includeTypeName) { - final String endpoint = new RequestConverters.EndpointBuilder() - .addPathPartAsIs("_template") + final String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_template") .addCommaSeparatedPathParts(getIndexTemplatesRequest.names()) .build(); final Request request = new Request(HttpGet.METHOD_NAME, endpoint); @@ -723,8 +731,7 @@ final class IndicesRequestConverters { } static Request getIndexTemplates(GetComposableIndexTemplateRequest getIndexTemplatesRequest) { - final String endpoint = new RequestConverters.EndpointBuilder() - .addPathPartAsIs("_index_template") + final String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_index_template") .addPathPart(getIndexTemplatesRequest.name()) .build(); final Request request = new Request(HttpGet.METHOD_NAME, endpoint); @@ -736,8 +743,7 @@ final class IndicesRequestConverters { } static Request templatesExist(IndexTemplatesExistRequest indexTemplatesExistRequest) { - final String endpoint = new RequestConverters.EndpointBuilder() - .addPathPartAsIs("_template") + final String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_template") .addCommaSeparatedPathParts(indexTemplatesExistRequest.names()) .build(); final Request request = new Request(HttpHead.METHOD_NAME, endpoint); @@ -749,8 +755,7 @@ final class IndicesRequestConverters { } static Request templatesExist(ComposableIndexTemplateExistRequest indexTemplatesExistRequest) { - final String endpoint = new RequestConverters.EndpointBuilder() - .addPathPartAsIs("_index_template") + final String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_index_template") .addPathPart(indexTemplatesExistRequest.name()) .build(); final Request request = new Request(HttpHead.METHOD_NAME, endpoint); @@ -794,10 +799,10 @@ final class IndicesRequestConverters { } static Request deleteAlias(DeleteAliasRequest deleteAliasRequest) { - String endpoint = new RequestConverters.EndpointBuilder() - .addPathPart(deleteAliasRequest.getIndex()) + String endpoint = new RequestConverters.EndpointBuilder().addPathPart(deleteAliasRequest.getIndex()) .addPathPartAsIs("_alias") - .addPathPart(deleteAliasRequest.getAlias()).build(); + .addPathPart(deleteAliasRequest.getAlias()) + .build(); Request request = new Request(HttpDelete.METHOD_NAME, endpoint); RequestConverters.Params parameters = new RequestConverters.Params(); parameters.withTimeout(deleteAliasRequest.timeout()); diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/IngestClient.java b/client/rest-high-level/src/main/java/org/opensearch/client/IngestClient.java index ca79325ba37..93dd3513a46 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/IngestClient.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/IngestClient.java @@ -32,8 +32,6 @@ package org.opensearch.client; -import org.opensearch.client.Cancellable; -import org.opensearch.client.RequestOptions; import org.opensearch.action.ActionListener; import org.opensearch.action.ingest.DeletePipelineRequest; import org.opensearch.action.ingest.GetPipelineRequest; @@ -69,8 +67,13 @@ public final class IngestClient { * @throws IOException in case there is a problem sending the request or parsing back the response */ public AcknowledgedResponse putPipeline(PutPipelineRequest request, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity( request, IngestRequestConverters::putPipeline, options, - AcknowledgedResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + request, + IngestRequestConverters::putPipeline, + options, + AcknowledgedResponse::fromXContent, + emptySet() + ); } /** @@ -82,8 +85,14 @@ public final class IngestClient { * @return cancellable that may be used to cancel the request */ public Cancellable putPipelineAsync(PutPipelineRequest request, RequestOptions options, ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity( request, IngestRequestConverters::putPipeline, options, - AcknowledgedResponse::fromXContent, listener, emptySet()); + return restHighLevelClient.performRequestAsyncAndParseEntity( + request, + IngestRequestConverters::putPipeline, + options, + AcknowledgedResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -95,8 +104,13 @@ public final class IngestClient { * @throws IOException in case there is a problem sending the request or parsing back the response */ public GetPipelineResponse getPipeline(GetPipelineRequest request, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity( request, IngestRequestConverters::getPipeline, options, - GetPipelineResponse::fromXContent, Collections.singleton(404)); + return restHighLevelClient.performRequestAndParseEntity( + request, + IngestRequestConverters::getPipeline, + options, + GetPipelineResponse::fromXContent, + Collections.singleton(404) + ); } /** @@ -108,8 +122,14 @@ public final class IngestClient { * @return cancellable that may be used to cancel the request */ public Cancellable getPipelineAsync(GetPipelineRequest request, RequestOptions options, ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity( request, IngestRequestConverters::getPipeline, options, - GetPipelineResponse::fromXContent, listener, Collections.singleton(404)); + return restHighLevelClient.performRequestAsyncAndParseEntity( + request, + IngestRequestConverters::getPipeline, + options, + GetPipelineResponse::fromXContent, + listener, + Collections.singleton(404) + ); } /** @@ -121,8 +141,13 @@ public final class IngestClient { * @throws IOException in case there is a problem sending the request or parsing back the response */ public AcknowledgedResponse deletePipeline(DeletePipelineRequest request, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity( request, IngestRequestConverters::deletePipeline, options, - AcknowledgedResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + request, + IngestRequestConverters::deletePipeline, + options, + AcknowledgedResponse::fromXContent, + emptySet() + ); } /** @@ -133,11 +158,19 @@ public final class IngestClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable deletePipelineAsync(DeletePipelineRequest request, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity( request, - IngestRequestConverters::deletePipeline, options, - AcknowledgedResponse::fromXContent, listener, emptySet()); + public Cancellable deletePipelineAsync( + DeletePipelineRequest request, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + request, + IngestRequestConverters::deletePipeline, + options, + AcknowledgedResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -150,8 +183,13 @@ public final class IngestClient { * @throws IOException in case there is a problem sending the request or parsing back the response */ public SimulatePipelineResponse simulate(SimulatePipelineRequest request, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity( request, IngestRequestConverters::simulatePipeline, options, - SimulatePipelineResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + request, + IngestRequestConverters::simulatePipeline, + options, + SimulatePipelineResponse::fromXContent, + emptySet() + ); } /** @@ -163,10 +201,18 @@ public final class IngestClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable simulateAsync(SimulatePipelineRequest request, - RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity( request, IngestRequestConverters::simulatePipeline, options, - SimulatePipelineResponse::fromXContent, listener, emptySet()); + public Cancellable simulateAsync( + SimulatePipelineRequest request, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + request, + IngestRequestConverters::simulatePipeline, + options, + SimulatePipelineResponse::fromXContent, + listener, + emptySet() + ); } } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/IngestRequestConverters.java b/client/rest-high-level/src/main/java/org/opensearch/client/IngestRequestConverters.java index fd2137fa1ad..e2ede61f38e 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/IngestRequestConverters.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/IngestRequestConverters.java @@ -40,7 +40,6 @@ import org.opensearch.action.ingest.DeletePipelineRequest; import org.opensearch.action.ingest.GetPipelineRequest; import org.opensearch.action.ingest.PutPipelineRequest; import org.opensearch.action.ingest.SimulatePipelineRequest; -import org.opensearch.client.Request; import java.io.IOException; @@ -49,8 +48,7 @@ final class IngestRequestConverters { private IngestRequestConverters() {} static Request getPipeline(GetPipelineRequest getPipelineRequest) { - String endpoint = new RequestConverters.EndpointBuilder() - .addPathPartAsIs("_ingest/pipeline") + String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_ingest/pipeline") .addCommaSeparatedPathParts(getPipelineRequest.getIds()) .build(); Request request = new Request(HttpGet.METHOD_NAME, endpoint); @@ -62,8 +60,7 @@ final class IngestRequestConverters { } static Request putPipeline(PutPipelineRequest putPipelineRequest) throws IOException { - String endpoint = new RequestConverters.EndpointBuilder() - .addPathPartAsIs("_ingest/pipeline") + String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_ingest/pipeline") .addPathPart(putPipelineRequest.getId()) .build(); Request request = new Request(HttpPut.METHOD_NAME, endpoint); @@ -77,8 +74,7 @@ final class IngestRequestConverters { } static Request deletePipeline(DeletePipelineRequest deletePipelineRequest) { - String endpoint = new RequestConverters.EndpointBuilder() - .addPathPartAsIs("_ingest/pipeline") + String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_ingest/pipeline") .addPathPart(deletePipelineRequest.getId()) .build(); Request request = new Request(HttpDelete.METHOD_NAME, endpoint); diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/NodesResponseHeader.java b/client/rest-high-level/src/main/java/org/opensearch/client/NodesResponseHeader.java index a6a49357632..7b094677986 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/NodesResponseHeader.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/NodesResponseHeader.java @@ -58,23 +58,28 @@ public final class NodesResponseHeader { public static final ParseField FAILURES = new ParseField("failures"); @SuppressWarnings("unchecked") - public static final ConstructingObjectParser PARSER = - new ConstructingObjectParser<>("nodes_response_header", true, - (a) -> { - int i = 0; - int total = (Integer) a[i++]; - int successful = (Integer) a[i++]; - int failed = (Integer) a[i++]; - List failures = (List) a[i++]; - return new NodesResponseHeader(total, successful, failed, failures); - }); + public static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( + "nodes_response_header", + true, + (a) -> { + int i = 0; + int total = (Integer) a[i++]; + int successful = (Integer) a[i++]; + int failed = (Integer) a[i++]; + List failures = (List) a[i++]; + return new NodesResponseHeader(total, successful, failed, failures); + } + ); static { PARSER.declareInt(ConstructingObjectParser.constructorArg(), TOTAL); PARSER.declareInt(ConstructingObjectParser.constructorArg(), SUCCESSFUL); PARSER.declareInt(ConstructingObjectParser.constructorArg(), FAILED); - PARSER.declareObjectArray(ConstructingObjectParser.optionalConstructorArg(), - (p, c) -> OpenSearchException.fromXContent(p), FAILURES); + PARSER.declareObjectArray( + ConstructingObjectParser.optionalConstructorArg(), + (p, c) -> OpenSearchException.fromXContent(p), + FAILURES + ); } private final int total; @@ -135,10 +140,7 @@ public final class NodesResponseHeader { return false; } NodesResponseHeader that = (NodesResponseHeader) o; - return total == that.total && - successful == that.successful && - failed == that.failed && - Objects.equals(failures, that.failures); + return total == that.total && successful == that.successful && failed == that.failed && Objects.equals(failures, that.failures); } @Override diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/RequestConverters.java b/client/rest-high-level/src/main/java/org/opensearch/client/RequestConverters.java index 27a36f8a477..acafcf96c2a 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/RequestConverters.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/RequestConverters.java @@ -243,14 +243,19 @@ final class RequestConverters { BytesReference indexSource = indexRequest.source(); XContentType indexXContentType = indexRequest.getContentType(); - try (XContentParser parser = XContentHelper.createParser( + try ( + XContentParser parser = XContentHelper.createParser( /* * EMPTY and THROW are fine here because we just call * copyCurrentStructure which doesn't touch the * registry or deprecation. */ - NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, - indexSource, indexXContentType)) { + NamedXContentRegistry.EMPTY, + DeprecationHandler.THROW_UNSUPPORTED_OPERATION, + indexSource, + indexXContentType + ) + ) { try (XContentBuilder builder = XContentBuilder.builder(bulkContentType.xContent())) { builder.copyCurrentStructure(parser); source = BytesReference.bytes(builder).toBytesRef(); @@ -398,8 +403,14 @@ final class RequestConverters { if (updateRequest.upsertRequest() != null) { XContentType upsertContentType = updateRequest.upsertRequest().getContentType(); if ((xContentType != null) && (xContentType != upsertContentType)) { - throw new IllegalStateException("Update request cannot have different content types for doc [" + xContentType + "]" + - " and upsert [" + upsertContentType + "] documents"); + throw new IllegalStateException( + "Update request cannot have different content types for doc [" + + xContentType + + "]" + + " and upsert [" + + upsertContentType + + "] documents" + ); } else { xContentType = upsertContentType; } @@ -523,10 +534,10 @@ final class RequestConverters { params.withRouting(countRequest.routing()); params.withPreference(countRequest.preference()); params.withIndicesOptions(countRequest.indicesOptions()); - if (countRequest.terminateAfter() != 0){ + if (countRequest.terminateAfter() != 0) { params.withTerminateAfter(countRequest.terminateAfter()); } - if (countRequest.minScore() != null){ + if (countRequest.minScore() != null) { params.putParam("min_score", String.valueOf(countRequest.minScore())); } request.addParameters(params.asMap()); @@ -551,7 +562,7 @@ final class RequestConverters { } static Request fieldCaps(FieldCapabilitiesRequest fieldCapabilitiesRequest) throws IOException { - String methodName = fieldCapabilitiesRequest.indexFilter() != null ? HttpPost.METHOD_NAME : HttpGet.METHOD_NAME; + String methodName = fieldCapabilitiesRequest.indexFilter() != null ? HttpPost.METHOD_NAME : HttpGet.METHOD_NAME; Request request = new Request(methodName, endpoint(fieldCapabilitiesRequest.indices(), "_field_caps")); Params params = new Params(); @@ -602,8 +613,7 @@ final class RequestConverters { private static Request prepareReindexRequest(ReindexRequest reindexRequest, boolean waitForCompletion) throws IOException { String endpoint = new EndpointBuilder().addPathPart("_reindex").build(); Request request = new Request(HttpPost.METHOD_NAME, endpoint); - Params params = new Params() - .withWaitForCompletion(waitForCompletion) + Params params = new Params().withWaitForCompletion(waitForCompletion) .withRefresh(reindexRequest.isRefresh()) .withTimeout(reindexRequest.getTimeout()) .withWaitForActiveShards(reindexRequest.getWaitForActiveShards()) @@ -618,13 +628,11 @@ final class RequestConverters { return request; } - private static Request prepareDeleteByQueryRequest(DeleteByQueryRequest deleteByQueryRequest, - boolean waitForCompletion) throws IOException { - String endpoint = - endpoint(deleteByQueryRequest.indices(), deleteByQueryRequest.getDocTypes(), "_delete_by_query"); + private static Request prepareDeleteByQueryRequest(DeleteByQueryRequest deleteByQueryRequest, boolean waitForCompletion) + throws IOException { + String endpoint = endpoint(deleteByQueryRequest.indices(), deleteByQueryRequest.getDocTypes(), "_delete_by_query"); Request request = new Request(HttpPost.METHOD_NAME, endpoint); - Params params = new Params() - .withRouting(deleteByQueryRequest.getRouting()) + Params params = new Params().withRouting(deleteByQueryRequest.getRouting()) .withRefresh(deleteByQueryRequest.isRefresh()) .withTimeout(deleteByQueryRequest.getTimeout()) .withWaitForActiveShards(deleteByQueryRequest.getWaitForActiveShards()) @@ -649,13 +657,10 @@ final class RequestConverters { return request; } - static Request prepareUpdateByQueryRequest(UpdateByQueryRequest updateByQueryRequest, - boolean waitForCompletion) throws IOException { - String endpoint = - endpoint(updateByQueryRequest.indices(), updateByQueryRequest.getDocTypes(), "_update_by_query"); + static Request prepareUpdateByQueryRequest(UpdateByQueryRequest updateByQueryRequest, boolean waitForCompletion) throws IOException { + String endpoint = endpoint(updateByQueryRequest.indices(), updateByQueryRequest.getDocTypes(), "_update_by_query"); Request request = new Request(HttpPost.METHOD_NAME, endpoint); - Params params = new Params() - .withRouting(updateByQueryRequest.getRouting()) + Params params = new Params().withRouting(updateByQueryRequest.getRouting()) .withPipeline(updateByQueryRequest.getPipeline()) .withRefresh(updateByQueryRequest.isRefresh()) .withTimeout(updateByQueryRequest.getTimeout()) @@ -694,11 +699,12 @@ final class RequestConverters { } private static Request rethrottle(RethrottleRequest rethrottleRequest, String firstPathPart) { - String endpoint = new EndpointBuilder().addPathPart(firstPathPart).addPathPart(rethrottleRequest.getTaskId().toString()) - .addPathPart("_rethrottle").build(); + String endpoint = new EndpointBuilder().addPathPart(firstPathPart) + .addPathPart(rethrottleRequest.getTaskId().toString()) + .addPathPart("_rethrottle") + .build(); Request request = new Request(HttpPost.METHOD_NAME, endpoint); - Params params = new Params() - .withRequestsPerSecond(rethrottleRequest.getRequestsPerSecond()); + Params params = new Params().withRequestsPerSecond(rethrottleRequest.getRequestsPerSecond()); // we set "group_by" to "none" because this is the response format we can parse back params.putParam("group_by", "none"); request.addParameters(params.asMap()); @@ -807,13 +813,17 @@ final class RequestConverters { } static String endpoint(String[] indices, String[] types, String endpoint) { - return new EndpointBuilder().addCommaSeparatedPathParts(indices).addCommaSeparatedPathParts(types) - .addPathPartAsIs(endpoint).build(); + return new EndpointBuilder().addCommaSeparatedPathParts(indices) + .addCommaSeparatedPathParts(types) + .addPathPartAsIs(endpoint) + .build(); } static String endpoint(String[] indices, String endpoint, String[] suffixes) { - return new EndpointBuilder().addCommaSeparatedPathParts(indices).addPathPartAsIs(endpoint) - .addCommaSeparatedPathParts(suffixes).build(); + return new EndpointBuilder().addCommaSeparatedPathParts(indices) + .addPathPartAsIs(endpoint) + .addCommaSeparatedPathParts(suffixes) + .build(); } static String endpoint(String[] indices, String endpoint, String type) { @@ -836,14 +846,13 @@ final class RequestConverters { * a {@link Request} and adds the parameters to it directly. */ static class Params { - private final Map parameters = new HashMap<>(); + private final Map parameters = new HashMap<>(); - Params() { - } + Params() {} Params putParam(String name, String value) { if (Strings.hasLength(value)) { - parameters.put(name,value); + parameters.put(name, value); } return this; } @@ -855,7 +864,7 @@ final class RequestConverters { return this; } - Map asMap(){ + Map asMap() { return parameters; } @@ -981,7 +990,7 @@ final class RequestConverters { return this; } - Params withTerminateAfter(int terminateAfter){ + Params withTerminateAfter(int terminateAfter) { return putParam("terminate_after", String.valueOf(terminateAfter)); } @@ -1097,7 +1106,7 @@ final class RequestConverters { } Params withNodes(String[] nodes) { - return withNodes(Arrays.asList(nodes)); + return withNodes(Arrays.asList(nodes)); } Params withNodes(List nodes) { @@ -1192,15 +1201,23 @@ final class RequestConverters { static XContentType enforceSameContentType(IndexRequest indexRequest, @Nullable XContentType xContentType) { XContentType requestContentType = indexRequest.getContentType(); if (requestContentType != XContentType.JSON && requestContentType != XContentType.SMILE) { - throw new IllegalArgumentException("Unsupported content-type found for request with content-type [" + requestContentType - + "], only JSON and SMILE are supported"); + throw new IllegalArgumentException( + "Unsupported content-type found for request with content-type [" + + requestContentType + + "], only JSON and SMILE are supported" + ); } if (xContentType == null) { return requestContentType; } if (requestContentType != xContentType) { - throw new IllegalArgumentException("Mismatching content-type found for request with content-type [" + requestContentType - + "], previous requests have content-type [" + xContentType + "]"); + throw new IllegalArgumentException( + "Mismatching content-type found for request with content-type [" + + requestContentType + + "], previous requests have content-type [" + + xContentType + + "]" + ); } return xContentType; } @@ -1231,7 +1248,7 @@ final class RequestConverters { return this; } - EndpointBuilder addPathPartAsIs(String ... parts) { + EndpointBuilder addPathPartAsIs(String... parts) { for (String part : parts) { if (Strings.hasLength(part)) { joiner.add(part); @@ -1246,13 +1263,13 @@ final class RequestConverters { private static String encodePart(String pathPart) { try { - //encode each part (e.g. index, type and id) separately before merging them into the path - //we prepend "/" to the path part to make this path absolute, otherwise there can be issues with - //paths that start with `-` or contain `:` - //the authority must be an empty string and not null, else paths that being with slashes could have them - //misinterpreted as part of the authority. + // encode each part (e.g. index, type and id) separately before merging them into the path + // we prepend "/" to the path part to make this path absolute, otherwise there can be issues with + // paths that start with `-` or contain `:` + // the authority must be an empty string and not null, else paths that being with slashes could have them + // misinterpreted as part of the authority. URI uri = new URI(null, "", "/" + pathPart, null, null); - //manually encode any slash that each part may contain + // manually encode any slash that each part may contain return uri.getRawPath().substring(1).replaceAll("/", "%2F"); } catch (URISyntaxException e) { throw new IllegalArgumentException("Path part [" + pathPart + "] couldn't be encoded", e); @@ -1260,4 +1277,3 @@ final class RequestConverters { } } } - diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/RestHighLevelClient.java b/client/rest-high-level/src/main/java/org/opensearch/client/RestHighLevelClient.java index c08df87f0e9..3eebb361fd9 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/RestHighLevelClient.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/RestHighLevelClient.java @@ -33,14 +33,6 @@ package org.opensearch.client; import org.apache.http.HttpEntity; -import org.opensearch.client.Cancellable; -import org.opensearch.client.Request; -import org.opensearch.client.RequestOptions; -import org.opensearch.client.Response; -import org.opensearch.client.ResponseException; -import org.opensearch.client.ResponseListener; -import org.opensearch.client.RestClient; -import org.opensearch.client.RestClientBuilder; import org.opensearch.OpenSearchException; import org.opensearch.OpenSearchStatusException; import org.opensearch.action.ActionListener; @@ -299,13 +291,18 @@ public class RestHighLevelClient implements Closeable { * The consumer argument allows to control what needs to be done when the {@link #close()} method is called. * Also subclasses can provide parsers for custom response sections added to OpenSearch through plugins. */ - protected RestHighLevelClient(RestClient restClient, CheckedConsumer doClose, - List namedXContentEntries) { + protected RestHighLevelClient( + RestClient restClient, + CheckedConsumer doClose, + List namedXContentEntries + ) { this.client = Objects.requireNonNull(restClient, "restClient must not be null"); this.doClose = Objects.requireNonNull(doClose, "doClose consumer must not be null"); this.registry = new NamedXContentRegistry( - Stream.of(getDefaultNamedXContents().stream(), getProvidedNamedXContents().stream(), namedXContentEntries.stream()) - .flatMap(Function.identity()).collect(toList())); + Stream.of(getDefaultNamedXContents().stream(), getProvidedNamedXContents().stream(), namedXContentEntries.stream()) + .flatMap(Function.identity()) + .collect(toList()) + ); } /** @@ -374,8 +371,14 @@ public class RestHighLevelClient implements Closeable { * @return cancellable that may be used to cancel the request */ public final Cancellable bulkAsync(BulkRequest bulkRequest, RequestOptions options, ActionListener listener) { - return performRequestAsyncAndParseEntity(bulkRequest, RequestConverters::bulk, options, - BulkResponse::fromXContent, listener, emptySet()); + return performRequestAsyncAndParseEntity( + bulkRequest, + RequestConverters::bulk, + options, + BulkResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -386,7 +389,11 @@ public class RestHighLevelClient implements Closeable { */ public final BulkByScrollResponse reindex(ReindexRequest reindexRequest, RequestOptions options) throws IOException { return performRequestAndParseEntity( - reindexRequest, RequestConverters::reindex, options, BulkByScrollResponse::fromXContent, singleton(409) + reindexRequest, + RequestConverters::reindex, + options, + BulkByScrollResponse::fromXContent, + singleton(409) ); } @@ -398,7 +405,11 @@ public class RestHighLevelClient implements Closeable { */ public final TaskSubmissionResponse submitReindexTask(ReindexRequest reindexRequest, RequestOptions options) throws IOException { return performRequestAndParseEntity( - reindexRequest, RequestConverters::submitReindex, options, TaskSubmissionResponse::fromXContent, emptySet() + reindexRequest, + RequestConverters::submitReindex, + options, + TaskSubmissionResponse::fromXContent, + emptySet() ); } @@ -409,10 +420,18 @@ public class RestHighLevelClient implements Closeable { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public final Cancellable reindexAsync(ReindexRequest reindexRequest, RequestOptions options, - ActionListener listener) { + public final Cancellable reindexAsync( + ReindexRequest reindexRequest, + RequestOptions options, + ActionListener listener + ) { return performRequestAsyncAndParseEntity( - reindexRequest, RequestConverters::reindex, options, BulkByScrollResponse::fromXContent, listener, singleton(409) + reindexRequest, + RequestConverters::reindex, + options, + BulkByScrollResponse::fromXContent, + listener, + singleton(409) ); } @@ -425,7 +444,11 @@ public class RestHighLevelClient implements Closeable { */ public final BulkByScrollResponse updateByQuery(UpdateByQueryRequest updateByQueryRequest, RequestOptions options) throws IOException { return performRequestAndParseEntity( - updateByQueryRequest, RequestConverters::updateByQuery, options, BulkByScrollResponse::fromXContent, singleton(409) + updateByQueryRequest, + RequestConverters::updateByQuery, + options, + BulkByScrollResponse::fromXContent, + singleton(409) ); } @@ -436,10 +459,14 @@ public class RestHighLevelClient implements Closeable { * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized * @return the submission response */ - public final TaskSubmissionResponse submitUpdateByQueryTask(UpdateByQueryRequest updateByQueryRequest, - RequestOptions options) throws IOException { + public final TaskSubmissionResponse submitUpdateByQueryTask(UpdateByQueryRequest updateByQueryRequest, RequestOptions options) + throws IOException { return performRequestAndParseEntity( - updateByQueryRequest, RequestConverters::submitUpdateByQuery, options, TaskSubmissionResponse::fromXContent, emptySet() + updateByQueryRequest, + RequestConverters::submitUpdateByQuery, + options, + TaskSubmissionResponse::fromXContent, + emptySet() ); } @@ -451,10 +478,18 @@ public class RestHighLevelClient implements Closeable { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public final Cancellable updateByQueryAsync(UpdateByQueryRequest updateByQueryRequest, RequestOptions options, - ActionListener listener) { + public final Cancellable updateByQueryAsync( + UpdateByQueryRequest updateByQueryRequest, + RequestOptions options, + ActionListener listener + ) { return performRequestAsyncAndParseEntity( - updateByQueryRequest, RequestConverters::updateByQuery, options, BulkByScrollResponse::fromXContent, listener, singleton(409) + updateByQueryRequest, + RequestConverters::updateByQuery, + options, + BulkByScrollResponse::fromXContent, + listener, + singleton(409) ); } @@ -467,7 +502,11 @@ public class RestHighLevelClient implements Closeable { */ public final BulkByScrollResponse deleteByQuery(DeleteByQueryRequest deleteByQueryRequest, RequestOptions options) throws IOException { return performRequestAndParseEntity( - deleteByQueryRequest, RequestConverters::deleteByQuery, options, BulkByScrollResponse::fromXContent, singleton(409) + deleteByQueryRequest, + RequestConverters::deleteByQuery, + options, + BulkByScrollResponse::fromXContent, + singleton(409) ); } @@ -478,10 +517,14 @@ public class RestHighLevelClient implements Closeable { * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized * @return the submission response */ - public final TaskSubmissionResponse submitDeleteByQueryTask(DeleteByQueryRequest deleteByQueryRequest, - RequestOptions options) throws IOException { + public final TaskSubmissionResponse submitDeleteByQueryTask(DeleteByQueryRequest deleteByQueryRequest, RequestOptions options) + throws IOException { return performRequestAndParseEntity( - deleteByQueryRequest, RequestConverters::submitDeleteByQuery, options, TaskSubmissionResponse::fromXContent, emptySet() + deleteByQueryRequest, + RequestConverters::submitDeleteByQuery, + options, + TaskSubmissionResponse::fromXContent, + emptySet() ); } @@ -493,10 +536,18 @@ public class RestHighLevelClient implements Closeable { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public final Cancellable deleteByQueryAsync(DeleteByQueryRequest deleteByQueryRequest, RequestOptions options, - ActionListener listener) { + public final Cancellable deleteByQueryAsync( + DeleteByQueryRequest deleteByQueryRequest, + RequestOptions options, + ActionListener listener + ) { return performRequestAsyncAndParseEntity( - deleteByQueryRequest, RequestConverters::deleteByQuery, options, BulkByScrollResponse::fromXContent, listener, singleton(409) + deleteByQueryRequest, + RequestConverters::deleteByQuery, + options, + BulkByScrollResponse::fromXContent, + listener, + singleton(409) ); } @@ -508,8 +559,13 @@ public class RestHighLevelClient implements Closeable { * @return the response */ public final ListTasksResponse deleteByQueryRethrottle(RethrottleRequest rethrottleRequest, RequestOptions options) throws IOException { - return performRequestAndParseEntity(rethrottleRequest, RequestConverters::rethrottleDeleteByQuery, options, - ListTasksResponse::fromXContent, emptySet()); + return performRequestAndParseEntity( + rethrottleRequest, + RequestConverters::rethrottleDeleteByQuery, + options, + ListTasksResponse::fromXContent, + emptySet() + ); } /** @@ -520,10 +576,19 @@ public class RestHighLevelClient implements Closeable { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public final Cancellable deleteByQueryRethrottleAsync(RethrottleRequest rethrottleRequest, RequestOptions options, - ActionListener listener) { - return performRequestAsyncAndParseEntity(rethrottleRequest, RequestConverters::rethrottleDeleteByQuery, options, - ListTasksResponse::fromXContent, listener, emptySet()); + public final Cancellable deleteByQueryRethrottleAsync( + RethrottleRequest rethrottleRequest, + RequestOptions options, + ActionListener listener + ) { + return performRequestAsyncAndParseEntity( + rethrottleRequest, + RequestConverters::rethrottleDeleteByQuery, + options, + ListTasksResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -534,8 +599,13 @@ public class RestHighLevelClient implements Closeable { * @return the response */ public final ListTasksResponse updateByQueryRethrottle(RethrottleRequest rethrottleRequest, RequestOptions options) throws IOException { - return performRequestAndParseEntity(rethrottleRequest, RequestConverters::rethrottleUpdateByQuery, options, - ListTasksResponse::fromXContent, emptySet()); + return performRequestAndParseEntity( + rethrottleRequest, + RequestConverters::rethrottleUpdateByQuery, + options, + ListTasksResponse::fromXContent, + emptySet() + ); } /** @@ -546,10 +616,19 @@ public class RestHighLevelClient implements Closeable { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public final Cancellable updateByQueryRethrottleAsync(RethrottleRequest rethrottleRequest, RequestOptions options, - ActionListener listener) { - return performRequestAsyncAndParseEntity(rethrottleRequest, RequestConverters::rethrottleUpdateByQuery, options, - ListTasksResponse::fromXContent, listener, emptySet()); + public final Cancellable updateByQueryRethrottleAsync( + RethrottleRequest rethrottleRequest, + RequestOptions options, + ActionListener listener + ) { + return performRequestAsyncAndParseEntity( + rethrottleRequest, + RequestConverters::rethrottleUpdateByQuery, + options, + ListTasksResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -560,8 +639,13 @@ public class RestHighLevelClient implements Closeable { * @return the response */ public final ListTasksResponse reindexRethrottle(RethrottleRequest rethrottleRequest, RequestOptions options) throws IOException { - return performRequestAndParseEntity(rethrottleRequest, RequestConverters::rethrottleReindex, options, - ListTasksResponse::fromXContent, emptySet()); + return performRequestAndParseEntity( + rethrottleRequest, + RequestConverters::rethrottleReindex, + options, + ListTasksResponse::fromXContent, + emptySet() + ); } /** @@ -572,10 +656,19 @@ public class RestHighLevelClient implements Closeable { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public final Cancellable reindexRethrottleAsync(RethrottleRequest rethrottleRequest, RequestOptions options, - ActionListener listener) { - return performRequestAsyncAndParseEntity(rethrottleRequest, - RequestConverters::rethrottleReindex, options, ListTasksResponse::fromXContent, listener, emptySet()); + public final Cancellable reindexRethrottleAsync( + RethrottleRequest rethrottleRequest, + RequestOptions options, + ActionListener listener + ) { + return performRequestAsyncAndParseEntity( + rethrottleRequest, + RequestConverters::rethrottleReindex, + options, + ListTasksResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -584,8 +677,13 @@ public class RestHighLevelClient implements Closeable { * @return true if the ping succeeded, false otherwise */ public final boolean ping(RequestOptions options) throws IOException { - return performRequest(new MainRequest(), (request) -> RequestConverters.ping(), options, RestHighLevelClient::convertExistsResponse, - emptySet()); + return performRequest( + new MainRequest(), + (request) -> RequestConverters.ping(), + options, + RestHighLevelClient::convertExistsResponse, + emptySet() + ); } /** @@ -594,8 +692,13 @@ public class RestHighLevelClient implements Closeable { * @return the response */ public final MainResponse info(RequestOptions options) throws IOException { - return performRequestAndParseEntity(new MainRequest(), (request) -> RequestConverters.info(), options, - MainResponse::fromXContent, emptySet()); + return performRequestAndParseEntity( + new MainRequest(), + (request) -> RequestConverters.info(), + options, + MainResponse::fromXContent, + emptySet() + ); } /** @@ -618,8 +721,14 @@ public class RestHighLevelClient implements Closeable { * @return cancellable that may be used to cancel the request */ public final Cancellable getAsync(GetRequest getRequest, RequestOptions options, ActionListener listener) { - return performRequestAsyncAndParseEntity(getRequest, RequestConverters::get, options, GetResponse::fromXContent, listener, - singleton(404)); + return performRequestAsyncAndParseEntity( + getRequest, + RequestConverters::get, + options, + GetResponse::fromXContent, + listener, + singleton(404) + ); } /** @@ -635,7 +744,6 @@ public class RestHighLevelClient implements Closeable { return mget(multiGetRequest, options); } - /** * Retrieves multiple documents by id using the Multi Get API. * @@ -644,8 +752,13 @@ public class RestHighLevelClient implements Closeable { * @return the response */ public final MultiGetResponse mget(MultiGetRequest multiGetRequest, RequestOptions options) throws IOException { - return performRequestAndParseEntity(multiGetRequest, RequestConverters::multiGet, options, MultiGetResponse::fromXContent, - singleton(404)); + return performRequestAndParseEntity( + multiGetRequest, + RequestConverters::multiGet, + options, + MultiGetResponse::fromXContent, + singleton(404) + ); } /** @@ -658,8 +771,11 @@ public class RestHighLevelClient implements Closeable { * @return cancellable that may be used to cancel the request */ @Deprecated - public final Cancellable multiGetAsync(MultiGetRequest multiGetRequest, RequestOptions options, - ActionListener listener) { + public final Cancellable multiGetAsync( + MultiGetRequest multiGetRequest, + RequestOptions options, + ActionListener listener + ) { return mgetAsync(multiGetRequest, options, listener); } @@ -671,10 +787,15 @@ public class RestHighLevelClient implements Closeable { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public final Cancellable mgetAsync(MultiGetRequest multiGetRequest, RequestOptions options, - ActionListener listener) { - return performRequestAsyncAndParseEntity(multiGetRequest, RequestConverters::multiGet, options, - MultiGetResponse::fromXContent, listener, singleton(404)); + public final Cancellable mgetAsync(MultiGetRequest multiGetRequest, RequestOptions options, ActionListener listener) { + return performRequestAsyncAndParseEntity( + multiGetRequest, + RequestConverters::multiGet, + options, + MultiGetResponse::fromXContent, + listener, + singleton(404) + ); } /** @@ -697,8 +818,14 @@ public class RestHighLevelClient implements Closeable { * @return cancellable that may be used to cancel the request */ public final Cancellable existsAsync(GetRequest getRequest, RequestOptions options, ActionListener listener) { - return performRequestAsync(getRequest, RequestConverters::exists, options, RestHighLevelClient::convertExistsResponse, listener, - emptySet()); + return performRequestAsync( + getRequest, + RequestConverters::exists, + options, + RestHighLevelClient::convertExistsResponse, + listener, + emptySet() + ); } /** @@ -712,8 +839,13 @@ public class RestHighLevelClient implements Closeable { @Deprecated public boolean existsSource(GetRequest getRequest, RequestOptions options) throws IOException { GetSourceRequest getSourceRequest = GetSourceRequest.from(getRequest); - return performRequest(getSourceRequest, RequestConverters::sourceExists, options, - RestHighLevelClient::convertExistsResponse, emptySet()); + return performRequest( + getSourceRequest, + RequestConverters::sourceExists, + options, + RestHighLevelClient::convertExistsResponse, + emptySet() + ); } /** @@ -728,8 +860,14 @@ public class RestHighLevelClient implements Closeable { @Deprecated public final Cancellable existsSourceAsync(GetRequest getRequest, RequestOptions options, ActionListener listener) { GetSourceRequest getSourceRequest = GetSourceRequest.from(getRequest); - return performRequestAsync(getSourceRequest, RequestConverters::sourceExists, options, - RestHighLevelClient::convertExistsResponse, listener, emptySet()); + return performRequestAsync( + getSourceRequest, + RequestConverters::sourceExists, + options, + RestHighLevelClient::convertExistsResponse, + listener, + emptySet() + ); } /** @@ -740,8 +878,13 @@ public class RestHighLevelClient implements Closeable { * @return true if the document and _source field exists, false otherwise */ public boolean existsSource(GetSourceRequest getSourceRequest, RequestOptions options) throws IOException { - return performRequest(getSourceRequest, RequestConverters::sourceExists, options, - RestHighLevelClient::convertExistsResponse, emptySet()); + return performRequest( + getSourceRequest, + RequestConverters::sourceExists, + options, + RestHighLevelClient::convertExistsResponse, + emptySet() + ); } /** @@ -752,10 +895,19 @@ public class RestHighLevelClient implements Closeable { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public final Cancellable existsSourceAsync(GetSourceRequest getSourceRequest, RequestOptions options, - ActionListener listener) { - return performRequestAsync(getSourceRequest, RequestConverters::sourceExists, options, - RestHighLevelClient::convertExistsResponse, listener, emptySet()); + public final Cancellable existsSourceAsync( + GetSourceRequest getSourceRequest, + RequestOptions options, + ActionListener listener + ) { + return performRequestAsync( + getSourceRequest, + RequestConverters::sourceExists, + options, + RestHighLevelClient::convertExistsResponse, + listener, + emptySet() + ); } /** @@ -766,8 +918,13 @@ public class RestHighLevelClient implements Closeable { * @return the response */ public GetSourceResponse getSource(GetSourceRequest getSourceRequest, RequestOptions options) throws IOException { - return performRequestAndParseEntity(getSourceRequest, RequestConverters::getSource, options, - GetSourceResponse::fromXContent, emptySet()); + return performRequestAndParseEntity( + getSourceRequest, + RequestConverters::getSource, + options, + GetSourceResponse::fromXContent, + emptySet() + ); } /** @@ -778,10 +935,19 @@ public class RestHighLevelClient implements Closeable { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public final Cancellable getSourceAsync(GetSourceRequest getSourceRequest, RequestOptions options, - ActionListener listener) { - return performRequestAsyncAndParseEntity(getSourceRequest, RequestConverters::getSource, options, - GetSourceResponse::fromXContent, listener, emptySet()); + public final Cancellable getSourceAsync( + GetSourceRequest getSourceRequest, + RequestOptions options, + ActionListener listener + ) { + return performRequestAsyncAndParseEntity( + getSourceRequest, + RequestConverters::getSource, + options, + GetSourceResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -792,8 +958,7 @@ public class RestHighLevelClient implements Closeable { * @return the response */ public final IndexResponse index(IndexRequest indexRequest, RequestOptions options) throws IOException { - return performRequestAndParseEntity(indexRequest, RequestConverters::index, options, - IndexResponse::fromXContent, emptySet()); + return performRequestAndParseEntity(indexRequest, RequestConverters::index, options, IndexResponse::fromXContent, emptySet()); } /** @@ -805,8 +970,14 @@ public class RestHighLevelClient implements Closeable { * @return cancellable that may be used to cancel the request */ public final Cancellable indexAsync(IndexRequest indexRequest, RequestOptions options, ActionListener listener) { - return performRequestAsyncAndParseEntity(indexRequest, RequestConverters::index, options, IndexResponse::fromXContent, listener, - emptySet()); + return performRequestAsyncAndParseEntity( + indexRequest, + RequestConverters::index, + options, + IndexResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -817,8 +988,7 @@ public class RestHighLevelClient implements Closeable { * @return the response */ public final CountResponse count(CountRequest countRequest, RequestOptions options) throws IOException { - return performRequestAndParseEntity(countRequest, RequestConverters::count, options, CountResponse::fromXContent, - emptySet()); + return performRequestAndParseEntity(countRequest, RequestConverters::count, options, CountResponse::fromXContent, emptySet()); } /** @@ -830,8 +1000,14 @@ public class RestHighLevelClient implements Closeable { * @return cancellable that may be used to cancel the request */ public final Cancellable countAsync(CountRequest countRequest, RequestOptions options, ActionListener listener) { - return performRequestAsyncAndParseEntity(countRequest, RequestConverters::count, options,CountResponse::fromXContent, - listener, emptySet()); + return performRequestAsyncAndParseEntity( + countRequest, + RequestConverters::count, + options, + CountResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -854,8 +1030,14 @@ public class RestHighLevelClient implements Closeable { * @return cancellable that may be used to cancel the request */ public final Cancellable updateAsync(UpdateRequest updateRequest, RequestOptions options, ActionListener listener) { - return performRequestAsyncAndParseEntity(updateRequest, RequestConverters::update, options, UpdateResponse::fromXContent, listener, - emptySet()); + return performRequestAsyncAndParseEntity( + updateRequest, + RequestConverters::update, + options, + UpdateResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -866,8 +1048,13 @@ public class RestHighLevelClient implements Closeable { * @return the response */ public final DeleteResponse delete(DeleteRequest deleteRequest, RequestOptions options) throws IOException { - return performRequestAndParseEntity(deleteRequest, RequestConverters::delete, options, DeleteResponse::fromXContent, - singleton(404)); + return performRequestAndParseEntity( + deleteRequest, + RequestConverters::delete, + options, + DeleteResponse::fromXContent, + singleton(404) + ); } /** @@ -879,8 +1066,14 @@ public class RestHighLevelClient implements Closeable { * @return cancellable that may be used to cancel the request */ public final Cancellable deleteAsync(DeleteRequest deleteRequest, RequestOptions options, ActionListener listener) { - return performRequestAsyncAndParseEntity(deleteRequest, RequestConverters::delete, options, DeleteResponse::fromXContent, listener, - Collections.singleton(404)); + return performRequestAsyncAndParseEntity( + deleteRequest, + RequestConverters::delete, + options, + DeleteResponse::fromXContent, + listener, + Collections.singleton(404) + ); } /** @@ -892,11 +1085,12 @@ public class RestHighLevelClient implements Closeable { */ public final SearchResponse search(SearchRequest searchRequest, RequestOptions options) throws IOException { return performRequestAndParseEntity( - searchRequest, - r -> RequestConverters.search(r, "_search"), - options, - SearchResponse::fromXContent, - emptySet()); + searchRequest, + r -> RequestConverters.search(r, "_search"), + options, + SearchResponse::fromXContent, + emptySet() + ); } /** @@ -909,12 +1103,13 @@ public class RestHighLevelClient implements Closeable { */ public final Cancellable searchAsync(SearchRequest searchRequest, RequestOptions options, ActionListener listener) { return performRequestAsyncAndParseEntity( - searchRequest, - r -> RequestConverters.search(r, "_search"), - options, - SearchResponse::fromXContent, - listener, - emptySet()); + searchRequest, + r -> RequestConverters.search(r, "_search"), + options, + SearchResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -938,8 +1133,13 @@ public class RestHighLevelClient implements Closeable { * @return the response */ public final MultiSearchResponse msearch(MultiSearchRequest multiSearchRequest, RequestOptions options) throws IOException { - return performRequestAndParseEntity(multiSearchRequest, RequestConverters::multiSearch, options, MultiSearchResponse::fromXContext, - emptySet()); + return performRequestAndParseEntity( + multiSearchRequest, + RequestConverters::multiSearch, + options, + MultiSearchResponse::fromXContext, + emptySet() + ); } /** @@ -952,8 +1152,11 @@ public class RestHighLevelClient implements Closeable { * @return cancellable that may be used to cancel the request */ @Deprecated - public final Cancellable multiSearchAsync(MultiSearchRequest searchRequest, RequestOptions options, - ActionListener listener) { + public final Cancellable multiSearchAsync( + MultiSearchRequest searchRequest, + RequestOptions options, + ActionListener listener + ) { return msearchAsync(searchRequest, options, listener); } @@ -965,10 +1168,19 @@ public class RestHighLevelClient implements Closeable { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public final Cancellable msearchAsync(MultiSearchRequest searchRequest, RequestOptions options, - ActionListener listener) { - return performRequestAsyncAndParseEntity(searchRequest, RequestConverters::multiSearch, options, MultiSearchResponse::fromXContext, - listener, emptySet()); + public final Cancellable msearchAsync( + MultiSearchRequest searchRequest, + RequestOptions options, + ActionListener listener + ) { + return performRequestAsyncAndParseEntity( + searchRequest, + RequestConverters::multiSearch, + options, + MultiSearchResponse::fromXContext, + listener, + emptySet() + ); } /** @@ -992,8 +1204,13 @@ public class RestHighLevelClient implements Closeable { * @return the response */ public final SearchResponse scroll(SearchScrollRequest searchScrollRequest, RequestOptions options) throws IOException { - return performRequestAndParseEntity(searchScrollRequest, RequestConverters::searchScroll, options, SearchResponse::fromXContent, - emptySet()); + return performRequestAndParseEntity( + searchScrollRequest, + RequestConverters::searchScroll, + options, + SearchResponse::fromXContent, + emptySet() + ); } /** @@ -1006,8 +1223,11 @@ public class RestHighLevelClient implements Closeable { * @return cancellable that may be used to cancel the request */ @Deprecated - public final Cancellable searchScrollAsync(SearchScrollRequest searchScrollRequest, RequestOptions options, - ActionListener listener) { + public final Cancellable searchScrollAsync( + SearchScrollRequest searchScrollRequest, + RequestOptions options, + ActionListener listener + ) { return scrollAsync(searchScrollRequest, options, listener); } @@ -1019,10 +1239,19 @@ public class RestHighLevelClient implements Closeable { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public final Cancellable scrollAsync(SearchScrollRequest searchScrollRequest, RequestOptions options, - ActionListener listener) { - return performRequestAsyncAndParseEntity(searchScrollRequest, RequestConverters::searchScroll, - options, SearchResponse::fromXContent, listener, emptySet()); + public final Cancellable scrollAsync( + SearchScrollRequest searchScrollRequest, + RequestOptions options, + ActionListener listener + ) { + return performRequestAsyncAndParseEntity( + searchScrollRequest, + RequestConverters::searchScroll, + options, + SearchResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -1033,8 +1262,13 @@ public class RestHighLevelClient implements Closeable { * @return the response */ public final ClearScrollResponse clearScroll(ClearScrollRequest clearScrollRequest, RequestOptions options) throws IOException { - return performRequestAndParseEntity(clearScrollRequest, RequestConverters::clearScroll, options, ClearScrollResponse::fromXContent, - emptySet()); + return performRequestAndParseEntity( + clearScrollRequest, + RequestConverters::clearScroll, + options, + ClearScrollResponse::fromXContent, + emptySet() + ); } /** @@ -1045,10 +1279,19 @@ public class RestHighLevelClient implements Closeable { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public final Cancellable clearScrollAsync(ClearScrollRequest clearScrollRequest, RequestOptions options, - ActionListener listener) { - return performRequestAsyncAndParseEntity(clearScrollRequest, RequestConverters::clearScroll, - options, ClearScrollResponse::fromXContent, listener, emptySet()); + public final Cancellable clearScrollAsync( + ClearScrollRequest clearScrollRequest, + RequestOptions options, + ActionListener listener + ) { + return performRequestAsyncAndParseEntity( + clearScrollRequest, + RequestConverters::clearScroll, + options, + ClearScrollResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -1058,10 +1301,15 @@ public class RestHighLevelClient implements Closeable { * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized * @return the response */ - public final SearchTemplateResponse searchTemplate(SearchTemplateRequest searchTemplateRequest, - RequestOptions options) throws IOException { - return performRequestAndParseEntity(searchTemplateRequest, RequestConverters::searchTemplate, options, - SearchTemplateResponse::fromXContent, emptySet()); + public final SearchTemplateResponse searchTemplate(SearchTemplateRequest searchTemplateRequest, RequestOptions options) + throws IOException { + return performRequestAndParseEntity( + searchTemplateRequest, + RequestConverters::searchTemplate, + options, + SearchTemplateResponse::fromXContent, + emptySet() + ); } /** @@ -1069,10 +1317,19 @@ public class RestHighLevelClient implements Closeable { * * @return cancellable that may be used to cancel the request */ - public final Cancellable searchTemplateAsync(SearchTemplateRequest searchTemplateRequest, RequestOptions options, - ActionListener listener) { - return performRequestAsyncAndParseEntity(searchTemplateRequest, RequestConverters::searchTemplate, options, - SearchTemplateResponse::fromXContent, listener, emptySet()); + public final Cancellable searchTemplateAsync( + SearchTemplateRequest searchTemplateRequest, + RequestOptions options, + ActionListener listener + ) { + return performRequestAsyncAndParseEntity( + searchTemplateRequest, + RequestConverters::searchTemplate, + options, + SearchTemplateResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -1083,13 +1340,13 @@ public class RestHighLevelClient implements Closeable { * @return the response */ public final ExplainResponse explain(ExplainRequest explainRequest, RequestOptions options) throws IOException { - return performRequest(explainRequest, RequestConverters::explain, options, - response -> { - CheckedFunction entityParser = - parser -> ExplainResponse.fromXContent(parser, convertExistsResponse(response)); - return parseEntity(response.getEntity(), entityParser); - }, - singleton(404)); + return performRequest(explainRequest, RequestConverters::explain, options, response -> { + CheckedFunction entityParser = parser -> ExplainResponse.fromXContent( + parser, + convertExistsResponse(response) + ); + return parseEntity(response.getEntity(), entityParser); + }, singleton(404)); } /** @@ -1101,16 +1358,15 @@ public class RestHighLevelClient implements Closeable { * @return cancellable that may be used to cancel the request */ public final Cancellable explainAsync(ExplainRequest explainRequest, RequestOptions options, ActionListener listener) { - return performRequestAsync(explainRequest, RequestConverters::explain, options, - response -> { - CheckedFunction entityParser = - parser -> ExplainResponse.fromXContent(parser, convertExistsResponse(response)); - return parseEntity(response.getEntity(), entityParser); - }, - listener, singleton(404)); + return performRequestAsync(explainRequest, RequestConverters::explain, options, response -> { + CheckedFunction entityParser = parser -> ExplainResponse.fromXContent( + parser, + convertExistsResponse(response) + ); + return parseEntity(response.getEntity(), entityParser); + }, listener, singleton(404)); } - /** * Calls the Term Vectors API * @@ -1118,8 +1374,13 @@ public class RestHighLevelClient implements Closeable { * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized */ public final TermVectorsResponse termvectors(TermVectorsRequest request, RequestOptions options) throws IOException { - return performRequestAndParseEntity(request, RequestConverters::termVectors, options, TermVectorsResponse::fromXContent, - emptySet()); + return performRequestAndParseEntity( + request, + RequestConverters::termVectors, + options, + TermVectorsResponse::fromXContent, + emptySet() + ); } /** @@ -1130,14 +1391,21 @@ public class RestHighLevelClient implements Closeable { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public final Cancellable termvectorsAsync(TermVectorsRequest request, RequestOptions options, - ActionListener listener) { - return performRequestAsyncAndParseEntity(request, RequestConverters::termVectors, options, - TermVectorsResponse::fromXContent, listener, - emptySet()); + public final Cancellable termvectorsAsync( + TermVectorsRequest request, + RequestOptions options, + ActionListener listener + ) { + return performRequestAsyncAndParseEntity( + request, + RequestConverters::termVectors, + options, + TermVectorsResponse::fromXContent, + listener, + emptySet() + ); } - /** * Calls the Multi Term Vectors API * @@ -1146,10 +1414,14 @@ public class RestHighLevelClient implements Closeable { */ public final MultiTermVectorsResponse mtermvectors(MultiTermVectorsRequest request, RequestOptions options) throws IOException { return performRequestAndParseEntity( - request, RequestConverters::mtermVectors, options, MultiTermVectorsResponse::fromXContent, emptySet()); + request, + RequestConverters::mtermVectors, + options, + MultiTermVectorsResponse::fromXContent, + emptySet() + ); } - /** * Asynchronously calls the Multi Term Vectors API * @@ -1158,13 +1430,21 @@ public class RestHighLevelClient implements Closeable { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public final Cancellable mtermvectorsAsync(MultiTermVectorsRequest request, RequestOptions options, - ActionListener listener) { + public final Cancellable mtermvectorsAsync( + MultiTermVectorsRequest request, + RequestOptions options, + ActionListener listener + ) { return performRequestAsyncAndParseEntity( - request, RequestConverters::mtermVectors, options, MultiTermVectorsResponse::fromXContent, listener, emptySet()); + request, + RequestConverters::mtermVectors, + options, + MultiTermVectorsResponse::fromXContent, + listener, + emptySet() + ); } - /** * Executes a request using the Ranking Evaluation API. * @@ -1173,19 +1453,28 @@ public class RestHighLevelClient implements Closeable { * @return the response */ public final RankEvalResponse rankEval(RankEvalRequest rankEvalRequest, RequestOptions options) throws IOException { - return performRequestAndParseEntity(rankEvalRequest, RequestConverters::rankEval, options, RankEvalResponse::fromXContent, - emptySet()); + return performRequestAndParseEntity( + rankEvalRequest, + RequestConverters::rankEval, + options, + RankEvalResponse::fromXContent, + emptySet() + ); } - /** * Executes a request using the Multi Search Template API. * */ - public final MultiSearchTemplateResponse msearchTemplate(MultiSearchTemplateRequest multiSearchTemplateRequest, - RequestOptions options) throws IOException { - return performRequestAndParseEntity(multiSearchTemplateRequest, RequestConverters::multiSearchTemplate, - options, MultiSearchTemplateResponse::fromXContext, emptySet()); + public final MultiSearchTemplateResponse msearchTemplate(MultiSearchTemplateRequest multiSearchTemplateRequest, RequestOptions options) + throws IOException { + return performRequestAndParseEntity( + multiSearchTemplateRequest, + RequestConverters::multiSearchTemplate, + options, + MultiSearchTemplateResponse::fromXContext, + emptySet() + ); } /** @@ -1193,11 +1482,19 @@ public class RestHighLevelClient implements Closeable { * * @return cancellable that may be used to cancel the request */ - public final Cancellable msearchTemplateAsync(MultiSearchTemplateRequest multiSearchTemplateRequest, - RequestOptions options, - ActionListener listener) { - return performRequestAsyncAndParseEntity(multiSearchTemplateRequest, RequestConverters::multiSearchTemplate, - options, MultiSearchTemplateResponse::fromXContext, listener, emptySet()); + public final Cancellable msearchTemplateAsync( + MultiSearchTemplateRequest multiSearchTemplateRequest, + RequestOptions options, + ActionListener listener + ) { + return performRequestAsyncAndParseEntity( + multiSearchTemplateRequest, + RequestConverters::multiSearchTemplate, + options, + MultiSearchTemplateResponse::fromXContext, + listener, + emptySet() + ); } /** @@ -1208,11 +1505,19 @@ public class RestHighLevelClient implements Closeable { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public final Cancellable rankEvalAsync(RankEvalRequest rankEvalRequest, RequestOptions options, - ActionListener listener) { - return performRequestAsyncAndParseEntity(rankEvalRequest, RequestConverters::rankEval, options, - RankEvalResponse::fromXContent, listener, - emptySet()); + public final Cancellable rankEvalAsync( + RankEvalRequest rankEvalRequest, + RequestOptions options, + ActionListener listener + ) { + return performRequestAsyncAndParseEntity( + rankEvalRequest, + RequestConverters::rankEval, + options, + RankEvalResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -1222,10 +1527,15 @@ public class RestHighLevelClient implements Closeable { * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized * @return the response */ - public final FieldCapabilitiesResponse fieldCaps(FieldCapabilitiesRequest fieldCapabilitiesRequest, - RequestOptions options) throws IOException { - return performRequestAndParseEntity(fieldCapabilitiesRequest, RequestConverters::fieldCaps, options, - FieldCapabilitiesResponse::fromXContent, emptySet()); + public final FieldCapabilitiesResponse fieldCaps(FieldCapabilitiesRequest fieldCapabilitiesRequest, RequestOptions options) + throws IOException { + return performRequestAndParseEntity( + fieldCapabilitiesRequest, + RequestConverters::fieldCaps, + options, + FieldCapabilitiesResponse::fromXContent, + emptySet() + ); } /** @@ -1236,8 +1546,13 @@ public class RestHighLevelClient implements Closeable { * @return the response */ public GetStoredScriptResponse getScript(GetStoredScriptRequest request, RequestOptions options) throws IOException { - return performRequestAndParseEntity(request, RequestConverters::getScript, options, - GetStoredScriptResponse::fromXContent, emptySet()); + return performRequestAndParseEntity( + request, + RequestConverters::getScript, + options, + GetStoredScriptResponse::fromXContent, + emptySet() + ); } /** @@ -1248,10 +1563,19 @@ public class RestHighLevelClient implements Closeable { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable getScriptAsync(GetStoredScriptRequest request, RequestOptions options, - ActionListener listener) { - return performRequestAsyncAndParseEntity(request, RequestConverters::getScript, options, - GetStoredScriptResponse::fromXContent, listener, emptySet()); + public Cancellable getScriptAsync( + GetStoredScriptRequest request, + RequestOptions options, + ActionListener listener + ) { + return performRequestAsyncAndParseEntity( + request, + RequestConverters::getScript, + options, + GetStoredScriptResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -1262,8 +1586,13 @@ public class RestHighLevelClient implements Closeable { * @return the response */ public AcknowledgedResponse deleteScript(DeleteStoredScriptRequest request, RequestOptions options) throws IOException { - return performRequestAndParseEntity(request, RequestConverters::deleteScript, options, - AcknowledgedResponse::fromXContent, emptySet()); + return performRequestAndParseEntity( + request, + RequestConverters::deleteScript, + options, + AcknowledgedResponse::fromXContent, + emptySet() + ); } /** @@ -1274,10 +1603,19 @@ public class RestHighLevelClient implements Closeable { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable deleteScriptAsync(DeleteStoredScriptRequest request, RequestOptions options, - ActionListener listener) { - return performRequestAsyncAndParseEntity(request, RequestConverters::deleteScript, options, - AcknowledgedResponse::fromXContent, listener, emptySet()); + public Cancellable deleteScriptAsync( + DeleteStoredScriptRequest request, + RequestOptions options, + ActionListener listener + ) { + return performRequestAsyncAndParseEntity( + request, + RequestConverters::deleteScript, + options, + AcknowledgedResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -1287,10 +1625,14 @@ public class RestHighLevelClient implements Closeable { * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized * @return the response */ - public AcknowledgedResponse putScript(PutStoredScriptRequest putStoredScriptRequest, - RequestOptions options) throws IOException { - return performRequestAndParseEntity(putStoredScriptRequest, RequestConverters::putScript, options, - AcknowledgedResponse::fromXContent, emptySet()); + public AcknowledgedResponse putScript(PutStoredScriptRequest putStoredScriptRequest, RequestOptions options) throws IOException { + return performRequestAndParseEntity( + putStoredScriptRequest, + RequestConverters::putScript, + options, + AcknowledgedResponse::fromXContent, + emptySet() + ); } /** @@ -1301,10 +1643,19 @@ public class RestHighLevelClient implements Closeable { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable putScriptAsync(PutStoredScriptRequest putStoredScriptRequest, RequestOptions options, - ActionListener listener) { - return performRequestAsyncAndParseEntity(putStoredScriptRequest, RequestConverters::putScript, options, - AcknowledgedResponse::fromXContent, listener, emptySet()); + public Cancellable putScriptAsync( + PutStoredScriptRequest putStoredScriptRequest, + RequestOptions options, + ActionListener listener + ) { + return performRequestAsyncAndParseEntity( + putStoredScriptRequest, + RequestConverters::putScript, + options, + AcknowledgedResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -1315,10 +1666,19 @@ public class RestHighLevelClient implements Closeable { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public final Cancellable fieldCapsAsync(FieldCapabilitiesRequest fieldCapabilitiesRequest, RequestOptions options, - ActionListener listener) { - return performRequestAsyncAndParseEntity(fieldCapabilitiesRequest, RequestConverters::fieldCaps, options, - FieldCapabilitiesResponse::fromXContent, listener, emptySet()); + public final Cancellable fieldCapsAsync( + FieldCapabilitiesRequest fieldCapabilitiesRequest, + RequestOptions options, + ActionListener listener + ) { + return performRequestAsyncAndParseEntity( + fieldCapabilitiesRequest, + RequestConverters::fieldCaps, + options, + FieldCapabilitiesResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -1326,25 +1686,27 @@ public class RestHighLevelClient implements Closeable { * layer has been added to the ReST client, and requests should extend {@link Validatable} instead of {@link ActionRequest}. */ @Deprecated - protected final Resp performRequestAndParseEntity(Req request, - CheckedFunction requestConverter, - RequestOptions options, - CheckedFunction entityParser, - Set ignores) throws IOException { - return performRequest(request, requestConverter, options, - response -> parseEntity(response.getEntity(), entityParser), ignores); + protected final Resp performRequestAndParseEntity( + Req request, + CheckedFunction requestConverter, + RequestOptions options, + CheckedFunction entityParser, + Set ignores + ) throws IOException { + return performRequest(request, requestConverter, options, response -> parseEntity(response.getEntity(), entityParser), ignores); } /** * Defines a helper method for performing a request and then parsing the returned entity using the provided entityParser. */ - protected final Resp performRequestAndParseEntity(Req request, - CheckedFunction requestConverter, - RequestOptions options, - CheckedFunction entityParser, - Set ignores) throws IOException { - return performRequest(request, requestConverter, options, - response -> parseEntity(response.getEntity(), entityParser), ignores); + protected final Resp performRequestAndParseEntity( + Req request, + CheckedFunction requestConverter, + RequestOptions options, + CheckedFunction entityParser, + Set ignores + ) throws IOException { + return performRequest(request, requestConverter, options, response -> parseEntity(response.getEntity(), entityParser), ignores); } /** @@ -1352,11 +1714,13 @@ public class RestHighLevelClient implements Closeable { * layer has been added to the ReST client, and requests should extend {@link Validatable} instead of {@link ActionRequest}. */ @Deprecated - protected final Resp performRequest(Req request, - CheckedFunction requestConverter, - RequestOptions options, - CheckedFunction responseConverter, - Set ignores) throws IOException { + protected final Resp performRequest( + Req request, + CheckedFunction requestConverter, + RequestOptions options, + CheckedFunction responseConverter, + Set ignores + ) throws IOException { ActionRequestValidationException validationException = request.validate(); if (validationException != null && validationException.validationErrors().isEmpty() == false) { throw validationException; @@ -1367,11 +1731,13 @@ public class RestHighLevelClient implements Closeable { /** * Defines a helper method for performing a request. */ - protected final Resp performRequest(Req request, - CheckedFunction requestConverter, - RequestOptions options, - CheckedFunction responseConverter, - Set ignores) throws IOException { + protected final Resp performRequest( + Req request, + CheckedFunction requestConverter, + RequestOptions options, + CheckedFunction responseConverter, + Set ignores + ) throws IOException { Optional validationException = request.validate(); if (validationException != null && validationException.isPresent()) { throw validationException.get(); @@ -1382,11 +1748,13 @@ public class RestHighLevelClient implements Closeable { /** * Provides common functionality for performing a request. */ - private Resp internalPerformRequest(Req request, - CheckedFunction requestConverter, - RequestOptions options, - CheckedFunction responseConverter, - Set ignores) throws IOException { + private Resp internalPerformRequest( + Req request, + CheckedFunction requestConverter, + RequestOptions options, + CheckedFunction responseConverter, + Set ignores + ) throws IOException { Request req = requestConverter.apply(request); req.setOptions(options); Response response; @@ -1409,7 +1777,7 @@ public class RestHighLevelClient implements Closeable { try { return responseConverter.apply(response); - } catch(Exception e) { + } catch (Exception e) { throw new IOException("Unable to parse response body for " + response, e); } } @@ -1418,11 +1786,12 @@ public class RestHighLevelClient implements Closeable { * Defines a helper method for requests that can 404 and in which case will return an empty Optional * otherwise tries to parse the response body */ - protected final Optional performRequestAndParseOptionalEntity(Req request, - CheckedFunction requestConverter, - RequestOptions options, - CheckedFunction entityParser - ) throws IOException { + protected final Optional performRequestAndParseOptionalEntity( + Req request, + CheckedFunction requestConverter, + RequestOptions options, + CheckedFunction entityParser + ) throws IOException { Optional validationException = request.validate(); if (validationException != null && validationException.isPresent()) { throw validationException.get(); @@ -1452,40 +1821,60 @@ public class RestHighLevelClient implements Closeable { * @return Cancellable instance that may be used to cancel the request */ @Deprecated - protected final Cancellable performRequestAsyncAndParseEntity(Req request, - CheckedFunction requestConverter, - RequestOptions options, - CheckedFunction entityParser, - ActionListener listener, Set ignores) { - return performRequestAsync(request, requestConverter, options, - response -> parseEntity(response.getEntity(), entityParser), listener, ignores); + protected final Cancellable performRequestAsyncAndParseEntity( + Req request, + CheckedFunction requestConverter, + RequestOptions options, + CheckedFunction entityParser, + ActionListener listener, + Set ignores + ) { + return performRequestAsync( + request, + requestConverter, + options, + response -> parseEntity(response.getEntity(), entityParser), + listener, + ignores + ); } /** * Defines a helper method for asynchronously performing a request. * @return Cancellable instance that may be used to cancel the request */ - protected final Cancellable performRequestAsyncAndParseEntity(Req request, - CheckedFunction requestConverter, - RequestOptions options, - CheckedFunction entityParser, - ActionListener listener, Set ignores) { - return performRequestAsync(request, requestConverter, options, - response -> parseEntity(response.getEntity(), entityParser), listener, ignores); + protected final Cancellable performRequestAsyncAndParseEntity( + Req request, + CheckedFunction requestConverter, + RequestOptions options, + CheckedFunction entityParser, + ActionListener listener, + Set ignores + ) { + return performRequestAsync( + request, + requestConverter, + options, + response -> parseEntity(response.getEntity(), entityParser), + listener, + ignores + ); } - /** * @deprecated If creating a new HLRC ReST API call, consider creating new actions instead of reusing server actions. The Validation * layer has been added to the ReST client, and requests should extend {@link Validatable} instead of {@link ActionRequest}. * @return Cancellable instance that may be used to cancel the request */ @Deprecated - protected final Cancellable performRequestAsync(Req request, - CheckedFunction requestConverter, - RequestOptions options, - CheckedFunction responseConverter, - ActionListener listener, Set ignores) { + protected final Cancellable performRequestAsync( + Req request, + CheckedFunction requestConverter, + RequestOptions options, + CheckedFunction responseConverter, + ActionListener listener, + Set ignores + ) { ActionRequestValidationException validationException = request.validate(); if (validationException != null && validationException.validationErrors().isEmpty() == false) { listener.onFailure(validationException); @@ -1498,11 +1887,14 @@ public class RestHighLevelClient implements Closeable { * Defines a helper method for asynchronously performing a request. * @return Cancellable instance that may be used to cancel the request */ - protected final Cancellable performRequestAsync(Req request, - CheckedFunction requestConverter, - RequestOptions options, - CheckedFunction responseConverter, - ActionListener listener, Set ignores) { + protected final Cancellable performRequestAsync( + Req request, + CheckedFunction requestConverter, + RequestOptions options, + CheckedFunction responseConverter, + ActionListener listener, + Set ignores + ) { Optional validationException = request.validate(); if (validationException != null && validationException.isPresent()) { listener.onFailure(validationException.get()); @@ -1515,11 +1907,14 @@ public class RestHighLevelClient implements Closeable { * Provides common functionality for asynchronously performing a request. * @return Cancellable instance that may be used to cancel the request */ - private Cancellable internalPerformRequestAsync(Req request, - CheckedFunction requestConverter, - RequestOptions options, - CheckedFunction responseConverter, - ActionListener listener, Set ignores) { + private Cancellable internalPerformRequestAsync( + Req request, + CheckedFunction requestConverter, + RequestOptions options, + CheckedFunction responseConverter, + ActionListener listener, + Set ignores + ) { Request req; try { req = requestConverter.apply(request); @@ -1533,15 +1928,17 @@ public class RestHighLevelClient implements Closeable { return client.performRequestAsync(req, responseListener); } - - final ResponseListener wrapResponseListener(CheckedFunction responseConverter, - ActionListener actionListener, Set ignores) { + final ResponseListener wrapResponseListener( + CheckedFunction responseConverter, + ActionListener actionListener, + Set ignores + ) { return new ResponseListener() { @Override public void onSuccess(Response response) { try { actionListener.onResponse(responseConverter.apply(response)); - } catch(Exception e) { + } catch (Exception e) { IOException ioe = new IOException("Unable to parse response body for " + response, e); onFailure(ioe); } @@ -1576,11 +1973,13 @@ public class RestHighLevelClient implements Closeable { * Asynchronous request which returns empty {@link Optional}s in the case of 404s or parses entity into an Optional * @return Cancellable instance that may be used to cancel the request */ - protected final Cancellable performRequestAsyncAndParseOptionalEntity(Req request, - CheckedFunction requestConverter, - RequestOptions options, - CheckedFunction entityParser, - ActionListener> listener) { + protected final Cancellable performRequestAsyncAndParseOptionalEntity( + Req request, + CheckedFunction requestConverter, + RequestOptions options, + CheckedFunction entityParser, + ActionListener> listener + ) { Optional validationException = request.validate(); if (validationException != null && validationException.isPresent()) { listener.onFailure(validationException.get()); @@ -1594,13 +1993,17 @@ public class RestHighLevelClient implements Closeable { return Cancellable.NO_OP; } req.setOptions(options); - ResponseListener responseListener = wrapResponseListener404sOptional(response -> parseEntity(response.getEntity(), - entityParser), listener); + ResponseListener responseListener = wrapResponseListener404sOptional( + response -> parseEntity(response.getEntity(), entityParser), + listener + ); return client.performRequestAsync(req, responseListener); } - final ResponseListener wrapResponseListener404sOptional(CheckedFunction responseConverter, - ActionListener> actionListener) { + final ResponseListener wrapResponseListener404sOptional( + CheckedFunction responseConverter, + ActionListener> actionListener + ) { return new ResponseListener() { @Override public void onSuccess(Response response) { @@ -1618,7 +2021,7 @@ public class RestHighLevelClient implements Closeable { ResponseException responseException = (ResponseException) exception; Response response = responseException.getResponse(); if (RestStatus.NOT_FOUND.getStatus() == response.getStatusLine().getStatusCode()) { - actionListener.onResponse(Optional.empty()); + actionListener.onResponse(Optional.empty()); } else { actionListener.onFailure(parseResponseException(responseException)); } @@ -1643,8 +2046,7 @@ public class RestHighLevelClient implements Closeable { RestStatus restStatus = RestStatus.fromCode(response.getStatusLine().getStatusCode()); if (entity == null) { - opensearchException = new OpenSearchStatusException( - responseException.getMessage(), restStatus, responseException); + opensearchException = new OpenSearchStatusException(responseException.getMessage(), restStatus, responseException); } else { try { opensearchException = parseEntity(entity, BytesRestResponse::errorFromXContent); @@ -1657,8 +2059,8 @@ public class RestHighLevelClient implements Closeable { return opensearchException; } - protected final Resp parseEntity(final HttpEntity entity, - final CheckedFunction entityParser) throws IOException { + protected final Resp parseEntity(final HttpEntity entity, final CheckedFunction entityParser) + throws IOException { if (entity == null) { throw new IllegalStateException("Response body expected but not returned"); } @@ -1707,15 +2109,13 @@ public class RestHighLevelClient implements Closeable { map.put(StatsAggregationBuilder.NAME, (p, c) -> ParsedStats.fromXContent(p, (String) c)); map.put(StatsBucketPipelineAggregationBuilder.NAME, (p, c) -> ParsedStatsBucket.fromXContent(p, (String) c)); map.put(ExtendedStatsAggregationBuilder.NAME, (p, c) -> ParsedExtendedStats.fromXContent(p, (String) c)); - map.put(ExtendedStatsBucketPipelineAggregationBuilder.NAME, - (p, c) -> ParsedExtendedStatsBucket.fromXContent(p, (String) c)); + map.put(ExtendedStatsBucketPipelineAggregationBuilder.NAME, (p, c) -> ParsedExtendedStatsBucket.fromXContent(p, (String) c)); map.put(GeoBoundsAggregationBuilder.NAME, (p, c) -> ParsedGeoBounds.fromXContent(p, (String) c)); map.put(GeoCentroidAggregationBuilder.NAME, (p, c) -> ParsedGeoCentroid.fromXContent(p, (String) c)); map.put(HistogramAggregationBuilder.NAME, (p, c) -> ParsedHistogram.fromXContent(p, (String) c)); map.put(DateHistogramAggregationBuilder.NAME, (p, c) -> ParsedDateHistogram.fromXContent(p, (String) c)); map.put(AutoDateHistogramAggregationBuilder.NAME, (p, c) -> ParsedAutoDateHistogram.fromXContent(p, (String) c)); - map.put(VariableWidthHistogramAggregationBuilder.NAME, - (p, c) -> ParsedVariableWidthHistogram.fromXContent(p, (String) c)); + map.put(VariableWidthHistogramAggregationBuilder.NAME, (p, c) -> ParsedVariableWidthHistogram.fromXContent(p, (String) c)); map.put(StringTerms.NAME, (p, c) -> ParsedStringTerms.fromXContent(p, (String) c)); map.put(LongTerms.NAME, (p, c) -> ParsedLongTerms.fromXContent(p, (String) c)); map.put(DoubleTerms.NAME, (p, c) -> ParsedDoubleTerms.fromXContent(p, (String) c)); @@ -1740,15 +2140,31 @@ public class RestHighLevelClient implements Closeable { map.put(IpRangeAggregationBuilder.NAME, (p, c) -> ParsedBinaryRange.fromXContent(p, (String) c)); map.put(TopHitsAggregationBuilder.NAME, (p, c) -> ParsedTopHits.fromXContent(p, (String) c)); map.put(CompositeAggregationBuilder.NAME, (p, c) -> ParsedComposite.fromXContent(p, (String) c)); - List entries = map.entrySet().stream() - .map(entry -> new NamedXContentRegistry.Entry(Aggregation.class, new ParseField(entry.getKey()), entry.getValue())) - .collect(Collectors.toList()); - entries.add(new NamedXContentRegistry.Entry(Suggest.Suggestion.class, new ParseField(TermSuggestionBuilder.SUGGESTION_NAME), - (parser, context) -> TermSuggestion.fromXContent(parser, (String)context))); - entries.add(new NamedXContentRegistry.Entry(Suggest.Suggestion.class, new ParseField(PhraseSuggestionBuilder.SUGGESTION_NAME), - (parser, context) -> PhraseSuggestion.fromXContent(parser, (String)context))); - entries.add(new NamedXContentRegistry.Entry(Suggest.Suggestion.class, new ParseField(CompletionSuggestionBuilder.SUGGESTION_NAME), - (parser, context) -> CompletionSuggestion.fromXContent(parser, (String)context))); + List entries = map.entrySet() + .stream() + .map(entry -> new NamedXContentRegistry.Entry(Aggregation.class, new ParseField(entry.getKey()), entry.getValue())) + .collect(Collectors.toList()); + entries.add( + new NamedXContentRegistry.Entry( + Suggest.Suggestion.class, + new ParseField(TermSuggestionBuilder.SUGGESTION_NAME), + (parser, context) -> TermSuggestion.fromXContent(parser, (String) context) + ) + ); + entries.add( + new NamedXContentRegistry.Entry( + Suggest.Suggestion.class, + new ParseField(PhraseSuggestionBuilder.SUGGESTION_NAME), + (parser, context) -> PhraseSuggestion.fromXContent(parser, (String) context) + ) + ); + entries.add( + new NamedXContentRegistry.Entry( + Suggest.Suggestion.class, + new ParseField(CompletionSuggestionBuilder.SUGGESTION_NAME), + (parser, context) -> CompletionSuggestion.fromXContent(parser, (String) context) + ) + ); return entries; } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/RethrottleRequest.java b/client/rest-high-level/src/main/java/org/opensearch/client/RethrottleRequest.java index c651d549ee9..958e6ce4cda 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/RethrottleRequest.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/RethrottleRequest.java @@ -63,7 +63,7 @@ public class RethrottleRequest implements Validatable { public RethrottleRequest(TaskId taskId, float requestsPerSecond) { Objects.requireNonNull(taskId, "taskId cannot be null"); if (requestsPerSecond <= 0) { - throw new IllegalArgumentException("requestsPerSecond needs to be positive value but was [" + requestsPerSecond+"]"); + throw new IllegalArgumentException("requestsPerSecond needs to be positive value but was [" + requestsPerSecond + "]"); } this.taskId = taskId; this.requestsPerSecond = requestsPerSecond; @@ -85,6 +85,6 @@ public class RethrottleRequest implements Validatable { @Override public String toString() { - return "RethrottleRequest: taskID = " + taskId +"; reqestsPerSecond = " + requestsPerSecond; + return "RethrottleRequest: taskID = " + taskId + "; reqestsPerSecond = " + requestsPerSecond; } } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/SnapshotClient.java b/client/rest-high-level/src/main/java/org/opensearch/client/SnapshotClient.java index 9ce1f78361d..c702fcda89e 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/SnapshotClient.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/SnapshotClient.java @@ -32,8 +32,6 @@ package org.opensearch.client; -import org.opensearch.client.Cancellable; -import org.opensearch.client.RequestOptions; import org.opensearch.action.ActionListener; import org.opensearch.action.admin.cluster.repositories.cleanup.CleanupRepositoryRequest; import org.opensearch.action.admin.cluster.repositories.cleanup.CleanupRepositoryResponse; @@ -79,10 +77,14 @@ public final class SnapshotClient { * @return the response * @throws IOException in case there is a problem sending the request or parsing back the response */ - public GetRepositoriesResponse getRepository(GetRepositoriesRequest getRepositoriesRequest, RequestOptions options) - throws IOException { - return restHighLevelClient.performRequestAndParseEntity(getRepositoriesRequest, SnapshotRequestConverters::getRepositories, options, - GetRepositoriesResponse::fromXContent, emptySet()); + public GetRepositoriesResponse getRepository(GetRepositoriesRequest getRepositoriesRequest, RequestOptions options) throws IOException { + return restHighLevelClient.performRequestAndParseEntity( + getRepositoriesRequest, + SnapshotRequestConverters::getRepositories, + options, + GetRepositoriesResponse::fromXContent, + emptySet() + ); } /** @@ -94,11 +96,19 @@ public final class SnapshotClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable getRepositoryAsync(GetRepositoriesRequest getRepositoriesRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(getRepositoriesRequest, - SnapshotRequestConverters::getRepositories, options, - GetRepositoriesResponse::fromXContent, listener, emptySet()); + public Cancellable getRepositoryAsync( + GetRepositoriesRequest getRepositoriesRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + getRepositoriesRequest, + SnapshotRequestConverters::getRepositories, + options, + GetRepositoriesResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -110,8 +120,13 @@ public final class SnapshotClient { * @throws IOException in case there is a problem sending the request or parsing back the response */ public AcknowledgedResponse createRepository(PutRepositoryRequest putRepositoryRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(putRepositoryRequest, SnapshotRequestConverters::createRepository, options, - AcknowledgedResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + putRepositoryRequest, + SnapshotRequestConverters::createRepository, + options, + AcknowledgedResponse::fromXContent, + emptySet() + ); } /** @@ -122,11 +137,19 @@ public final class SnapshotClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable createRepositoryAsync(PutRepositoryRequest putRepositoryRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(putRepositoryRequest, - SnapshotRequestConverters::createRepository, options, - AcknowledgedResponse::fromXContent, listener, emptySet()); + public Cancellable createRepositoryAsync( + PutRepositoryRequest putRepositoryRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + putRepositoryRequest, + SnapshotRequestConverters::createRepository, + options, + AcknowledgedResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -139,8 +162,13 @@ public final class SnapshotClient { */ public AcknowledgedResponse deleteRepository(DeleteRepositoryRequest deleteRepositoryRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(deleteRepositoryRequest, SnapshotRequestConverters::deleteRepository, - options, AcknowledgedResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + deleteRepositoryRequest, + SnapshotRequestConverters::deleteRepository, + options, + AcknowledgedResponse::fromXContent, + emptySet() + ); } /** @@ -151,11 +179,19 @@ public final class SnapshotClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable deleteRepositoryAsync(DeleteRepositoryRequest deleteRepositoryRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(deleteRepositoryRequest, - SnapshotRequestConverters::deleteRepository, options, - AcknowledgedResponse::fromXContent, listener, emptySet()); + public Cancellable deleteRepositoryAsync( + DeleteRepositoryRequest deleteRepositoryRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + deleteRepositoryRequest, + SnapshotRequestConverters::deleteRepository, + options, + AcknowledgedResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -168,8 +204,13 @@ public final class SnapshotClient { */ public VerifyRepositoryResponse verifyRepository(VerifyRepositoryRequest verifyRepositoryRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(verifyRepositoryRequest, SnapshotRequestConverters::verifyRepository, - options, VerifyRepositoryResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + verifyRepositoryRequest, + SnapshotRequestConverters::verifyRepository, + options, + VerifyRepositoryResponse::fromXContent, + emptySet() + ); } /** @@ -180,11 +221,19 @@ public final class SnapshotClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable verifyRepositoryAsync(VerifyRepositoryRequest verifyRepositoryRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(verifyRepositoryRequest, - SnapshotRequestConverters::verifyRepository, options, - VerifyRepositoryResponse::fromXContent, listener, emptySet()); + public Cancellable verifyRepositoryAsync( + VerifyRepositoryRequest verifyRepositoryRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + verifyRepositoryRequest, + SnapshotRequestConverters::verifyRepository, + options, + VerifyRepositoryResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -197,8 +246,13 @@ public final class SnapshotClient { */ public CleanupRepositoryResponse cleanupRepository(CleanupRepositoryRequest cleanupRepositoryRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(cleanupRepositoryRequest, SnapshotRequestConverters::cleanupRepository, - options, CleanupRepositoryResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + cleanupRepositoryRequest, + SnapshotRequestConverters::cleanupRepository, + options, + CleanupRepositoryResponse::fromXContent, + emptySet() + ); } /** @@ -209,19 +263,32 @@ public final class SnapshotClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable cleanupRepositoryAsync(CleanupRepositoryRequest cleanupRepositoryRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(cleanupRepositoryRequest, SnapshotRequestConverters::cleanupRepository, - options, CleanupRepositoryResponse::fromXContent, listener, emptySet()); + public Cancellable cleanupRepositoryAsync( + CleanupRepositoryRequest cleanupRepositoryRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + cleanupRepositoryRequest, + SnapshotRequestConverters::cleanupRepository, + options, + CleanupRepositoryResponse::fromXContent, + listener, + emptySet() + ); } /** * Creates a snapshot. */ - public CreateSnapshotResponse create(CreateSnapshotRequest createSnapshotRequest, RequestOptions options) - throws IOException { - return restHighLevelClient.performRequestAndParseEntity(createSnapshotRequest, SnapshotRequestConverters::createSnapshot, options, - CreateSnapshotResponse::fromXContent, emptySet()); + public CreateSnapshotResponse create(CreateSnapshotRequest createSnapshotRequest, RequestOptions options) throws IOException { + return restHighLevelClient.performRequestAndParseEntity( + createSnapshotRequest, + SnapshotRequestConverters::createSnapshot, + options, + CreateSnapshotResponse::fromXContent, + emptySet() + ); } /** @@ -230,20 +297,32 @@ public final class SnapshotClient { * * @return cancellable that may be used to cancel the request */ - public Cancellable createAsync(CreateSnapshotRequest createSnapshotRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(createSnapshotRequest, - SnapshotRequestConverters::createSnapshot, options, - CreateSnapshotResponse::fromXContent, listener, emptySet()); + public Cancellable createAsync( + CreateSnapshotRequest createSnapshotRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + createSnapshotRequest, + SnapshotRequestConverters::createSnapshot, + options, + CreateSnapshotResponse::fromXContent, + listener, + emptySet() + ); } /** * Clones a snapshot. */ - public AcknowledgedResponse clone(CloneSnapshotRequest cloneSnapshotRequest, RequestOptions options) - throws IOException { - return restHighLevelClient.performRequestAndParseEntity(cloneSnapshotRequest, SnapshotRequestConverters::cloneSnapshot, options, - AcknowledgedResponse::fromXContent, emptySet()); + public AcknowledgedResponse clone(CloneSnapshotRequest cloneSnapshotRequest, RequestOptions options) throws IOException { + return restHighLevelClient.performRequestAndParseEntity( + cloneSnapshotRequest, + SnapshotRequestConverters::cloneSnapshot, + options, + AcknowledgedResponse::fromXContent, + emptySet() + ); } /** @@ -252,11 +331,19 @@ public final class SnapshotClient { * * @return cancellable that may be used to cancel the request */ - public Cancellable cloneAsync(CloneSnapshotRequest cloneSnapshotRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(cloneSnapshotRequest, - SnapshotRequestConverters::cloneSnapshot, options, - AcknowledgedResponse::fromXContent, listener, emptySet()); + public Cancellable cloneAsync( + CloneSnapshotRequest cloneSnapshotRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + cloneSnapshotRequest, + SnapshotRequestConverters::cloneSnapshot, + options, + AcknowledgedResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -268,8 +355,13 @@ public final class SnapshotClient { * @throws IOException in case there is a problem sending the request or parsing back the response */ public GetSnapshotsResponse get(GetSnapshotsRequest getSnapshotsRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(getSnapshotsRequest, SnapshotRequestConverters::getSnapshots, options, - GetSnapshotsResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + getSnapshotsRequest, + SnapshotRequestConverters::getSnapshots, + options, + GetSnapshotsResponse::fromXContent, + emptySet() + ); } /** @@ -280,11 +372,19 @@ public final class SnapshotClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable getAsync(GetSnapshotsRequest getSnapshotsRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(getSnapshotsRequest, - SnapshotRequestConverters::getSnapshots, options, - GetSnapshotsResponse::fromXContent, listener, emptySet()); + public Cancellable getAsync( + GetSnapshotsRequest getSnapshotsRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + getSnapshotsRequest, + SnapshotRequestConverters::getSnapshots, + options, + GetSnapshotsResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -295,10 +395,14 @@ public final class SnapshotClient { * @return the response * @throws IOException in case there is a problem sending the request or parsing back the response */ - public SnapshotsStatusResponse status(SnapshotsStatusRequest snapshotsStatusRequest, RequestOptions options) - throws IOException { - return restHighLevelClient.performRequestAndParseEntity(snapshotsStatusRequest, SnapshotRequestConverters::snapshotsStatus, options, - SnapshotsStatusResponse::fromXContent, emptySet()); + public SnapshotsStatusResponse status(SnapshotsStatusRequest snapshotsStatusRequest, RequestOptions options) throws IOException { + return restHighLevelClient.performRequestAndParseEntity( + snapshotsStatusRequest, + SnapshotRequestConverters::snapshotsStatus, + options, + SnapshotsStatusResponse::fromXContent, + emptySet() + ); } /** @@ -309,11 +413,19 @@ public final class SnapshotClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable statusAsync(SnapshotsStatusRequest snapshotsStatusRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(snapshotsStatusRequest, - SnapshotRequestConverters::snapshotsStatus, options, - SnapshotsStatusResponse::fromXContent, listener, emptySet()); + public Cancellable statusAsync( + SnapshotsStatusRequest snapshotsStatusRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + snapshotsStatusRequest, + SnapshotRequestConverters::snapshotsStatus, + options, + SnapshotsStatusResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -325,8 +437,13 @@ public final class SnapshotClient { * @throws IOException in case there is a problem sending the request or parsing back the response */ public RestoreSnapshotResponse restore(RestoreSnapshotRequest restoreSnapshotRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(restoreSnapshotRequest, SnapshotRequestConverters::restoreSnapshot, options, - RestoreSnapshotResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + restoreSnapshotRequest, + SnapshotRequestConverters::restoreSnapshot, + options, + RestoreSnapshotResponse::fromXContent, + emptySet() + ); } /** @@ -337,11 +454,19 @@ public final class SnapshotClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable restoreAsync(RestoreSnapshotRequest restoreSnapshotRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(restoreSnapshotRequest, - SnapshotRequestConverters::restoreSnapshot, options, - RestoreSnapshotResponse::fromXContent, listener, emptySet()); + public Cancellable restoreAsync( + RestoreSnapshotRequest restoreSnapshotRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + restoreSnapshotRequest, + SnapshotRequestConverters::restoreSnapshot, + options, + RestoreSnapshotResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -353,9 +478,13 @@ public final class SnapshotClient { * @throws IOException in case there is a problem sending the request or parsing back the response */ public AcknowledgedResponse delete(DeleteSnapshotRequest deleteSnapshotRequest, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(deleteSnapshotRequest, - SnapshotRequestConverters::deleteSnapshot, options, - AcknowledgedResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + deleteSnapshotRequest, + SnapshotRequestConverters::deleteSnapshot, + options, + AcknowledgedResponse::fromXContent, + emptySet() + ); } /** @@ -366,10 +495,18 @@ public final class SnapshotClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable deleteAsync(DeleteSnapshotRequest deleteSnapshotRequest, RequestOptions options, - ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(deleteSnapshotRequest, - SnapshotRequestConverters::deleteSnapshot, options, - AcknowledgedResponse::fromXContent, listener, emptySet()); + public Cancellable deleteAsync( + DeleteSnapshotRequest deleteSnapshotRequest, + RequestOptions options, + ActionListener listener + ) { + return restHighLevelClient.performRequestAsyncAndParseEntity( + deleteSnapshotRequest, + SnapshotRequestConverters::deleteSnapshot, + options, + AcknowledgedResponse::fromXContent, + listener, + emptySet() + ); } } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/SnapshotRequestConverters.java b/client/rest-high-level/src/main/java/org/opensearch/client/SnapshotRequestConverters.java index c4e62e881f2..3c92bb5ec2a 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/SnapshotRequestConverters.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/SnapshotRequestConverters.java @@ -36,7 +36,6 @@ import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; -import org.opensearch.client.Request; import org.opensearch.action.admin.cluster.repositories.cleanup.CleanupRepositoryRequest; import org.opensearch.action.admin.cluster.repositories.delete.DeleteRepositoryRequest; import org.opensearch.action.admin.cluster.repositories.get.GetRepositoriesRequest; @@ -58,7 +57,8 @@ final class SnapshotRequestConverters { static Request getRepositories(GetRepositoriesRequest getRepositoriesRequest) { String[] repositories = getRepositoriesRequest.repositories() == null ? Strings.EMPTY_ARRAY : getRepositoriesRequest.repositories(); - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_snapshot").addCommaSeparatedPathParts(repositories) + String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_snapshot") + .addCommaSeparatedPathParts(repositories) .build(); Request request = new Request(HttpGet.METHOD_NAME, endpoint); @@ -85,7 +85,8 @@ final class SnapshotRequestConverters { } static Request deleteRepository(DeleteRepositoryRequest deleteRepositoryRequest) { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_snapshot").addPathPart(deleteRepositoryRequest.name()) + String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_snapshot") + .addPathPart(deleteRepositoryRequest.name()) .build(); Request request = new Request(HttpDelete.METHOD_NAME, endpoint); @@ -140,11 +141,11 @@ final class SnapshotRequestConverters { static Request cloneSnapshot(CloneSnapshotRequest cloneSnapshotRequest) throws IOException { String endpoint = new RequestConverters.EndpointBuilder().addPathPart("_snapshot") - .addPathPart(cloneSnapshotRequest.repository()) - .addPathPart(cloneSnapshotRequest.source()) - .addPathPart("_clone") - .addPathPart(cloneSnapshotRequest.target()) - .build(); + .addPathPart(cloneSnapshotRequest.repository()) + .addPathPart(cloneSnapshotRequest.source()) + .addPathPart("_clone") + .addPathPart(cloneSnapshotRequest.target()) + .build(); Request request = new Request(HttpPut.METHOD_NAME, endpoint); RequestConverters.Params params = new RequestConverters.Params(); params.withMasterTimeout(cloneSnapshotRequest.masterNodeTimeout()); diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/SyncedFlushResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/SyncedFlushResponse.java index ba044889a80..a0c94fb7557 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/SyncedFlushResponse.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/SyncedFlushResponse.java @@ -103,7 +103,7 @@ public class SyncedFlushResponse implements ToXContentObject { builder.startObject(SHARDS_FIELD); totalCounts.toXContent(builder, params); builder.endObject(); - for (Map.Entry entry: indexResults.entrySet()) { + for (Map.Entry entry : indexResults.entrySet()) { String indexName = entry.getKey(); IndexResult indexResult = entry.getValue(); builder.startObject(indexName); @@ -132,10 +132,7 @@ public class SyncedFlushResponse implements ToXContentObject { if (totalCounts != null) { return new SyncedFlushResponse(totalCounts, indexResults); } else { - throw new ParsingException( - startLoc, - "Unable to reconstruct object. Total counts for shards couldn't be parsed." - ); + throw new ParsingException(startLoc, "Unable to reconstruct object. Total counts for shards couldn't be parsed."); } } @@ -148,11 +145,10 @@ public class SyncedFlushResponse implements ToXContentObject { public static final String SUCCESSFUL_FIELD = "successful"; public static final String FAILED_FIELD = "failed"; - private static final ConstructingObjectParser PARSER = - new ConstructingObjectParser<>( - "shardcounts", - a -> new ShardCounts((Integer) a[0], (Integer) a[1], (Integer) a[2]) - ); + private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( + "shardcounts", + a -> new ShardCounts((Integer) a[0], (Integer) a[1], (Integer) a[2]) + ); static { PARSER.declareInt(constructorArg(), new ParseField(TOTAL_FIELD)); PARSER.declareInt(constructorArg(), new ParseField(SUCCESSFUL_FIELD)); @@ -163,7 +159,6 @@ public class SyncedFlushResponse implements ToXContentObject { private int successful; private int failed; - ShardCounts(int total, int successful, int failed) { this.total = total; this.successful = successful; @@ -184,10 +179,7 @@ public class SyncedFlushResponse implements ToXContentObject { public boolean equals(ShardCounts other) { if (other != null) { - return - other.total == this.total && - other.successful == this.successful && - other.failed == this.failed; + return other.total == this.total && other.successful == this.successful && other.failed == this.failed; } else { return false; } @@ -207,11 +199,10 @@ public class SyncedFlushResponse implements ToXContentObject { public static final String FAILURES_FIELD = "failures"; @SuppressWarnings("unchecked") - private static final ConstructingObjectParser PARSER = - new ConstructingObjectParser<>( - "indexresult", - a -> new IndexResult((Integer) a[0], (Integer) a[1], (Integer) a[2], (List)a[3]) - ); + private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( + "indexresult", + a -> new IndexResult((Integer) a[0], (Integer) a[1], (Integer) a[2], (List) a[3]) + ); static { PARSER.declareInt(constructorArg(), new ParseField(TOTAL_FIELD)); PARSER.declareInt(constructorArg(), new ParseField(SUCCESSFUL_FIELD)); @@ -297,16 +288,12 @@ public class SyncedFlushResponse implements ToXContentObject { @SuppressWarnings("unchecked") static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( "shardfailure", - a -> new ShardFailure((Integer)a[0], (String)a[1], (Map)a[2]) + a -> new ShardFailure((Integer) a[0], (String) a[1], (Map) a[2]) ); static { PARSER.declareInt(constructorArg(), new ParseField(SHARD_ID_FIELD)); PARSER.declareString(constructorArg(), new ParseField(FAILURE_REASON_FIELD)); - PARSER.declareObject( - optionalConstructorArg(), - (parser, c) -> parser.map(), - new ParseField(ROUTING_FIELD) - ); + PARSER.declareObject(optionalConstructorArg(), (parser, c) -> parser.map(), new ParseField(ROUTING_FIELD)); } ShardFailure(int shardId, String failureReason, Map routing) { diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/TasksClient.java b/client/rest-high-level/src/main/java/org/opensearch/client/TasksClient.java index 8355e2e7c0c..51764e33393 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/TasksClient.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/TasksClient.java @@ -64,8 +64,13 @@ public final class TasksClient { * @throws IOException in case there is a problem sending the request or parsing back the response */ public ListTasksResponse list(ListTasksRequest request, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity(request, TasksRequestConverters::listTasks, options, - ListTasksResponse::fromXContent, emptySet()); + return restHighLevelClient.performRequestAndParseEntity( + request, + TasksRequestConverters::listTasks, + options, + ListTasksResponse::fromXContent, + emptySet() + ); } /** @@ -77,8 +82,14 @@ public final class TasksClient { * @return cancellable that may be used to cancel the request */ public Cancellable listAsync(ListTasksRequest request, RequestOptions options, ActionListener listener) { - return restHighLevelClient.performRequestAsyncAndParseEntity(request, TasksRequestConverters::listTasks, options, - ListTasksResponse::fromXContent, listener, emptySet()); + return restHighLevelClient.performRequestAsyncAndParseEntity( + request, + TasksRequestConverters::listTasks, + options, + ListTasksResponse::fromXContent, + listener, + emptySet() + ); } /** @@ -90,8 +101,12 @@ public final class TasksClient { * @throws IOException in case there is a problem sending the request or parsing back the response */ public Optional get(GetTaskRequest request, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseOptionalEntity(request, TasksRequestConverters::getTask, options, - GetTaskResponse::fromXContent); + return restHighLevelClient.performRequestAndParseOptionalEntity( + request, + TasksRequestConverters::getTask, + options, + GetTaskResponse::fromXContent + ); } /** @@ -102,11 +117,15 @@ public final class TasksClient { * @param listener an actionlistener that takes an optional response (404s are returned as an empty Optional) * @return cancellable that may be used to cancel the request */ - public Cancellable getAsync(GetTaskRequest request, RequestOptions options, - ActionListener> listener) { + public Cancellable getAsync(GetTaskRequest request, RequestOptions options, ActionListener> listener) { - return restHighLevelClient.performRequestAsyncAndParseOptionalEntity(request, TasksRequestConverters::getTask, options, - GetTaskResponse::fromXContent, listener); + return restHighLevelClient.performRequestAsyncAndParseOptionalEntity( + request, + TasksRequestConverters::getTask, + options, + GetTaskResponse::fromXContent, + listener + ); } /** @@ -118,7 +137,7 @@ public final class TasksClient { * @throws IOException in case there is a problem sending the request or parsing back the response * */ - public CancelTasksResponse cancel(CancelTasksRequest cancelTasksRequest, RequestOptions options ) throws IOException { + public CancelTasksResponse cancel(CancelTasksRequest cancelTasksRequest, RequestOptions options) throws IOException { return restHighLevelClient.performRequestAndParseEntity( cancelTasksRequest, TasksRequestConverters::cancelTasks, @@ -136,8 +155,11 @@ public final class TasksClient { * @param listener the listener to be notified upon request completion * @return cancellable that may be used to cancel the request */ - public Cancellable cancelAsync(CancelTasksRequest cancelTasksRequest, RequestOptions options, - ActionListener listener) { + public Cancellable cancelAsync( + CancelTasksRequest cancelTasksRequest, + RequestOptions options, + ActionListener listener + ) { return restHighLevelClient.performRequestAsyncAndParseEntity( cancelTasksRequest, TasksRequestConverters::cancelTasks, diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/TasksRequestConverters.java b/client/rest-high-level/src/main/java/org/opensearch/client/TasksRequestConverters.java index dfbc4d2aac4..ff89950f37c 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/TasksRequestConverters.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/TasksRequestConverters.java @@ -49,9 +49,7 @@ final class TasksRequestConverters { req.getTimeout().ifPresent(params::withTimeout); req.getTaskId().ifPresent(params::withTaskId); req.getParentTaskId().ifPresent(params::withParentTaskId); - params - .withNodes(req.getNodes()) - .withActions(req.getActions()); + params.withNodes(req.getNodes()).withActions(req.getActions()); if (req.getWaitForCompletion() != null) { params.withWaitForCompletion(req.getWaitForCompletion()); } @@ -63,7 +61,7 @@ final class TasksRequestConverters { if (listTaskRequest.getTaskId() != null && listTaskRequest.getTaskId().isSet()) { throw new IllegalArgumentException("TaskId cannot be used for list tasks request"); } - Request request = new Request(HttpGet.METHOD_NAME, "/_tasks"); + Request request = new Request(HttpGet.METHOD_NAME, "/_tasks"); RequestConverters.Params params = new RequestConverters.Params(); params.withTimeout(listTaskRequest.getTimeout()) .withDetailed(listTaskRequest.getDetailed()) @@ -78,12 +76,11 @@ final class TasksRequestConverters { static Request getTask(GetTaskRequest getTaskRequest) { String endpoint = new EndpointBuilder().addPathPartAsIs("_tasks") - .addPathPartAsIs(getTaskRequest.getNodeId() + ":" + Long.toString(getTaskRequest.getTaskId())) - .build(); + .addPathPartAsIs(getTaskRequest.getNodeId() + ":" + Long.toString(getTaskRequest.getTaskId())) + .build(); Request request = new Request(HttpGet.METHOD_NAME, endpoint); RequestConverters.Params params = new RequestConverters.Params(); - params.withTimeout(getTaskRequest.getTimeout()) - .withWaitForCompletion(getTaskRequest.getWaitForCompletion()); + params.withTimeout(getTaskRequest.getTimeout()).withWaitForCompletion(getTaskRequest.getWaitForCompletion()); request.addParameters(params.asMap()); return request; } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/Validatable.java b/client/rest-high-level/src/main/java/org/opensearch/client/Validatable.java index e69f9ee33ba..2ec1ed302c4 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/Validatable.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/Validatable.java @@ -38,7 +38,8 @@ import java.util.Optional; */ public interface Validatable { - Validatable EMPTY = new Validatable() {}; + Validatable EMPTY = new Validatable() { + }; /** * Perform validation. This method does not have to be overridden in the event that no validation needs to be done, diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/cluster/ProxyModeInfo.java b/client/rest-high-level/src/main/java/org/opensearch/client/cluster/ProxyModeInfo.java index 6bd2631ad10..fe5b767a7f6 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/cluster/ProxyModeInfo.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/cluster/ProxyModeInfo.java @@ -84,10 +84,10 @@ public class ProxyModeInfo implements RemoteConnectionInfo.ModeInfo { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ProxyModeInfo otherProxy = (ProxyModeInfo) o; - return maxSocketConnections == otherProxy.maxSocketConnections && - numSocketsConnected == otherProxy.numSocketsConnected && - Objects.equals(address, otherProxy.address) && - Objects.equals(serverName, otherProxy.serverName); + return maxSocketConnections == otherProxy.maxSocketConnections + && numSocketsConnected == otherProxy.numSocketsConnected + && Objects.equals(address, otherProxy.address) + && Objects.equals(serverName, otherProxy.serverName); } @Override diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/cluster/RemoteConnectionInfo.java b/client/rest-high-level/src/main/java/org/opensearch/client/cluster/RemoteConnectionInfo.java index ea5e633d687..4f91d32452d 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/cluster/RemoteConnectionInfo.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/cluster/RemoteConnectionInfo.java @@ -55,23 +55,21 @@ public final class RemoteConnectionInfo { @SuppressWarnings("unchecked") private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "RemoteConnectionInfoObjectParser", - false, - (args, clusterAlias) -> { - String mode = (String) args[1]; - ModeInfo modeInfo; - if (mode.equals(ProxyModeInfo.NAME)) { - modeInfo = new ProxyModeInfo((String) args[4], (String) args[5], (int) args[6], (int) args[7]); - } else if (mode.equals(SniffModeInfo.NAME)) { - modeInfo = new SniffModeInfo((List) args[8], (int) args[9], (int) args[10]); - } else { - throw new IllegalArgumentException("mode cannot be " + mode); - } - return new RemoteConnectionInfo(clusterAlias, - modeInfo, - (String) args[2], - (boolean) args[3]); - }); + "RemoteConnectionInfoObjectParser", + false, + (args, clusterAlias) -> { + String mode = (String) args[1]; + ModeInfo modeInfo; + if (mode.equals(ProxyModeInfo.NAME)) { + modeInfo = new ProxyModeInfo((String) args[4], (String) args[5], (int) args[6], (int) args[7]); + } else if (mode.equals(SniffModeInfo.NAME)) { + modeInfo = new SniffModeInfo((List) args[8], (int) args[9], (int) args[10]); + } else { + throw new IllegalArgumentException("mode cannot be " + mode); + } + return new RemoteConnectionInfo(clusterAlias, modeInfo, (String) args[2], (boolean) args[3]); + } + ); static { PARSER.declareBoolean(constructorArg(), new ParseField(CONNECTED)); @@ -133,10 +131,10 @@ public final class RemoteConnectionInfo { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RemoteConnectionInfo that = (RemoteConnectionInfo) o; - return skipUnavailable == that.skipUnavailable && - Objects.equals(modeInfo, that.modeInfo) && - Objects.equals(initialConnectionTimeoutString, that.initialConnectionTimeoutString) && - Objects.equals(clusterAlias, that.clusterAlias); + return skipUnavailable == that.skipUnavailable + && Objects.equals(modeInfo, that.modeInfo) + && Objects.equals(initialConnectionTimeoutString, that.initialConnectionTimeoutString) + && Objects.equals(clusterAlias, that.clusterAlias); } @Override diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/cluster/SniffModeInfo.java b/client/rest-high-level/src/main/java/org/opensearch/client/cluster/SniffModeInfo.java index 94320123e07..63c53ab4f69 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/cluster/SniffModeInfo.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/cluster/SniffModeInfo.java @@ -77,9 +77,9 @@ public class SniffModeInfo implements RemoteConnectionInfo.ModeInfo { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SniffModeInfo sniff = (SniffModeInfo) o; - return maxConnectionsPerCluster == sniff.maxConnectionsPerCluster && - numNodesConnected == sniff.numNodesConnected && - Objects.equals(seedNodes, sniff.seedNodes); + return maxConnectionsPerCluster == sniff.maxConnectionsPerCluster + && numNodesConnected == sniff.numNodesConnected + && Objects.equals(seedNodes, sniff.seedNodes); } @Override diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/core/AcknowledgedResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/core/AcknowledgedResponse.java index fdeb94a0b3e..c54bef15d48 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/core/AcknowledgedResponse.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/core/AcknowledgedResponse.java @@ -45,8 +45,11 @@ import static org.opensearch.common.xcontent.ConstructingObjectParser.constructo public class AcknowledgedResponse { protected static final String PARSE_FIELD_NAME = "acknowledged"; - private static final ConstructingObjectParser PARSER = AcknowledgedResponse - .generateParser("acknowledged_response", AcknowledgedResponse::new, AcknowledgedResponse.PARSE_FIELD_NAME); + private static final ConstructingObjectParser PARSER = AcknowledgedResponse.generateParser( + "acknowledged_response", + AcknowledgedResponse::new, + AcknowledgedResponse.PARSE_FIELD_NAME + ); private final boolean acknowledged; diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/core/BroadcastResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/core/BroadcastResponse.java index 20766afe62b..dc46b3fbcc9 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/core/BroadcastResponse.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/core/BroadcastResponse.java @@ -65,8 +65,9 @@ public class BroadcastResponse { private static final ParseField SHARDS_FIELD = new ParseField("_shards"); static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "broadcast_response", - a -> new BroadcastResponse((Shards) a[0])); + "broadcast_response", + a -> new BroadcastResponse((Shards) a[0]) + ); static { declareShardsField(PARSER); @@ -149,11 +150,12 @@ public class BroadcastResponse { } Shards( - final int total, - final int successful, - final int skipped, - final int failed, - final Collection failures) { + final int total, + final int successful, + final int skipped, + final int failed, + final Collection failures + ) { this.total = total; this.successful = successful; this.skipped = skipped; @@ -169,13 +171,15 @@ public class BroadcastResponse { @SuppressWarnings("unchecked") static final ConstructingObjectParser SHARDS_PARSER = new ConstructingObjectParser<>( - "shards", - a -> new Shards( - (int) a[0], // total - (int) a[1], // successful - a[2] == null ? 0 : (int) a[2], // skipped - (int) a[3], // failed - a[4] == null ? Collections.emptyList() : (Collection) a[4])); // failures + "shards", + a -> new Shards( + (int) a[0], // total + (int) a[1], // successful + a[2] == null ? 0 : (int) a[2], // skipped + (int) a[3], // failed + a[4] == null ? Collections.emptyList() : (Collection) a[4] + ) + ); // failures static { SHARDS_PARSER.declareInt(ConstructingObjectParser.constructorArg(), TOTAL_FIELD); @@ -183,8 +187,10 @@ public class BroadcastResponse { SHARDS_PARSER.declareInt(ConstructingObjectParser.optionalConstructorArg(), SKIPPED_FIELD); SHARDS_PARSER.declareInt(ConstructingObjectParser.constructorArg(), FAILED_FIELD); SHARDS_PARSER.declareObjectArray( - ConstructingObjectParser.optionalConstructorArg(), - DefaultShardOperationFailedException.PARSER, FAILURES_FIELD); + ConstructingObjectParser.optionalConstructorArg(), + DefaultShardOperationFailedException.PARSER, + FAILURES_FIELD + ); } } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/core/CountRequest.java b/client/rest-high-level/src/main/java/org/opensearch/client/core/CountRequest.java index 20414b390ff..88d0fee69a8 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/core/CountRequest.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/core/CountRequest.java @@ -88,7 +88,8 @@ public final class CountRequest extends ActionRequest implements IndicesRequest. */ public CountRequest(String[] indices, QueryBuilder query) { indices(indices); - this.query = Objects.requireNonNull(query, "query must not be null");; + this.query = Objects.requireNonNull(query, "query must not be null"); + ; } @Override @@ -261,14 +262,14 @@ public final class CountRequest extends ActionRequest implements IndicesRequest. return false; } CountRequest that = (CountRequest) o; - return Objects.equals(indicesOptions, that.indicesOptions) && - Arrays.equals(indices, that.indices) && - Arrays.equals(types, that.types) && - Objects.equals(routing, that.routing) && - Objects.equals(preference, that.preference) && - Objects.equals(terminateAfter, that.terminateAfter) && - Objects.equals(minScore, that.minScore) && - Objects.equals(query, that.query); + return Objects.equals(indicesOptions, that.indicesOptions) + && Arrays.equals(indices, that.indices) + && Arrays.equals(types, that.types) + && Objects.equals(routing, that.routing) + && Objects.equals(preference, that.preference) + && Objects.equals(terminateAfter, that.terminateAfter) + && Objects.equals(minScore, that.minScore) + && Objects.equals(query, that.query); } @Override diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/core/CountResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/core/CountResponse.java index e115a8fb03e..1d67a50f68f 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/core/CountResponse.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/core/CountResponse.java @@ -120,7 +120,7 @@ public final class CountResponse { String currentName = parser.currentName(); Boolean terminatedEarly = null; long count = 0; - ShardStats shardStats = new ShardStats(-1, -1,0, ShardSearchFailure.EMPTY_ARRAY); + ShardStats shardStats = new ShardStats(-1, -1, 0, ShardSearchFailure.EMPTY_ARRAY); for (XContentParser.Token token = parser.nextToken(); token != XContentParser.Token.END_OBJECT; token = parser.nextToken()) { if (token == XContentParser.Token.FIELD_NAME) { @@ -146,11 +146,13 @@ public final class CountResponse { @Override public String toString() { - String s = "{" + - "count=" + count + - (isTerminatedEarly() != null ? ", terminatedEarly=" + terminatedEarly : "") + - ", " + shardStats + - '}'; + String s = "{" + + "count=" + + count + + (isTerminatedEarly() != null ? ", terminatedEarly=" + terminatedEarly : "") + + ", " + + shardStats + + '}'; return s; } @@ -200,7 +202,7 @@ public final class CountResponse { static ShardStats fromXContent(XContentParser parser) throws IOException { int successfulShards = -1; int totalShards = -1; - int skippedShards = 0; //BWC @see org.opensearch.action.search.SearchResponse + int skippedShards = 0; // BWC @see org.opensearch.action.search.SearchResponse List failures = new ArrayList<>(); XContentParser.Token token; String currentName = parser.currentName(); @@ -236,13 +238,17 @@ public final class CountResponse { @Override public String toString() { - return "_shards : {" + - "total=" + totalShards + - ", successful=" + successfulShards + - ", skipped=" + skippedShards + - ", failed=" + (shardFailures != null && shardFailures.length > 0 ? shardFailures.length : 0 ) + - (shardFailures != null && shardFailures.length > 0 ? ", failures: " + Arrays.asList(shardFailures): "") + - '}'; + return "_shards : {" + + "total=" + + totalShards + + ", successful=" + + successfulShards + + ", skipped=" + + skippedShards + + ", failed=" + + (shardFailures != null && shardFailures.length > 0 ? shardFailures.length : 0) + + (shardFailures != null && shardFailures.length > 0 ? ", failures: " + Arrays.asList(shardFailures) : "") + + '}'; } } } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/core/GetSourceRequest.java b/client/rest-high-level/src/main/java/org/opensearch/client/core/GetSourceRequest.java index 4496b0994e8..49af90314cc 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/core/GetSourceRequest.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/core/GetSourceRequest.java @@ -55,8 +55,7 @@ public final class GetSourceRequest implements Validatable { } public static GetSourceRequest from(GetRequest getRequest) { - return new GetSourceRequest(getRequest.index(), getRequest.id()) - .routing(getRequest.routing()) + return new GetSourceRequest(getRequest.index(), getRequest.id()).routing(getRequest.routing()) .preference(getRequest.preference()) .refresh(getRequest.refresh()) .realtime(getRequest.realtime()) diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/core/IndexerJobStats.java b/client/rest-high-level/src/main/java/org/opensearch/client/core/IndexerJobStats.java index 2ca3785a6aa..b0cc46b80af 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/core/IndexerJobStats.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/core/IndexerJobStats.java @@ -63,9 +63,20 @@ public abstract class IndexerJobStats { protected final long indexFailures; protected final long searchFailures; - public IndexerJobStats(long numPages, long numInputDocuments, long numOutputDocuments, long numInvocations, - long indexTime, long searchTime, long processingTime, long indexTotal, long searchTotal, long processingTotal, - long indexFailures, long searchFailures) { + public IndexerJobStats( + long numPages, + long numInputDocuments, + long numOutputDocuments, + long numInvocations, + long indexTime, + long searchTime, + long processingTime, + long indexTotal, + long searchTotal, + long processingTotal, + long indexFailures, + long searchFailures + ) { this.numPages = numPages; this.numInputDocuments = numInputDocuments; this.numOuputDocuments = numOutputDocuments; @@ -165,7 +176,6 @@ public abstract class IndexerJobStats { return processingTotal; } - @Override public boolean equals(Object other) { if (this == other) { @@ -178,39 +188,63 @@ public abstract class IndexerJobStats { IndexerJobStats that = (IndexerJobStats) other; return Objects.equals(this.numPages, that.numPages) - && Objects.equals(this.numInputDocuments, that.numInputDocuments) - && Objects.equals(this.numOuputDocuments, that.numOuputDocuments) - && Objects.equals(this.numInvocations, that.numInvocations) - && Objects.equals(this.indexTime, that.indexTime) - && Objects.equals(this.searchTime, that.searchTime) - && Objects.equals(this.processingTime, that.processingTime) - && Objects.equals(this.indexFailures, that.indexFailures) - && Objects.equals(this.searchFailures, that.searchFailures) - && Objects.equals(this.searchTotal, that.searchTotal) - && Objects.equals(this.processingTotal, that.processingTotal) - && Objects.equals(this.indexTotal, that.indexTotal); + && Objects.equals(this.numInputDocuments, that.numInputDocuments) + && Objects.equals(this.numOuputDocuments, that.numOuputDocuments) + && Objects.equals(this.numInvocations, that.numInvocations) + && Objects.equals(this.indexTime, that.indexTime) + && Objects.equals(this.searchTime, that.searchTime) + && Objects.equals(this.processingTime, that.processingTime) + && Objects.equals(this.indexFailures, that.indexFailures) + && Objects.equals(this.searchFailures, that.searchFailures) + && Objects.equals(this.searchTotal, that.searchTotal) + && Objects.equals(this.processingTotal, that.processingTotal) + && Objects.equals(this.indexTotal, that.indexTotal); } @Override public int hashCode() { - return Objects.hash(numPages, numInputDocuments, numOuputDocuments, numInvocations, - indexTime, searchTime, processingTime, indexFailures, searchFailures, searchTotal, - indexTotal, processingTotal); + return Objects.hash( + numPages, + numInputDocuments, + numOuputDocuments, + numInvocations, + indexTime, + searchTime, + processingTime, + indexFailures, + searchFailures, + searchTotal, + indexTotal, + processingTotal + ); } @Override public final String toString() { - return "{pages=" + numPages - + ", input_docs=" + numInputDocuments - + ", output_docs=" + numOuputDocuments - + ", invocations=" + numInvocations - + ", index_failures=" + indexFailures - + ", search_failures=" + searchFailures - + ", index_time_in_ms=" + indexTime - + ", index_total=" + indexTotal - + ", search_time_in_ms=" + searchTime - + ", search_total=" + searchTotal - + ", processing_time_in_ms=" + processingTime - + ", processing_total=" + processingTotal + "}"; + return "{pages=" + + numPages + + ", input_docs=" + + numInputDocuments + + ", output_docs=" + + numOuputDocuments + + ", invocations=" + + numInvocations + + ", index_failures=" + + indexFailures + + ", search_failures=" + + searchFailures + + ", index_time_in_ms=" + + indexTime + + ", index_total=" + + indexTotal + + ", search_time_in_ms=" + + searchTime + + ", search_total=" + + searchTotal + + ", processing_time_in_ms=" + + processingTime + + ", processing_total=" + + processingTotal + + "}"; } } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/core/IndexerState.java b/client/rest-high-level/src/main/java/org/opensearch/client/core/IndexerState.java index b12aee6bd3c..7f757d2bc60 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/core/IndexerState.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/core/IndexerState.java @@ -32,7 +32,6 @@ package org.opensearch.client.core; - import java.util.Locale; /** diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/core/MainRequest.java b/client/rest-high-level/src/main/java/org/opensearch/client/core/MainRequest.java index b61ada48816..664faa5b358 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/core/MainRequest.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/core/MainRequest.java @@ -34,5 +34,4 @@ package org.opensearch.client.core; import org.opensearch.client.Validatable; -public class MainRequest implements Validatable { -} +public class MainRequest implements Validatable {} 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 a90ef26fca7..b15ef2e699c 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 @@ -40,12 +40,11 @@ import java.util.Objects; 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]); - } - ); + 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]); } + ); static { PARSER.declareString(ConstructingObjectParser.constructorArg(), new ParseField("name")); @@ -92,10 +91,10 @@ public class MainResponse { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MainResponse that = (MainResponse) o; - return nodeName.equals(that.nodeName) && - version.equals(that.version) && - clusterName.equals(that.clusterName) && - clusterUuid.equals(that.clusterUuid); + return nodeName.equals(that.nodeName) + && version.equals(that.version) + && clusterName.equals(that.clusterName) + && clusterUuid.equals(that.clusterUuid); } @Override @@ -104,13 +103,22 @@ public class MainResponse { } public static class Version { - private static final ConstructingObjectParser PARSER = - new ConstructingObjectParser<>(Version.class.getName(), true, - args -> { - return new Version((String) args[0], (String) args[1], (String) args[2], (String) args[3], - (Boolean) args[4], (String) args[5], (String) args[6], (String) args[7]); - } - ); + private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( + Version.class.getName(), + true, + args -> { + return new Version( + (String) args[0], + (String) args[1], + (String) args[2], + (String) args[3], + (Boolean) args[4], + (String) args[5], + (String) args[6], + (String) args[7] + ); + } + ); static { PARSER.declareString(ConstructingObjectParser.constructorArg(), new ParseField("number")); @@ -132,8 +140,16 @@ public class MainResponse { private final String minimumWireCompatibilityVersion; private final String minimumIndexCompatibilityVersion; - public Version(String number, String buildType, String buildHash, String buildDate, boolean isSnapshot, - String luceneVersion, String minimumWireCompatibilityVersion, String minimumIndexCompatibilityVersion) { + public Version( + String number, + String buildType, + String buildHash, + String buildDate, + boolean isSnapshot, + String luceneVersion, + String minimumWireCompatibilityVersion, + String minimumIndexCompatibilityVersion + ) { this.number = number; this.buildType = buildType; this.buildHash = buildHash; @@ -181,20 +197,28 @@ public class MainResponse { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Version version = (Version) o; - return isSnapshot == version.isSnapshot && - number.equals(version.number) && - Objects.equals(buildType, version.buildType) && - buildHash.equals(version.buildHash) && - buildDate.equals(version.buildDate) && - luceneVersion.equals(version.luceneVersion) && - minimumWireCompatibilityVersion.equals(version.minimumWireCompatibilityVersion) && - minimumIndexCompatibilityVersion.equals(version.minimumIndexCompatibilityVersion); + return isSnapshot == version.isSnapshot + && number.equals(version.number) + && Objects.equals(buildType, version.buildType) + && buildHash.equals(version.buildHash) + && buildDate.equals(version.buildDate) + && luceneVersion.equals(version.luceneVersion) + && minimumWireCompatibilityVersion.equals(version.minimumWireCompatibilityVersion) + && minimumIndexCompatibilityVersion.equals(version.minimumIndexCompatibilityVersion); } @Override public int hashCode() { - return Objects.hash(number, buildType, buildHash, buildDate, isSnapshot, luceneVersion, - minimumWireCompatibilityVersion, minimumIndexCompatibilityVersion); + return Objects.hash( + number, + buildType, + buildHash, + buildDate, + isSnapshot, + luceneVersion, + minimumWireCompatibilityVersion, + minimumIndexCompatibilityVersion + ); } } } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/core/MultiTermVectorsResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/core/MultiTermVectorsResponse.java index cfeedf8cf71..490c5e314a5 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/core/MultiTermVectorsResponse.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/core/MultiTermVectorsResponse.java @@ -32,7 +32,6 @@ package org.opensearch.client.core; - import org.opensearch.common.ParseField; import org.opensearch.common.xcontent.ConstructingObjectParser; import org.opensearch.common.xcontent.XContentParser; @@ -49,17 +48,19 @@ public class MultiTermVectorsResponse { this.responses = responses; } - private static final ConstructingObjectParser PARSER = - new ConstructingObjectParser<>("multi_term_vectors", true, + private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( + "multi_term_vectors", + true, args -> { // as the response comes from server, we are sure that args[0] will be a list of TermVectorsResponse - @SuppressWarnings("unchecked") List termVectorsResponsesList = (List) args[0]; + @SuppressWarnings("unchecked") + List termVectorsResponsesList = (List) args[0]; return new MultiTermVectorsResponse(termVectorsResponsesList); } ); static { - PARSER.declareObjectArray(constructorArg(), (p,c) -> TermVectorsResponse.fromXContent(p), new ParseField("docs")); + PARSER.declareObjectArray(constructorArg(), (p, c) -> TermVectorsResponse.fromXContent(p), new ParseField("docs")); } public static MultiTermVectorsResponse fromXContent(XContentParser parser) { @@ -73,7 +74,6 @@ public class MultiTermVectorsResponse { return responses; } - @Override public boolean equals(Object obj) { if (this == obj) return true; diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/core/PageParams.java b/client/rest-high-level/src/main/java/org/opensearch/client/core/PageParams.java index 76a129567b1..38b287a87d4 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/core/PageParams.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/core/PageParams.java @@ -49,8 +49,10 @@ public class PageParams implements ToXContentObject { public static final ParseField FROM = new ParseField("from"); public static final ParseField SIZE = new ParseField("size"); - public static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>(PAGE.getPreferredName(), - a -> new PageParams((Integer) a[0], (Integer) a[1])); + public static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( + PAGE.getPreferredName(), + a -> new PageParams((Integer) a[0], (Integer) a[1]) + ); static { PARSER.declareInt(ConstructingObjectParser.optionalConstructorArg(), FROM); @@ -105,8 +107,7 @@ public class PageParams implements ToXContentObject { return false; } PageParams other = (PageParams) obj; - return Objects.equals(from, other.from) && - Objects.equals(size, other.size); + return Objects.equals(from, other.from) && Objects.equals(size, other.size); } } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/core/ShardsAcknowledgedResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/core/ShardsAcknowledgedResponse.java index 90269bed408..df228d3d84f 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/core/ShardsAcknowledgedResponse.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/core/ShardsAcknowledgedResponse.java @@ -42,10 +42,14 @@ import static org.opensearch.common.xcontent.ConstructingObjectParser.constructo public class ShardsAcknowledgedResponse extends AcknowledgedResponse { protected static final String SHARDS_PARSE_FIELD_NAME = "shards_acknowledged"; + private static ConstructingObjectParser buildParser() { - ConstructingObjectParser p = new ConstructingObjectParser<>("freeze", true, - args -> new ShardsAcknowledgedResponse((boolean) args[0], (boolean) args[1])); + ConstructingObjectParser p = new ConstructingObjectParser<>( + "freeze", + true, + args -> new ShardsAcknowledgedResponse((boolean) args[0], (boolean) args[1]) + ); p.declareBoolean(constructorArg(), new ParseField(AcknowledgedResponse.PARSE_FIELD_NAME)); p.declareBoolean(constructorArg(), new ParseField(SHARDS_PARSE_FIELD_NAME)); return p; diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/core/TermVectorsRequest.java b/client/rest-high-level/src/main/java/org/opensearch/client/core/TermVectorsRequest.java index 2ad0739380e..b346667f462 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/core/TermVectorsRequest.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/core/TermVectorsRequest.java @@ -45,7 +45,8 @@ import java.util.Map; public class TermVectorsRequest implements ToXContentObject, Validatable { private final String index; - @Nullable private final String type; + @Nullable + private final String type; private String id = null; private XContentBuilder docBuilder = null; @@ -118,7 +119,6 @@ public class TermVectorsRequest implements ToXContentObject, Validatable { this.docBuilder = docBuilder; } - /** * Constructs a new TermVectorRequest from a template * using the provided document id @@ -262,7 +262,6 @@ public class TermVectorsRequest implements ToXContentObject, Validatable { return realtime; } - @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); @@ -289,8 +288,14 @@ public class TermVectorsRequest implements ToXContentObject, Validatable { if (filterSettings != null) { builder.startObject("filter"); - String[] filterSettingNames = - {"max_num_terms", "min_term_freq", "max_term_freq", "min_doc_freq", "max_doc_freq", "min_word_length", "max_word_length"}; + String[] filterSettingNames = { + "max_num_terms", + "min_term_freq", + "max_term_freq", + "min_doc_freq", + "max_doc_freq", + "min_word_length", + "max_word_length" }; for (String settingName : filterSettingNames) { if (filterSettings.containsKey(settingName)) builder.field(settingName, filterSettings.get(settingName)); } 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 9f322c1d645..757e0df6aee 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 @@ -54,7 +54,14 @@ public class TermVectorsResponse { private final List termVectorList; public TermVectorsResponse( - String index, String type, String id, long version, boolean found, long tookInMillis, List termVectorList) { + String index, + String type, + String id, + long version, + boolean found, + long tookInMillis, + List termVectorList + ) { this.index = index; this.type = type; this.id = id; @@ -64,10 +71,13 @@ public class TermVectorsResponse { this.termVectorList = termVectorList; } - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>("term_vectors", true, + private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( + "term_vectors", + true, args -> { // as the response comes from server, we are sure that args[6] will be a list of TermVector - @SuppressWarnings("unchecked") List termVectorList = (List) args[6]; + @SuppressWarnings("unchecked") + List termVectorList = (List) args[6]; if (termVectorList != null) { Collections.sort(termVectorList, Comparator.comparing(TermVector::getFieldName)); } @@ -90,8 +100,11 @@ public class TermVectorsResponse { PARSER.declareLong(constructorArg(), new ParseField("_version")); PARSER.declareBoolean(constructorArg(), new ParseField("found")); PARSER.declareLong(constructorArg(), new ParseField("took")); - PARSER.declareNamedObjects(optionalConstructorArg(), - (p, c, fieldName) -> TermVector.fromXContent(p, fieldName), new ParseField("term_vectors")); + PARSER.declareNamedObjects( + optionalConstructorArg(), + (p, c, fieldName) -> TermVector.fromXContent(p, fieldName), + new ParseField("term_vectors") + ); } public static TermVectorsResponse fromXContent(XContentParser parser) { @@ -135,7 +148,7 @@ public class TermVectorsResponse { * Returns the document version */ public long getDocVersion() { - return docVersion; + return docVersion; } /** @@ -148,7 +161,7 @@ public class TermVectorsResponse { /** * Returns the list of term vectors */ - public List getTermVectorsList(){ + public List getTermVectorsList() { return termVectorList; } @@ -171,13 +184,15 @@ public class TermVectorsResponse { return Objects.hash(index, type, id, docVersion, found, tookInMillis, termVectorList); } - public static final class TermVector { - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>("term_vector", true, - (args, ctxFieldName) -> { + private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( + "term_vector", + true, + (args, ctxFieldName) -> { // as the response comes from server, we are sure that args[1] will be a list of Term - @SuppressWarnings("unchecked") List terms = (List) args[1]; + @SuppressWarnings("unchecked") + List terms = (List) args[1]; if (terms != null) { Collections.sort(terms, Comparator.comparing(Term::getTerm)); } @@ -186,8 +201,7 @@ public class TermVectorsResponse { ); static { - PARSER.declareObject(optionalConstructorArg(), - (p,c) -> FieldStatistics.fromXContent(p), new ParseField("field_statistics")); + PARSER.declareObject(optionalConstructorArg(), (p, c) -> FieldStatistics.fromXContent(p), new ParseField("field_statistics")); PARSER.declareNamedObjects(optionalConstructorArg(), (p, c, term) -> Term.fromXContent(p, term), new ParseField("terms")); } @@ -228,7 +242,6 @@ public class TermVectorsResponse { return fieldStatistics; } - @Override public boolean equals(Object obj) { if (this == obj) return true; @@ -248,10 +261,9 @@ public class TermVectorsResponse { 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]); - } + "field_statistics", + true, + args -> { return new FieldStatistics((long) args[0], (int) args[1], (long) args[2]); } ); static { @@ -293,14 +305,13 @@ public class TermVectorsResponse { public long getSumTotalTermFreq() { return sumTotalTermFreq; } + @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof FieldStatistics)) return false; FieldStatistics other = (FieldStatistics) obj; - return docCount == other.docCount - && sumDocFreq == other.sumDocFreq - && sumTotalTermFreq == other.sumTotalTermFreq; + return docCount == other.docCount && sumDocFreq == other.sumDocFreq && sumTotalTermFreq == other.sumTotalTermFreq; } @Override @@ -309,12 +320,14 @@ public class TermVectorsResponse { } } - public static final class Term { - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>("token", true, - (args, ctxTerm) -> { + private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( + "token", + true, + (args, ctxTerm) -> { // as the response comes from server, we are sure that args[4] will be a list of Token - @SuppressWarnings("unchecked") List tokens = (List) args[4]; + @SuppressWarnings("unchecked") + List tokens = (List) args[4]; if (tokens != null) { Collections.sort( tokens, @@ -331,7 +344,7 @@ public class TermVectorsResponse { PARSER.declareInt(optionalConstructorArg(), new ParseField("doc_freq")); PARSER.declareLong(optionalConstructorArg(), new ParseField("ttf")); PARSER.declareFloat(optionalConstructorArg(), new ParseField("score")); - PARSER.declareObjectArray(optionalConstructorArg(), (p,c) -> Token.fromXContent(p), new ParseField("tokens")); + PARSER.declareObjectArray(optionalConstructorArg(), (p, c) -> Token.fromXContent(p), new ParseField("tokens")); } private final String term; @@ -382,14 +395,14 @@ public class TermVectorsResponse { /** * Returns total term frequency - the number of times this term occurs across all documents */ - public Long getTotalTermFreq( ){ + public Long getTotalTermFreq() { return totalTermFreq; } /** * Returns tf-idf score, if the request used some form of terms filtering */ - public Float getScore(){ + public Float getScore() { return score; } @@ -419,13 +432,13 @@ public class TermVectorsResponse { } } - 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")); @@ -442,8 +455,7 @@ public class TermVectorsResponse { @Nullable private final String payload; - - public Token(Integer startOffset, Integer endOffset, Integer position, String payload) { + public Token(Integer startOffset, Integer endOffset, Integer position, String payload) { this.startOffset = startOffset; this.endOffset = endOffset; this.position = position; @@ -488,7 +500,7 @@ public class TermVectorsResponse { if (!(obj instanceof Token)) return false; Token other = (Token) obj; return Objects.equals(startOffset, other.startOffset) - && Objects.equals(endOffset,other.endOffset) + && Objects.equals(endOffset, other.endOffset) && Objects.equals(position, other.position) && Objects.equals(payload, other.payload); } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/indices/AnalyzeRequest.java b/client/rest-high-level/src/main/java/org/opensearch/client/indices/AnalyzeRequest.java index 2fcd51c10fb..b614e30d63d 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/indices/AnalyzeRequest.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/indices/AnalyzeRequest.java @@ -188,8 +188,13 @@ public class AnalyzeRequest implements Validatable, ToXContentObject { this.text = text; } - private AnalyzeRequest(String index, NameOrDefinition tokenizer, List charFilters, - List tokenFilters, String... text) { + private AnalyzeRequest( + String index, + NameOrDefinition tokenizer, + List charFilters, + List tokenFilters, + String... text + ) { this.index = index; this.analyzer = null; this.normalizer = null; diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/indices/AnalyzeResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/indices/AnalyzeResponse.java index 35954a97e2b..cc173a5b8ab 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/indices/AnalyzeResponse.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/indices/AnalyzeResponse.java @@ -64,13 +64,13 @@ public class AnalyzeResponse { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AnalyzeResponse.AnalyzeToken that = (AnalyzeResponse.AnalyzeToken) o; - return startOffset == that.startOffset && - endOffset == that.endOffset && - position == that.position && - positionLength == that.positionLength && - Objects.equals(term, that.term) && - Objects.equals(attributes, that.attributes) && - Objects.equals(type, that.type); + return startOffset == that.startOffset + && endOffset == that.endOffset + && position == that.position + && positionLength == that.positionLength + && Objects.equals(term, that.term) + && Objects.equals(attributes, that.attributes) + && Objects.equals(type, that.type); } @Override @@ -134,8 +134,11 @@ public class AnalyzeResponse { this.attributes.put(key, value); } - private static final ObjectParser PARSER - = new ObjectParser<>("analyze_token", AnalyzeToken::setAttribute, AnalyzeToken::new); + private static final ObjectParser PARSER = new ObjectParser<>( + "analyze_token", + AnalyzeToken::setAttribute, + AnalyzeToken::new + ); static { PARSER.declareString(AnalyzeToken::setTerm, new ParseField("token")); PARSER.declareString(AnalyzeToken::setType, new ParseField("type")); @@ -167,8 +170,11 @@ public class AnalyzeResponse { } @SuppressWarnings("unchecked") - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>("analyze_response", - true, args -> new AnalyzeResponse((List) args[0], (DetailAnalyzeResponse) args[1])); + private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( + "analyze_response", + true, + args -> new AnalyzeResponse((List) args[0], (DetailAnalyzeResponse) args[1]) + ); static { PARSER.declareObjectArray(optionalConstructorArg(), AnalyzeToken.PARSER, new ParseField(TOKENS)); @@ -184,8 +190,7 @@ public class AnalyzeResponse { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AnalyzeResponse that = (AnalyzeResponse) o; - return Objects.equals(detail, that.detail) && - Objects.equals(tokens, that.tokens); + return Objects.equals(detail, that.detail) && Objects.equals(tokens, that.tokens); } @Override diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/indices/CloseIndexResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/indices/CloseIndexResponse.java index 66719eec172..817d1c08532 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/indices/CloseIndexResponse.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/indices/CloseIndexResponse.java @@ -51,13 +51,16 @@ import static org.opensearch.common.xcontent.ObjectParser.ValueType; public class CloseIndexResponse extends ShardsAcknowledgedResponse { @SuppressWarnings("unchecked") - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>("close_index_response", - true, args -> { - boolean acknowledged = (boolean) args[0]; - boolean shardsAcknowledged = args[1] != null ? (boolean) args[1] : acknowledged; - List indices = args[2] != null ? (List) args[2] : emptyList(); - return new CloseIndexResponse(acknowledged, shardsAcknowledged, indices); - }); + private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( + "close_index_response", + true, + args -> { + boolean acknowledged = (boolean) args[0]; + boolean shardsAcknowledged = args[1] != null ? (boolean) args[1] : acknowledged; + List indices = args[2] != null ? (List) args[2] : emptyList(); + return new CloseIndexResponse(acknowledged, shardsAcknowledged, indices); + } + ); static { declareAcknowledgedField(PARSER); @@ -83,7 +86,9 @@ public class CloseIndexResponse extends ShardsAcknowledgedResponse { public static class IndexResult { @SuppressWarnings("unchecked") - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>("index_result", true, + private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( + "index_result", + true, (args, index) -> { Exception exception = (Exception) args[1]; if (exception != null) { @@ -97,7 +102,8 @@ public class CloseIndexResponse extends ShardsAcknowledgedResponse { } assert (boolean) args[0]; return new IndexResult(index); - }); + } + ); static { PARSER.declareBoolean(optionalConstructorArg(), new ParseField("closed")); PARSER.declareObject(optionalConstructorArg(), (p, c) -> { @@ -107,8 +113,11 @@ public class CloseIndexResponse extends ShardsAcknowledgedResponse { XContentParserUtils.ensureExpectedToken(XContentParser.Token.END_OBJECT, p.nextToken(), p); return e; }, new ParseField("exception")); - PARSER.declareNamedObjects(optionalConstructorArg(), - (p, c, id) -> ShardResult.fromXContent(p, id), new ParseField("failedShards")); + PARSER.declareNamedObjects( + optionalConstructorArg(), + (p, c, id) -> ShardResult.fromXContent(p, id), + new ParseField("failedShards") + ); } private final String index; @@ -167,11 +176,14 @@ public class CloseIndexResponse extends ShardsAcknowledgedResponse { public static class ShardResult { @SuppressWarnings("unchecked") - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>("shard_result", true, + private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( + "shard_result", + true, (arg, id) -> { Failure[] failures = arg[0] != null ? ((List) arg[0]).toArray(new Failure[0]) : new Failure[0]; return new ShardResult(Integer.parseInt(id), failures); - }); + } + ); static { PARSER.declareObjectArray(optionalConstructorArg(), (p, c) -> Failure.PARSER.apply(p, null), new ParseField("failures")); @@ -203,8 +215,11 @@ public class CloseIndexResponse extends ShardsAcknowledgedResponse { public static class Failure extends DefaultShardOperationFailedException { - static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>("failure", true, - arg -> new Failure((String) arg[0], (int) arg[1], (Throwable) arg[2], (String) arg[3])); + static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( + "failure", + true, + arg -> new Failure((String) arg[0], (int) arg[1], (Throwable) arg[2], (String) arg[3]) + ); static { declareFields(PARSER); diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/indices/CreateIndexRequest.java b/client/rest-high-level/src/main/java/org/opensearch/client/indices/CreateIndexRequest.java index 1c97da2ef18..5bf65a6ea19 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/indices/CreateIndexRequest.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/indices/CreateIndexRequest.java @@ -183,7 +183,7 @@ public class CreateIndexRequest extends TimedRequest implements Validatable, ToX * @param source The mapping source */ public CreateIndexRequest mapping(Map source) { - try { + try { XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON); builder.map(source); return mapping(BytesReference.bytes(builder), builder.contentType()); @@ -243,15 +243,21 @@ public class CreateIndexRequest extends TimedRequest implements Validatable, ToX */ public CreateIndexRequest aliases(BytesReference source, XContentType contentType) { // EMPTY is safe here because we never call namedObject - try (XContentParser parser = XContentHelper.createParser(NamedXContentRegistry.EMPTY, - DeprecationHandler.THROW_UNSUPPORTED_OPERATION, source, contentType)) { - //move to the first alias + try ( + XContentParser parser = XContentHelper.createParser( + NamedXContentRegistry.EMPTY, + DeprecationHandler.THROW_UNSUPPORTED_OPERATION, + source, + contentType + ) + ) { + // move to the first alias parser.nextToken(); while ((parser.nextToken()) != XContentParser.Token.END_OBJECT) { alias(Alias.fromXContent(parser)); } return this; - } catch(IOException e) { + } catch (IOException e) { throw new OpenSearchParseException("Failed to parse aliases", e); } } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/indices/CreateIndexResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/indices/CreateIndexResponse.java index ba6a2e566e6..7e1ea289496 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/indices/CreateIndexResponse.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/indices/CreateIndexResponse.java @@ -48,8 +48,11 @@ import static org.opensearch.common.xcontent.ConstructingObjectParser.constructo public class CreateIndexResponse extends ShardsAcknowledgedResponse { private static final ParseField INDEX = new ParseField("index"); - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>("create_index", - true, args -> new CreateIndexResponse((boolean) args[0], (boolean) args[1], (String) args[2])); + private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( + "create_index", + true, + args -> new CreateIndexResponse((boolean) args[0], (boolean) args[1], (String) args[2]) + ); static { declareAcknowledgedAndShardsAcknowledgedFields(PARSER); diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/indices/DataStream.java b/client/rest-high-level/src/main/java/org/opensearch/client/indices/DataStream.java index 3f879dcc67d..e87a77dafdd 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/indices/DataStream.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/indices/DataStream.java @@ -53,8 +53,14 @@ public final class DataStream { @Nullable String indexTemplate; - public DataStream(String name, String timeStampField, List indices, long generation, ClusterHealthStatus dataStreamStatus, - @Nullable String indexTemplate) { + public DataStream( + String name, + String timeStampField, + List indices, + long generation, + ClusterHealthStatus dataStreamStatus, + @Nullable String indexTemplate + ) { this.name = name; this.timeStampField = timeStampField; this.indices = indices; @@ -95,18 +101,16 @@ public final class DataStream { public static final ParseField INDEX_TEMPLATE_FIELD = new ParseField("template"); @SuppressWarnings("unchecked") - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>("data_stream", - args -> { - String dataStreamName = (String) args[0]; - String timeStampField = (String) ((Map) args[1]).get("name"); - List indices = - ((List>) args[2]).stream().map(m -> m.get("index_name")).collect(Collectors.toList()); - Long generation = (Long) args[3]; - String statusStr = (String) args[4]; - ClusterHealthStatus status = ClusterHealthStatus.fromString(statusStr); - String indexTemplate = (String) args[5]; - return new DataStream(dataStreamName, timeStampField, indices, generation, status, indexTemplate); - }); + private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>("data_stream", args -> { + String dataStreamName = (String) args[0]; + String timeStampField = (String) ((Map) args[1]).get("name"); + List indices = ((List>) args[2]).stream().map(m -> m.get("index_name")).collect(Collectors.toList()); + Long generation = (Long) args[3]; + String statusStr = (String) args[4]; + ClusterHealthStatus status = ClusterHealthStatus.fromString(statusStr); + String indexTemplate = (String) args[5]; + return new DataStream(dataStreamName, timeStampField, indices, generation, status, indexTemplate); + }); static { PARSER.declareString(ConstructingObjectParser.constructorArg(), NAME_FIELD); @@ -126,12 +130,12 @@ public final class DataStream { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DataStream that = (DataStream) o; - return generation == that.generation && - name.equals(that.name) && - timeStampField.equals(that.timeStampField) && - indices.equals(that.indices) && - dataStreamStatus == that.dataStreamStatus && - Objects.equals(indexTemplate, that.indexTemplate); + return generation == that.generation + && name.equals(that.name) + && timeStampField.equals(that.timeStampField) + && indices.equals(that.indices) + && dataStreamStatus == that.dataStreamStatus + && Objects.equals(indexTemplate, that.indexTemplate); } @Override diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/indices/DataStreamsStatsResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/indices/DataStreamsStatsResponse.java index 22307dfc85b..fc3a7b5b4fa 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/indices/DataStreamsStatsResponse.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/indices/DataStreamsStatsResponse.java @@ -54,8 +54,13 @@ public class DataStreamsStatsResponse extends BroadcastResponse { private final ByteSizeValue totalStoreSize; private final Map dataStreams; - protected DataStreamsStatsResponse(Shards shards, int dataStreamCount, int backingIndices, ByteSizeValue totalStoreSize, - Map dataStreams) { + protected DataStreamsStatsResponse( + Shards shards, + int dataStreamCount, + int backingIndices, + ByteSizeValue totalStoreSize, + Map dataStreams + ) { super(shards); this.dataStreamCount = dataStreamCount; this.backingIndices = backingIndices; @@ -73,38 +78,52 @@ public class DataStreamsStatsResponse extends BroadcastResponse { @SuppressWarnings("unchecked") private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "data_streams_stats", true, arg -> { - Shards shards = (Shards) arg[0]; - Integer dataStreamCount = ((Integer) arg[1]); - Integer backingIndices = ((Integer) arg[2]); - ByteSizeValue totalStoreSize = ((ByteSizeValue) arg[3]); - Map dataStreams = new HashMap<>(); - for (DataStreamStats dataStreamStats : ((List) arg[4])) { - dataStreams.put(dataStreamStats.dataStream, dataStreamStats); + "data_streams_stats", + true, + arg -> { + Shards shards = (Shards) arg[0]; + Integer dataStreamCount = ((Integer) arg[1]); + Integer backingIndices = ((Integer) arg[2]); + ByteSizeValue totalStoreSize = ((ByteSizeValue) arg[3]); + Map dataStreams = new HashMap<>(); + for (DataStreamStats dataStreamStats : ((List) arg[4])) { + dataStreams.put(dataStreamStats.dataStream, dataStreamStats); + } + return new DataStreamsStatsResponse(shards, dataStreamCount, backingIndices, totalStoreSize, dataStreams); } - return new DataStreamsStatsResponse(shards, dataStreamCount, backingIndices, totalStoreSize, dataStreams); - }); + ); private static final ConstructingObjectParser ENTRY_PARSER = new ConstructingObjectParser<>( - "data_streams_stats.entry", true, arg -> { - String dataStream = ((String) arg[0]); - Integer backingIndices = ((Integer) arg[1]); - ByteSizeValue storeSize = ((ByteSizeValue) arg[2]); - Long maximumTimestamp = ((Long) arg[3]); - return new DataStreamStats(dataStream, backingIndices, storeSize, maximumTimestamp); - }); + "data_streams_stats.entry", + true, + arg -> { + String dataStream = ((String) arg[0]); + Integer backingIndices = ((Integer) arg[1]); + ByteSizeValue storeSize = ((ByteSizeValue) arg[2]); + Long maximumTimestamp = ((Long) arg[3]); + return new DataStreamStats(dataStream, backingIndices, storeSize, maximumTimestamp); + } + ); static { declareShardsField(PARSER); PARSER.declareInt(constructorArg(), DATA_STREAM_COUNT); PARSER.declareInt(constructorArg(), BACKING_INDICES); - PARSER.declareField(constructorArg(), (p, c) -> new ByteSizeValue(p.longValue()), TOTAL_STORE_SIZE_BYTES, - ObjectParser.ValueType.VALUE); + PARSER.declareField( + constructorArg(), + (p, c) -> new ByteSizeValue(p.longValue()), + TOTAL_STORE_SIZE_BYTES, + ObjectParser.ValueType.VALUE + ); PARSER.declareObjectArray(constructorArg(), ENTRY_PARSER, DATA_STREAMS); ENTRY_PARSER.declareString(constructorArg(), DATA_STREAM); ENTRY_PARSER.declareInt(constructorArg(), BACKING_INDICES); - ENTRY_PARSER.declareField(constructorArg(), (p, c) -> new ByteSizeValue(p.longValue()), STORE_SIZE_BYTES, - ObjectParser.ValueType.VALUE); + ENTRY_PARSER.declareField( + constructorArg(), + (p, c) -> new ByteSizeValue(p.longValue()), + STORE_SIZE_BYTES, + ObjectParser.ValueType.VALUE + ); ENTRY_PARSER.declareLong(constructorArg(), MAXIMUM_TIMESTAMP); } @@ -137,10 +156,10 @@ public class DataStreamsStatsResponse extends BroadcastResponse { return false; } DataStreamsStatsResponse that = (DataStreamsStatsResponse) obj; - return dataStreamCount == that.dataStreamCount && - backingIndices == that.backingIndices && - Objects.equals(totalStoreSize, that.totalStoreSize) && - Objects.equals(dataStreams, that.dataStreams); + return dataStreamCount == that.dataStreamCount + && backingIndices == that.backingIndices + && Objects.equals(totalStoreSize, that.totalStoreSize) + && Objects.equals(dataStreams, that.dataStreams); } @Override @@ -150,12 +169,16 @@ public class DataStreamsStatsResponse extends BroadcastResponse { @Override public String toString() { - return "DataStreamsStatsResponse{" + - "dataStreamCount=" + dataStreamCount + - ", backingIndices=" + backingIndices + - ", totalStoreSize=" + totalStoreSize + - ", dataStreams=" + dataStreams + - '}'; + return "DataStreamsStatsResponse{" + + "dataStreamCount=" + + dataStreamCount + + ", backingIndices=" + + backingIndices + + ", totalStoreSize=" + + totalStoreSize + + ", dataStreams=" + + dataStreams + + '}'; } public static class DataStreamStats { @@ -197,10 +220,10 @@ public class DataStreamsStatsResponse extends BroadcastResponse { return false; } DataStreamStats that = (DataStreamStats) obj; - return backingIndices == that.backingIndices && - maximumTimestamp == that.maximumTimestamp && - Objects.equals(dataStream, that.dataStream) && - Objects.equals(storeSize, that.storeSize); + return backingIndices == that.backingIndices + && maximumTimestamp == that.maximumTimestamp + && Objects.equals(dataStream, that.dataStream) + && Objects.equals(storeSize, that.storeSize); } @Override @@ -210,12 +233,17 @@ public class DataStreamsStatsResponse extends BroadcastResponse { @Override public String toString() { - return "DataStreamStats{" + - "dataStream='" + dataStream + '\'' + - ", backingIndices=" + backingIndices + - ", storeSize=" + storeSize + - ", maximumTimestamp=" + maximumTimestamp + - '}'; + return "DataStreamStats{" + + "dataStream='" + + dataStream + + '\'' + + ", backingIndices=" + + backingIndices + + ", storeSize=" + + storeSize + + ", maximumTimestamp=" + + maximumTimestamp + + '}'; } } } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/indices/DetailAnalyzeResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/indices/DetailAnalyzeResponse.java index 99e646a3840..00fa6fb046c 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/indices/DetailAnalyzeResponse.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/indices/DetailAnalyzeResponse.java @@ -53,16 +53,18 @@ public class DetailAnalyzeResponse { private final AnalyzeTokenList tokenizer; private final AnalyzeTokenList[] tokenfilters; - private DetailAnalyzeResponse(boolean customAnalyzer, - AnalyzeTokenList analyzer, - List charfilters, - AnalyzeTokenList tokenizer, - List tokenfilters) { + private DetailAnalyzeResponse( + boolean customAnalyzer, + AnalyzeTokenList analyzer, + List charfilters, + AnalyzeTokenList tokenizer, + List tokenfilters + ) { this.customAnalyzer = customAnalyzer; this.analyzer = analyzer; - this.charfilters = charfilters == null ? null : charfilters.toArray(new CharFilteredText[]{}); + this.charfilters = charfilters == null ? null : charfilters.toArray(new CharFilteredText[] {}); this.tokenizer = tokenizer; - this.tokenfilters = tokenfilters == null ? null : tokenfilters.toArray(new AnalyzeTokenList[]{}); + this.tokenfilters = tokenfilters == null ? null : tokenfilters.toArray(new AnalyzeTokenList[] {}); } public AnalyzeTokenList analyzer() { @@ -86,11 +88,11 @@ public class DetailAnalyzeResponse { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DetailAnalyzeResponse that = (DetailAnalyzeResponse) o; - return customAnalyzer == that.customAnalyzer && - Objects.equals(analyzer, that.analyzer) && - Arrays.equals(charfilters, that.charfilters) && - Objects.equals(tokenizer, that.tokenizer) && - Arrays.equals(tokenfilters, that.tokenfilters); + return customAnalyzer == that.customAnalyzer + && Objects.equals(analyzer, that.analyzer) + && Arrays.equals(charfilters, that.charfilters) + && Objects.equals(tokenizer, that.tokenizer) + && Arrays.equals(tokenfilters, that.tokenfilters); } @Override @@ -102,13 +104,17 @@ public class DetailAnalyzeResponse { } @SuppressWarnings("unchecked") - static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>("detail", - true, args -> new DetailAnalyzeResponse( - (boolean) args[0], - (AnalyzeTokenList) args[1], - (List)args[2], - (AnalyzeTokenList) args[3], - (List)args[4])); + static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( + "detail", + true, + args -> new DetailAnalyzeResponse( + (boolean) args[0], + (AnalyzeTokenList) args[1], + (List) args[2], + (AnalyzeTokenList) args[3], + (List) args[4] + ) + ); static { PARSER.declareBoolean(constructorArg(), new ParseField("custom_analyzer")); @@ -131,8 +137,7 @@ public class DetailAnalyzeResponse { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AnalyzeTokenList that = (AnalyzeTokenList) o; - return Objects.equals(name, that.name) && - Arrays.equals(tokens, that.tokens); + return Objects.equals(name, that.name) && Arrays.equals(tokens, that.tokens); } @Override @@ -144,7 +149,7 @@ public class DetailAnalyzeResponse { public AnalyzeTokenList(String name, List tokens) { this.name = name; - this.tokens = tokens.toArray(new AnalyzeResponse.AnalyzeToken[]{}); + this.tokens = tokens.toArray(new AnalyzeResponse.AnalyzeToken[] {}); } public String getName() { @@ -156,14 +161,15 @@ public class DetailAnalyzeResponse { } @SuppressWarnings("unchecked") - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>("token_list", - true, args -> new AnalyzeTokenList((String) args[0], - (List)args[1])); + private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( + "token_list", + true, + args -> new AnalyzeTokenList((String) args[0], (List) args[1]) + ); static { PARSER.declareString(constructorArg(), new ParseField("name")); - PARSER.declareObjectArray(constructorArg(), (p, c) -> AnalyzeResponse.AnalyzeToken.fromXContent(p), - new ParseField("tokens")); + PARSER.declareObjectArray(constructorArg(), (p, c) -> AnalyzeResponse.AnalyzeToken.fromXContent(p), new ParseField("tokens")); } public static AnalyzeTokenList fromXContent(XContentParser parser) throws IOException { @@ -194,8 +200,11 @@ public class DetailAnalyzeResponse { } @SuppressWarnings("unchecked") - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>("char_filtered_text", - true, args -> new CharFilteredText((String) args[0], ((List) args[1]).toArray(new String[0]))); + private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( + "char_filtered_text", + true, + args -> new CharFilteredText((String) args[0], ((List) args[1]).toArray(new String[0])) + ); static { PARSER.declareString(constructorArg(), new ParseField("name")); @@ -211,8 +220,7 @@ public class DetailAnalyzeResponse { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CharFilteredText that = (CharFilteredText) o; - return Objects.equals(name, that.name) && - Arrays.equals(texts, that.texts); + return Objects.equals(name, that.name) && Arrays.equals(texts, that.texts); } @Override diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetComponentTemplatesResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetComponentTemplatesResponse.java index e3b7f8f2616..8f6ebbc8349 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetComponentTemplatesResponse.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetComponentTemplatesResponse.java @@ -44,7 +44,6 @@ import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; - public class GetComponentTemplatesResponse { public static final ParseField NAME = new ParseField("name"); @@ -52,14 +51,18 @@ public class GetComponentTemplatesResponse { public static final ParseField COMPONENT_TEMPLATE = new ParseField("component_template"); @SuppressWarnings("unchecked") - private static final ConstructingObjectParser, Void> PARSER = - new ConstructingObjectParser<>("component_templates", false, - a -> ((List) a[0]).stream().collect(Collectors.toMap(n -> n.name, n -> n.componentTemplate, - (n1, n2) -> n1, LinkedHashMap::new))); + private static final ConstructingObjectParser, Void> PARSER = new ConstructingObjectParser<>( + "component_templates", + false, + a -> ((List) a[0]).stream() + .collect(Collectors.toMap(n -> n.name, n -> n.componentTemplate, (n1, n2) -> n1, LinkedHashMap::new)) + ); - private static final ConstructingObjectParser INNER_PARSER = - new ConstructingObjectParser<>("named_component_template", false, - a -> new NamedComponentTemplate((String) a[0], (ComponentTemplate) a[1])); + private static final ConstructingObjectParser INNER_PARSER = new ConstructingObjectParser<>( + "named_component_template", + false, + a -> new NamedComponentTemplate((String) a[0], (ComponentTemplate) a[1]) + ); static { INNER_PARSER.declareString(ConstructingObjectParser.constructorArg(), NAME); @@ -92,7 +95,6 @@ public class GetComponentTemplatesResponse { return componentTemplates; } - public static GetComponentTemplatesResponse fromXContent(XContentParser parser) throws IOException { return new GetComponentTemplatesResponse(PARSER.apply(parser, null)); } @@ -117,5 +119,4 @@ public class GetComponentTemplatesResponse { return Objects.equals(componentTemplates, other.componentTemplates); } - } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetComposableIndexTemplatesResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetComposableIndexTemplatesResponse.java index 00315dc7409..96ba7e67525 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetComposableIndexTemplatesResponse.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetComposableIndexTemplatesResponse.java @@ -44,7 +44,6 @@ import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; - public class GetComposableIndexTemplatesResponse { public static final ParseField NAME = new ParseField("name"); @@ -52,14 +51,18 @@ public class GetComposableIndexTemplatesResponse { public static final ParseField INDEX_TEMPLATE = new ParseField("index_template"); @SuppressWarnings("unchecked") - private static final ConstructingObjectParser, Void> PARSER = - new ConstructingObjectParser<>("index_templates", false, - a -> ((List) a[0]).stream().collect(Collectors.toMap(n -> n.name, n -> n.indexTemplate, - (n1, n2) -> n1, LinkedHashMap::new))); + private static final ConstructingObjectParser, Void> PARSER = new ConstructingObjectParser<>( + "index_templates", + false, + a -> ((List) a[0]).stream() + .collect(Collectors.toMap(n -> n.name, n -> n.indexTemplate, (n1, n2) -> n1, LinkedHashMap::new)) + ); - private static final ConstructingObjectParser INNER_PARSER = - new ConstructingObjectParser<>("named_index_template", false, - a -> new NamedIndexTemplate((String) a[0], (ComposableIndexTemplate) a[1])); + private static final ConstructingObjectParser INNER_PARSER = new ConstructingObjectParser<>( + "named_index_template", + false, + a -> new NamedIndexTemplate((String) a[0], (ComposableIndexTemplate) a[1]) + ); static { INNER_PARSER.declareString(ConstructingObjectParser.constructorArg(), NAME); @@ -92,7 +95,6 @@ public class GetComposableIndexTemplatesResponse { return indexTemplates; } - public static GetComposableIndexTemplatesResponse fromXContent(XContentParser parser) throws IOException { return new GetComposableIndexTemplatesResponse(PARSER.apply(parser, null)); } @@ -117,5 +119,4 @@ public class GetComposableIndexTemplatesResponse { return Objects.equals(indexTemplates, other.indexTemplates); } - } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetDataStreamResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetDataStreamResponse.java index 3e5e566cfdf..81fde3ebf21 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetDataStreamResponse.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetDataStreamResponse.java @@ -40,7 +40,6 @@ import java.util.HashSet; import java.util.List; import java.util.Objects; - public class GetDataStreamResponse { private final List dataStreams; diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetFieldMappingsResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetFieldMappingsResponse.java index 1fa73addcf3..c3d9679fc48 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetFieldMappingsResponse.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetFieldMappingsResponse.java @@ -56,8 +56,11 @@ public class GetFieldMappingsResponse { private static final ParseField MAPPINGS = new ParseField("mappings"); - private static final ObjectParser, String> PARSER = - new ObjectParser<>(MAPPINGS.getPreferredName(), true, HashMap::new); + private static final ObjectParser, String> PARSER = new ObjectParser<>( + MAPPINGS.getPreferredName(), + true, + HashMap::new + ); static { PARSER.declareField((p, fieldMappings, index) -> { @@ -77,10 +80,9 @@ public class GetFieldMappingsResponse { this.mappings = mappings; } - - /** - * Returns the fields mapping. The return map keys are indexes and fields (as specified in the request). - */ + /** + * Returns the fields mapping. The return map keys are indexes and fields (as specified in the request). + */ public Map> mappings() { return mappings; } @@ -99,7 +101,6 @@ public class GetFieldMappingsResponse { return indexMapping.get(field); } - public static GetFieldMappingsResponse fromXContent(XContentParser parser) throws IOException { ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser); final Map> mappings = new HashMap<>(); @@ -118,20 +119,19 @@ public class GetFieldMappingsResponse { private static final ParseField FULL_NAME = new ParseField("full_name"); private static final ParseField MAPPING = new ParseField("mapping"); - private static final ConstructingObjectParser PARSER = - new ConstructingObjectParser<>("field_mapping_meta_data", true, - a -> new FieldMappingMetadata((String)a[0], (BytesReference)a[1]) - ); + private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( + "field_mapping_meta_data", + true, + a -> new FieldMappingMetadata((String) a[0], (BytesReference) a[1]) + ); static { - PARSER.declareField(optionalConstructorArg(), - (p, c) -> p.text(), FULL_NAME, ObjectParser.ValueType.STRING); - PARSER.declareField(optionalConstructorArg(), - (p, c) -> { - final XContentBuilder jsonBuilder = jsonBuilder().copyCurrentStructure(p); - final BytesReference bytes = BytesReference.bytes(jsonBuilder); - return bytes; - }, MAPPING, ObjectParser.ValueType.OBJECT); + PARSER.declareField(optionalConstructorArg(), (p, c) -> p.text(), FULL_NAME, ObjectParser.ValueType.STRING); + PARSER.declareField(optionalConstructorArg(), (p, c) -> { + final XContentBuilder jsonBuilder = jsonBuilder().copyCurrentStructure(p); + final BytesReference bytes = BytesReference.bytes(jsonBuilder); + return bytes; + }, MAPPING, ObjectParser.ValueType.OBJECT); } private String fullName; @@ -153,7 +153,7 @@ public class GetFieldMappingsResponse { return XContentHelper.convertToMap(source, true, XContentType.JSON).v2(); } - //pkg-private for testing + // pkg-private for testing BytesReference getSource() { return source; } @@ -162,7 +162,7 @@ public class GetFieldMappingsResponse { return PARSER.parse(parser, null); } - @Override + @Override public String toString() { return "FieldMappingMetadata{fullName='" + fullName + '\'' + ", source=" + source + '}'; } @@ -181,10 +181,9 @@ public class GetFieldMappingsResponse { } } - @Override public String toString() { - return "GetFieldMappingsResponse{" + "mappings=" + mappings + '}'; + return "GetFieldMappingsResponse{" + "mappings=" + mappings + '}'; } @Override diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetIndexRequest.java b/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetIndexRequest.java index 0041b7ec487..5e5ab6aeae3 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetIndexRequest.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetIndexRequest.java @@ -141,5 +141,4 @@ public class GetIndexRequest extends TimedRequest { return includeDefaults; } - } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetIndexResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetIndexResponse.java index 59411482b9e..4fa87a28784 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetIndexResponse.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetIndexResponse.java @@ -63,12 +63,14 @@ public class GetIndexResponse { private Map dataStreams; private String[] indices; - GetIndexResponse(String[] indices, - Map mappings, - Map> aliases, - Map settings, - Map defaultSettings, - Map dataStreams) { + GetIndexResponse( + String[] indices, + Map mappings, + Map> aliases, + Map settings, + Map defaultSettings, + Map dataStreams + ) { this.indices = indices; // to have deterministic order Arrays.sort(indices); @@ -205,8 +207,14 @@ public class GetIndexResponse { Settings indexSettings = Settings.EMPTY; Settings indexDefaultSettings = Settings.EMPTY; String dataStream; - IndexEntry(List indexAliases, MappingMetadata indexMappings, Settings indexSettings, Settings indexDefaultSettings, - String dataStream) { + + IndexEntry( + List indexAliases, + MappingMetadata indexMappings, + Settings indexSettings, + Settings indexDefaultSettings, + String dataStream + ) { if (indexAliases != null) this.indexAliases = indexAliases; if (indexMappings != null) this.indexMappings = indexMappings; if (indexSettings != null) this.indexSettings = indexSettings; diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetIndexTemplatesResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetIndexTemplatesResponse.java index cba357b91f1..84ee4c25409 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetIndexTemplatesResponse.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetIndexTemplatesResponse.java @@ -39,8 +39,7 @@ import java.util.Comparator; import java.util.List; import java.util.Objects; - -public class GetIndexTemplatesResponse { +public class GetIndexTemplatesResponse { @Override public String toString() { @@ -63,7 +62,6 @@ public class GetIndexTemplatesResponse { return indexTemplates; } - public static GetIndexTemplatesResponse fromXContent(XContentParser parser) throws IOException { final List templates = new ArrayList<>(); for (XContentParser.Token token = parser.nextToken(); token != XContentParser.Token.END_OBJECT; token = parser.nextToken()) { @@ -84,12 +82,9 @@ public class GetIndexTemplatesResponse { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; // To compare results we need to make sure the templates are listed in the same order GetIndexTemplatesResponse other = (GetIndexTemplatesResponse) obj; List thisList = new ArrayList<>(this.indexTemplates); @@ -99,5 +94,4 @@ public class GetIndexTemplatesResponse { return Objects.equals(thisList, otherList); } - } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetMappingsResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetMappingsResponse.java index f6f32f6ed8e..85841d9e28d 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetMappingsResponse.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetMappingsResponse.java @@ -61,9 +61,7 @@ public class GetMappingsResponse { parser.nextToken(); } - XContentParserUtils.ensureExpectedToken(parser.currentToken(), - XContentParser.Token.START_OBJECT, - parser); + XContentParserUtils.ensureExpectedToken(parser.currentToken(), XContentParser.Token.START_OBJECT, parser); Map parts = parser.map(); @@ -73,8 +71,9 @@ public class GetMappingsResponse { assert entry.getValue() instanceof Map : "expected a map as type mapping, but got: " + entry.getValue().getClass(); @SuppressWarnings("unchecked") - final Map fieldMappings = (Map) ((Map) entry.getValue()) - .get(MAPPINGS.getPreferredName()); + final Map fieldMappings = (Map) ((Map) entry.getValue()).get( + MAPPINGS.getPreferredName() + ); mappings.put(indexName, new MappingMetadata(MapperService.SINGLE_MAPPING_NAME, fieldMappings)); } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/indices/IndexTemplateMetadata.java b/client/rest-high-level/src/main/java/org/opensearch/client/indices/IndexTemplateMetadata.java index 10e5abdc0c7..63ffae0bd4a 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/indices/IndexTemplateMetadata.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/indices/IndexTemplateMetadata.java @@ -51,25 +51,28 @@ import java.util.stream.Collectors; import static org.opensearch.common.xcontent.ConstructingObjectParser.optionalConstructorArg; -public class IndexTemplateMetadata { +public class IndexTemplateMetadata { @SuppressWarnings("unchecked") private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "IndexTemplateMetadata", true, (a, name) -> { - List> alias = (List>) a[5]; - ImmutableOpenMap aliasMap = - new ImmutableOpenMap.Builder() - .putAll(alias.stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))) - .build(); - return new IndexTemplateMetadata( - name, - (Integer) a[0], - (Integer) a[1], - (List) a[2], - (Settings) a[3], - (MappingMetadata) a[4], - aliasMap); - }); + "IndexTemplateMetadata", + true, + (a, name) -> { + List> alias = (List>) a[5]; + ImmutableOpenMap aliasMap = new ImmutableOpenMap.Builder().putAll( + alias.stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)) + ).build(); + return new IndexTemplateMetadata( + name, + (Integer) a[0], + (Integer) a[1], + (List) a[2], + (Settings) a[3], + (MappingMetadata) a[4], + aliasMap + ); + } + ); static { PARSER.declareInt(optionalConstructorArg(), new ParseField("order")); @@ -88,8 +91,11 @@ public class IndexTemplateMetadata { } return new MappingMetadata(MapperService.SINGLE_MAPPING_NAME, mapping); }, new ParseField("mappings")); - PARSER.declareNamedObjects(optionalConstructorArg(), - (p, c, name) -> new AbstractMap.SimpleEntry<>(name, AliasMetadata.Builder.fromXContent(p)), new ParseField("aliases")); + PARSER.declareNamedObjects( + optionalConstructorArg(), + (p, c, name) -> new AbstractMap.SimpleEntry<>(name, AliasMetadata.Builder.fromXContent(p)), + new ParseField("aliases") + ); } private final String name; @@ -124,17 +130,22 @@ public class IndexTemplateMetadata { private final ImmutableOpenMap aliases; - public IndexTemplateMetadata(String name, int order, Integer version, - List patterns, Settings settings, - MappingMetadata mappings, - ImmutableOpenMap aliases) { + public IndexTemplateMetadata( + String name, + int order, + Integer version, + List patterns, + Settings settings, + MappingMetadata mappings, + ImmutableOpenMap aliases + ) { if (patterns == null || patterns.isEmpty()) { throw new IllegalArgumentException("Index patterns must not be null or empty; got " + patterns); } this.name = name; this.order = order; this.version = version; - this.patterns= patterns; + this.patterns = patterns; this.settings = settings; this.mappings = mappings; this.aliases = aliases; @@ -178,13 +189,13 @@ public class IndexTemplateMetadata { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; IndexTemplateMetadata that = (IndexTemplateMetadata) o; - return order == that.order && - Objects.equals(name, that.name) && - Objects.equals(version, that.version) && - Objects.equals(patterns, that.patterns) && - Objects.equals(settings, that.settings) && - Objects.equals(mappings, that.mappings) && - Objects.equals(aliases, that.aliases); + return order == that.order + && Objects.equals(name, that.name) + && Objects.equals(version, that.version) + && Objects.equals(patterns, that.patterns) + && Objects.equals(settings, that.settings) + && Objects.equals(mappings, that.mappings) + && Objects.equals(aliases, that.aliases); } @Override @@ -269,7 +280,6 @@ public class IndexTemplateMetadata { return new IndexTemplateMetadata(name, order, version, indexPatterns, settings, mappings, aliases.build()); } - public static IndexTemplateMetadata fromXContent(XContentParser parser, String templateName) throws IOException { return PARSER.parse(parser, templateName); } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/indices/PutIndexTemplateRequest.java b/client/rest-high-level/src/main/java/org/opensearch/client/indices/PutIndexTemplateRequest.java index 15e23592fb4..f248e8efa24 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/indices/PutIndexTemplateRequest.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/indices/PutIndexTemplateRequest.java @@ -118,7 +118,7 @@ public class PutIndexTemplateRequest extends MasterNodeRequest entry : source.entrySet()) { String name = entry.getKey(); if (name.equals("template")) { - if(entry.getValue() instanceof String) { + if (entry.getValue() instanceof String) { this.template = (String) entry.getValue(); } } else if (name.equals("index_patterns")) { - if(entry.getValue() instanceof String) { + if (entry.getValue() instanceof String) { patterns(Collections.singletonList((String) entry.getValue())); } else if (entry.getValue() instanceof List) { List elements = ((List) entry.getValue()).stream().map(Object::toString).collect(Collectors.toList()); @@ -321,7 +319,7 @@ public class PutIndexTemplateRequest extends MasterNodeRequest aliases() { return this.aliases; } @@ -404,15 +401,20 @@ public class PutIndexTemplateRequest extends MasterNodeRequest PARSER = new ConstructingObjectParser<>("resize_index", - true, args -> new ResizeResponse((boolean) args[0], (boolean) args[1], (String) args[2])); + private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( + "resize_index", + true, + args -> new ResizeResponse((boolean) args[0], (boolean) args[1], (String) args[2]) + ); static { PARSER.declareBoolean(constructorArg(), new ParseField(AcknowledgedResponse.PARSE_FIELD_NAME)); diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/indices/SimulateIndexTemplateResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/indices/SimulateIndexTemplateResponse.java index 6cf6cd25f93..a2156a32fa1 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/indices/SimulateIndexTemplateResponse.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/indices/SimulateIndexTemplateResponse.java @@ -51,20 +51,24 @@ public class SimulateIndexTemplateResponse { private static final ParseField INDEX_PATTERNS = new ParseField("index_patterns"); @SuppressWarnings("unchecked") - private static final ConstructingObjectParser PARSER = - new ConstructingObjectParser<>("simulate_index_templates_response", false, - a -> new SimulateIndexTemplateResponse( - a[0] != null ? (Template) a[0] : null, - a[1] != null ? - ((List) a[1]).stream() - .collect(Collectors.toMap(IndexTemplateAndPatterns::name, IndexTemplateAndPatterns::indexPatterns)) : null - ) - ); + private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( + "simulate_index_templates_response", + false, + a -> new SimulateIndexTemplateResponse( + a[0] != null ? (Template) a[0] : null, + a[1] != null + ? ((List) a[1]).stream() + .collect(Collectors.toMap(IndexTemplateAndPatterns::name, IndexTemplateAndPatterns::indexPatterns)) + : null + ) + ); @SuppressWarnings("unchecked") - private static final ConstructingObjectParser INNER_PARSER = - new ConstructingObjectParser<>("index_template_and_patterns", false, - a -> new IndexTemplateAndPatterns((String) a[0], (List) a[1])); + private static final ConstructingObjectParser INNER_PARSER = new ConstructingObjectParser<>( + "index_template_and_patterns", + false, + a -> new IndexTemplateAndPatterns((String) a[0], (List) a[1]) + ); private static class IndexTemplateAndPatterns { String name; @@ -136,7 +140,11 @@ public class SimulateIndexTemplateResponse { @Override public String toString() { - return "SimulateIndexTemplateResponse{" + "resolved template=" + resolvedTemplate + ", overlapping templates=" - + String.join("|", overlappingTemplates.keySet()) + "}"; + return "SimulateIndexTemplateResponse{" + + "resolved template=" + + resolvedTemplate + + ", overlapping templates=" + + String.join("|", overlappingTemplates.keySet()) + + "}"; } } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/indices/rollover/RolloverRequest.java b/client/rest-high-level/src/main/java/org/opensearch/client/indices/rollover/RolloverRequest.java index 86d54777acc..85f2836db5c 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/indices/rollover/RolloverRequest.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/indices/rollover/RolloverRequest.java @@ -55,7 +55,7 @@ public class RolloverRequest extends TimedRequest implements ToXContentObject { private final String newIndexName; private boolean dryRun; private final Map> conditions = new HashMap<>(2); - //the index name "_na_" is never read back, what matters are settings, mappings and aliases + // the index name "_na_" is never read back, what matters are settings, mappings and aliases private final CreateIndexRequest createIndexRequest = new CreateIndexRequest("_na_"); public RolloverRequest(String alias, String newIndexName) { @@ -80,7 +80,6 @@ public class RolloverRequest extends TimedRequest implements ToXContentObject { return newIndexName; } - /** * Sets if the rollover should not be executed when conditions are met */ @@ -88,6 +87,7 @@ public class RolloverRequest extends TimedRequest implements ToXContentObject { this.dryRun = dryRun; return this; } + /** * Returns if the rollover should not be executed when conditions are met */ @@ -118,6 +118,7 @@ public class RolloverRequest extends TimedRequest implements ToXContentObject { this.conditions.put(maxDocsCondition.name(), maxDocsCondition); return this; } + /** * Adds a size-based condition to check if the index size is at least size. */ @@ -129,6 +130,7 @@ public class RolloverRequest extends TimedRequest implements ToXContentObject { this.conditions.put(maxSizeCondition.name(), maxSizeCondition); return this; } + /** * Returns all set conditions */ diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/indices/rollover/RolloverResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/indices/rollover/RolloverResponse.java index e1950cbc79e..0303dba2535 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/indices/rollover/RolloverResponse.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/indices/rollover/RolloverResponse.java @@ -54,9 +54,19 @@ public final class RolloverResponse extends ShardsAcknowledgedResponse { private static final ParseField CONDITIONS = new ParseField("conditions"); @SuppressWarnings("unchecked") - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>("rollover", - true, args -> new RolloverResponse((String) args[0], (String) args[1], (Map) args[2], - (Boolean)args[3], (Boolean)args[4], (Boolean) args[5], (Boolean) args[6])); + private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( + "rollover", + true, + args -> new RolloverResponse( + (String) args[0], + (String) args[1], + (Map) args[2], + (Boolean) args[3], + (Boolean) args[4], + (Boolean) args[5], + (Boolean) args[6] + ) + ); static { PARSER.declareString(constructorArg(), OLD_INDEX); @@ -73,8 +83,15 @@ public final class RolloverResponse extends ShardsAcknowledgedResponse { private final boolean dryRun; private final boolean rolledOver; - public RolloverResponse(String oldIndex, String newIndex, Map conditionResults, - boolean dryRun, boolean rolledOver, boolean acknowledged, boolean shardsAcknowledged) { + public RolloverResponse( + String oldIndex, + String newIndex, + Map conditionResults, + boolean dryRun, + boolean rolledOver, + boolean acknowledged, + boolean shardsAcknowledged + ) { super(acknowledged, shardsAcknowledged); this.oldIndex = oldIndex; this.newIndex = newIndex; @@ -126,11 +143,11 @@ public final class RolloverResponse extends ShardsAcknowledgedResponse { public boolean equals(Object o) { if (super.equals(o)) { RolloverResponse that = (RolloverResponse) o; - return dryRun == that.dryRun && - rolledOver == that.rolledOver && - Objects.equals(oldIndex, that.oldIndex) && - Objects.equals(newIndex, that.newIndex) && - Objects.equals(conditionStatus, that.conditionStatus); + return dryRun == that.dryRun + && rolledOver == that.rolledOver + && Objects.equals(oldIndex, that.oldIndex) + && Objects.equals(newIndex, that.newIndex) + && Objects.equals(conditionStatus, that.conditionStatus); } return false; } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/slm/ExecuteSnapshotLifecyclePolicyResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/slm/ExecuteSnapshotLifecyclePolicyResponse.java index df5318bed3e..7b22b83bcf5 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/slm/ExecuteSnapshotLifecyclePolicyResponse.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/slm/ExecuteSnapshotLifecyclePolicyResponse.java @@ -43,9 +43,11 @@ import java.io.IOException; public class ExecuteSnapshotLifecyclePolicyResponse implements ToXContentObject { private static final ParseField SNAPSHOT_NAME = new ParseField("snapshot_name"); - private static final ConstructingObjectParser PARSER = - new ConstructingObjectParser<>("excecute_snapshot_policy", true, - a -> new ExecuteSnapshotLifecyclePolicyResponse((String) a[0])); + private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( + "excecute_snapshot_policy", + true, + a -> new ExecuteSnapshotLifecyclePolicyResponse((String) a[0]) + ); static { PARSER.declareString(ConstructingObjectParser.constructorArg(), SNAPSHOT_NAME); diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/slm/ExecuteSnapshotLifecycleRetentionRequest.java b/client/rest-high-level/src/main/java/org/opensearch/client/slm/ExecuteSnapshotLifecycleRetentionRequest.java index 144d4c3ef45..f47382c51e7 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/slm/ExecuteSnapshotLifecycleRetentionRequest.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/slm/ExecuteSnapshotLifecycleRetentionRequest.java @@ -34,5 +34,4 @@ package org.opensearch.client.slm; import org.opensearch.client.TimedRequest; -public class ExecuteSnapshotLifecycleRetentionRequest extends TimedRequest { -} +public class ExecuteSnapshotLifecycleRetentionRequest extends TimedRequest {} diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotInvocationRecord.java b/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotInvocationRecord.java index 817a891f42c..6d60003302a 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotInvocationRecord.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotInvocationRecord.java @@ -50,9 +50,11 @@ public class SnapshotInvocationRecord implements ToXContentObject { private long timestamp; private String details; - public static final ConstructingObjectParser PARSER = - new ConstructingObjectParser<>("snapshot_policy_invocation_record", true, - a -> new SnapshotInvocationRecord((String) a[0], (long) a[1], (String) a[2])); + public static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( + "snapshot_policy_invocation_record", + true, + a -> new SnapshotInvocationRecord((String) a[0], (long) a[1], (String) a[2]) + ); static { PARSER.declareString(ConstructingObjectParser.constructorArg(), SNAPSHOT_NAME); @@ -101,9 +103,9 @@ public class SnapshotInvocationRecord implements ToXContentObject { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SnapshotInvocationRecord that = (SnapshotInvocationRecord) o; - return getTimestamp() == that.getTimestamp() && - Objects.equals(getSnapshotName(), that.getSnapshotName()) && - Objects.equals(getDetails(), that.getDetails()); + return getTimestamp() == that.getTimestamp() + && Objects.equals(getSnapshotName(), that.getSnapshotName()) + && Objects.equals(getDetails(), that.getDetails()); } @Override diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecycleManagementStatusRequest.java b/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecycleManagementStatusRequest.java index 6b7923c2cbe..d7abe3592d3 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecycleManagementStatusRequest.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecycleManagementStatusRequest.java @@ -34,5 +34,4 @@ package org.opensearch.client.slm; import org.opensearch.client.TimedRequest; -public class SnapshotLifecycleManagementStatusRequest extends TimedRequest { -} +public class SnapshotLifecycleManagementStatusRequest extends TimedRequest {} diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecyclePolicy.java b/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecyclePolicy.java index 8ec7e8d36b4..a6e08fc6df0 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecyclePolicy.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecyclePolicy.java @@ -60,16 +60,18 @@ public class SnapshotLifecyclePolicy implements ToXContentObject { private static final ParseField RETENTION = new ParseField("retention"); @SuppressWarnings("unchecked") - private static final ConstructingObjectParser PARSER = - new ConstructingObjectParser<>("snapshot_lifecycle", true, - (a, id) -> { - String name = (String) a[0]; - String schedule = (String) a[1]; - String repo = (String) a[2]; - Map config = (Map) a[3]; - SnapshotRetentionConfiguration retention = (SnapshotRetentionConfiguration) a[4]; - return new SnapshotLifecyclePolicy(id, name, schedule, repo, config, retention); - }); + private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( + "snapshot_lifecycle", + true, + (a, id) -> { + String name = (String) a[0]; + String schedule = (String) a[1]; + String repo = (String) a[2]; + Map config = (Map) a[3]; + SnapshotRetentionConfiguration retention = (SnapshotRetentionConfiguration) a[4]; + return new SnapshotLifecyclePolicy(id, name, schedule, repo, config, retention); + } + ); static { PARSER.declareString(ConstructingObjectParser.constructorArg(), NAME); @@ -79,9 +81,14 @@ public class SnapshotLifecyclePolicy implements ToXContentObject { PARSER.declareObject(ConstructingObjectParser.optionalConstructorArg(), SnapshotRetentionConfiguration::parse, RETENTION); } - public SnapshotLifecyclePolicy(final String id, final String name, final String schedule, - final String repository, @Nullable final Map configuration, - @Nullable final SnapshotRetentionConfiguration retentionPolicy) { + public SnapshotLifecyclePolicy( + final String id, + final String name, + final String schedule, + final String repository, + @Nullable final Map configuration, + @Nullable final SnapshotRetentionConfiguration retentionPolicy + ) { this.id = Objects.requireNonNull(id, "policy id is required"); this.name = Objects.requireNonNull(name, "policy snapshot name is required"); this.schedule = Objects.requireNonNull(schedule, "policy schedule is required"); @@ -151,12 +158,12 @@ public class SnapshotLifecyclePolicy implements ToXContentObject { return false; } SnapshotLifecyclePolicy other = (SnapshotLifecyclePolicy) obj; - return Objects.equals(id, other.id) && - Objects.equals(name, other.name) && - Objects.equals(schedule, other.schedule) && - Objects.equals(repository, other.repository) && - Objects.equals(configuration, other.configuration) && - Objects.equals(retentionPolicy, other.retentionPolicy); + return Objects.equals(id, other.id) + && Objects.equals(name, other.name) + && Objects.equals(schedule, other.schedule) + && Objects.equals(repository, other.repository) + && Objects.equals(configuration, other.configuration) + && Objects.equals(retentionPolicy, other.retentionPolicy); } @Override diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecyclePolicyMetadata.java b/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecyclePolicyMetadata.java index 49c4930279e..199805d348f 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecyclePolicyMetadata.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecyclePolicyMetadata.java @@ -70,20 +70,20 @@ public class SnapshotLifecyclePolicyMetadata implements ToXContentObject { private final SnapshotLifecycleStats.SnapshotPolicyStats policyStats; @SuppressWarnings("unchecked") - public static final ConstructingObjectParser PARSER = - new ConstructingObjectParser<>("snapshot_policy_metadata", - a -> { - SnapshotLifecyclePolicy policy = (SnapshotLifecyclePolicy) a[0]; - long version = (long) a[1]; - long modifiedDate = (long) a[2]; - SnapshotInvocationRecord lastSuccess = (SnapshotInvocationRecord) a[3]; - SnapshotInvocationRecord lastFailure = (SnapshotInvocationRecord) a[4]; - long nextExecution = (long) a[5]; - SnapshotInProgress sip = (SnapshotInProgress) a[6]; - SnapshotLifecycleStats.SnapshotPolicyStats stats = (SnapshotLifecycleStats.SnapshotPolicyStats) a[7]; - return new SnapshotLifecyclePolicyMetadata(policy, version, modifiedDate, lastSuccess, - lastFailure, nextExecution, sip, stats); - }); + public static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( + "snapshot_policy_metadata", + a -> { + SnapshotLifecyclePolicy policy = (SnapshotLifecyclePolicy) a[0]; + long version = (long) a[1]; + long modifiedDate = (long) a[2]; + SnapshotInvocationRecord lastSuccess = (SnapshotInvocationRecord) a[3]; + SnapshotInvocationRecord lastFailure = (SnapshotInvocationRecord) a[4]; + long nextExecution = (long) a[5]; + SnapshotInProgress sip = (SnapshotInProgress) a[6]; + SnapshotLifecycleStats.SnapshotPolicyStats stats = (SnapshotLifecycleStats.SnapshotPolicyStats) a[7]; + return new SnapshotLifecyclePolicyMetadata(policy, version, modifiedDate, lastSuccess, lastFailure, nextExecution, sip, stats); + } + ); static { PARSER.declareObject(ConstructingObjectParser.constructorArg(), SnapshotLifecyclePolicy::parse, POLICY); @@ -93,8 +93,11 @@ public class SnapshotLifecyclePolicyMetadata implements ToXContentObject { PARSER.declareObject(ConstructingObjectParser.optionalConstructorArg(), SnapshotInvocationRecord::parse, LAST_FAILURE); PARSER.declareLong(ConstructingObjectParser.constructorArg(), NEXT_EXECUTION_MILLIS); PARSER.declareObject(ConstructingObjectParser.optionalConstructorArg(), SnapshotInProgress::parse, SNAPSHOT_IN_PROGRESS); - PARSER.declareObject(ConstructingObjectParser.constructorArg(), - (p, c) -> SnapshotLifecycleStats.SnapshotPolicyStats.parse(p, "policy"), POLICY_STATS); + PARSER.declareObject( + ConstructingObjectParser.constructorArg(), + (p, c) -> SnapshotLifecycleStats.SnapshotPolicyStats.parse(p, "policy"), + POLICY_STATS + ); } @@ -102,11 +105,16 @@ public class SnapshotLifecyclePolicyMetadata implements ToXContentObject { return PARSER.apply(parser, id); } - public SnapshotLifecyclePolicyMetadata(SnapshotLifecyclePolicy policy, long version, long modifiedDate, - SnapshotInvocationRecord lastSuccess, SnapshotInvocationRecord lastFailure, - long nextExecution, - @Nullable SnapshotInProgress snapshotInProgress, - SnapshotLifecycleStats.SnapshotPolicyStats policyStats) { + public SnapshotLifecyclePolicyMetadata( + SnapshotLifecyclePolicy policy, + long version, + long modifiedDate, + SnapshotInvocationRecord lastSuccess, + SnapshotInvocationRecord lastFailure, + long nextExecution, + @Nullable SnapshotInProgress snapshotInProgress, + SnapshotLifecycleStats.SnapshotPolicyStats policyStats + ) { this.policy = policy; this.version = version; this.modifiedDate = modifiedDate; @@ -191,13 +199,13 @@ public class SnapshotLifecyclePolicyMetadata implements ToXContentObject { return false; } SnapshotLifecyclePolicyMetadata other = (SnapshotLifecyclePolicyMetadata) obj; - return Objects.equals(policy, other.policy) && - Objects.equals(version, other.version) && - Objects.equals(modifiedDate, other.modifiedDate) && - Objects.equals(lastSuccess, other.lastSuccess) && - Objects.equals(lastFailure, other.lastFailure) && - Objects.equals(nextExecution, other.nextExecution) && - Objects.equals(policyStats, other.policyStats); + return Objects.equals(policy, other.policy) + && Objects.equals(version, other.version) + && Objects.equals(modifiedDate, other.modifiedDate) + && Objects.equals(lastSuccess, other.lastSuccess) + && Objects.equals(lastFailure, other.lastFailure) + && Objects.equals(nextExecution, other.nextExecution) + && Objects.equals(policyStats, other.policyStats); } public static class SnapshotInProgress implements ToXContentObject { @@ -207,14 +215,17 @@ public class SnapshotLifecyclePolicyMetadata implements ToXContentObject { private static final ParseField START_TIME = new ParseField("start_time_millis"); private static final ParseField FAILURE = new ParseField("failure"); - private static final ConstructingObjectParser PARSER = - new ConstructingObjectParser<>("snapshot_in_progress", true, a -> { + private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( + "snapshot_in_progress", + true, + a -> { SnapshotId id = new SnapshotId((String) a[0], (String) a[1]); String state = (String) a[2]; long start = (long) a[3]; String failure = (String) a[4]; return new SnapshotInProgress(id, state, start, failure); - }); + } + ); static { PARSER.declareString(ConstructingObjectParser.constructorArg(), NAME); @@ -269,10 +280,10 @@ public class SnapshotLifecyclePolicyMetadata implements ToXContentObject { return false; } SnapshotInProgress other = (SnapshotInProgress) obj; - return Objects.equals(snapshotId, other.snapshotId) && - Objects.equals(state, other.state) && - startTime == other.startTime && - Objects.equals(failure, other.failure); + return Objects.equals(snapshotId, other.snapshotId) + && Objects.equals(state, other.state) + && startTime == other.startTime + && Objects.equals(failure, other.failure); } @Override diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecycleStats.java b/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecycleStats.java index 9299b9733f2..74d3d219524 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecycleStats.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecycleStats.java @@ -68,19 +68,20 @@ public class SnapshotLifecycleStats implements ToXContentObject { public static final ParseField TOTAL_DELETIONS = new ParseField("total_snapshots_deleted"); public static final ParseField TOTAL_DELETION_FAILURES = new ParseField("total_snapshot_deletion_failures"); - @SuppressWarnings("unchecked") - private static final ConstructingObjectParser PARSER = - new ConstructingObjectParser<>("snapshot_policy_stats", true, - a -> { - long runs = (long) a[0]; - long failed = (long) a[1]; - long timedOut = (long) a[2]; - long timeMs = (long) a[3]; - Map policyStatsMap = ((List) a[4]).stream() - .collect(Collectors.toMap(m -> m.policyId, Function.identity())); - return new SnapshotLifecycleStats(runs, failed, timedOut, timeMs, policyStatsMap); - }); + private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( + "snapshot_policy_stats", + true, + a -> { + long runs = (long) a[0]; + long failed = (long) a[1]; + long timedOut = (long) a[2]; + long timeMs = (long) a[3]; + Map policyStatsMap = ((List) a[4]).stream() + .collect(Collectors.toMap(m -> m.policyId, Function.identity())); + return new SnapshotLifecycleStats(runs, failed, timedOut, timeMs, policyStatsMap); + } + ); static { PARSER.declareLong(ConstructingObjectParser.constructorArg(), RETENTION_RUNS); @@ -91,8 +92,13 @@ public class SnapshotLifecycleStats implements ToXContentObject { } // Package visible for testing - private SnapshotLifecycleStats(long retentionRuns, long retentionFailed, long retentionTimedOut, long retentionTimeMs, - Map policyStats) { + private SnapshotLifecycleStats( + long retentionRuns, + long retentionFailed, + long retentionTimedOut, + long retentionTimeMs, + Map policyStats + ) { this.retentionRunCount = retentionRuns; this.retentionFailedCount = retentionFailed; this.retentionTimedOut = retentionTimedOut; @@ -172,11 +178,11 @@ public class SnapshotLifecycleStats implements ToXContentObject { return false; } SnapshotLifecycleStats other = (SnapshotLifecycleStats) obj; - return retentionRunCount == other.retentionRunCount && - retentionFailedCount == other.retentionFailedCount && - retentionTimedOut == other.retentionTimedOut && - retentionTimeMs == other.retentionTimeMs && - Objects.equals(policyStats, other.policyStats); + return retentionRunCount == other.retentionRunCount + && retentionFailedCount == other.retentionFailedCount + && retentionTimedOut == other.retentionTimedOut + && retentionTimeMs == other.retentionTimeMs + && Objects.equals(policyStats, other.policyStats); } @Override @@ -197,16 +203,18 @@ public class SnapshotLifecycleStats implements ToXContentObject { static final ParseField SNAPSHOTS_DELETED = new ParseField("snapshots_deleted"); static final ParseField SNAPSHOT_DELETION_FAILURES = new ParseField("snapshot_deletion_failures"); - private static final ConstructingObjectParser PARSER = - new ConstructingObjectParser<>("snapshot_policy_stats", true, - a -> { - String id = (String) a[0]; - long taken = (long) a[1]; - long failed = (long) a[2]; - long deleted = (long) a[3]; - long deleteFailed = (long) a[4]; - return new SnapshotPolicyStats(id, taken, failed, deleted, deleteFailed); - }); + private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( + "snapshot_policy_stats", + true, + a -> { + String id = (String) a[0]; + long taken = (long) a[1]; + long failed = (long) a[2]; + long deleted = (long) a[3]; + long deleteFailed = (long) a[4]; + return new SnapshotPolicyStats(id, taken, failed, deleted, deleteFailed); + } + ); static { PARSER.declareString(ConstructingObjectParser.constructorArg(), POLICY_ID); @@ -262,11 +270,11 @@ public class SnapshotLifecycleStats implements ToXContentObject { return false; } SnapshotPolicyStats other = (SnapshotPolicyStats) obj; - return Objects.equals(policyId, other.policyId) && - snapshotsTaken == other.snapshotsTaken && - snapshotsFailed == other.snapshotsFailed && - snapshotsDeleted == other.snapshotsDeleted && - snapshotDeleteFailures == other.snapshotDeleteFailures; + return Objects.equals(policyId, other.policyId) + && snapshotsTaken == other.snapshotsTaken + && snapshotsFailed == other.snapshotsFailed + && snapshotsDeleted == other.snapshotsDeleted + && snapshotDeleteFailures == other.snapshotDeleteFailures; } @Override diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotRetentionConfiguration.java b/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotRetentionConfiguration.java index 8a4c59c982e..2f2aa778b69 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotRetentionConfiguration.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotRetentionConfiguration.java @@ -52,13 +52,16 @@ public class SnapshotRetentionConfiguration implements ToXContentObject { private static final ParseField MINIMUM_SNAPSHOT_COUNT = new ParseField("min_count"); private static final ParseField MAXIMUM_SNAPSHOT_COUNT = new ParseField("max_count"); - private static final ConstructingObjectParser PARSER = - new ConstructingObjectParser<>("snapshot_retention", true, a -> { + private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( + "snapshot_retention", + true, + a -> { TimeValue expireAfter = a[0] == null ? null : TimeValue.parseTimeValue((String) a[0], EXPIRE_AFTER.getPreferredName()); Integer minCount = (Integer) a[1]; Integer maxCount = (Integer) a[2]; return new SnapshotRetentionConfiguration(expireAfter, minCount, maxCount); - }); + } + ); static { PARSER.declareString(ConstructingObjectParser.optionalConstructorArg(), EXPIRE_AFTER); @@ -70,9 +73,11 @@ public class SnapshotRetentionConfiguration implements ToXContentObject { private final Integer minimumSnapshotCount; private final Integer maximumSnapshotCount; - public SnapshotRetentionConfiguration(@Nullable TimeValue expireAfter, - @Nullable Integer minimumSnapshotCount, - @Nullable Integer maximumSnapshotCount) { + public SnapshotRetentionConfiguration( + @Nullable TimeValue expireAfter, + @Nullable Integer minimumSnapshotCount, + @Nullable Integer maximumSnapshotCount + ) { this.expireAfter = expireAfter; this.minimumSnapshotCount = minimumSnapshotCount; this.maximumSnapshotCount = maximumSnapshotCount; @@ -83,8 +88,12 @@ public class SnapshotRetentionConfiguration implements ToXContentObject { throw new IllegalArgumentException("maximum snapshot count must be at least 1, but was: " + this.maximumSnapshotCount); } if ((maximumSnapshotCount != null && minimumSnapshotCount != null) && this.minimumSnapshotCount > this.maximumSnapshotCount) { - throw new IllegalArgumentException("minimum snapshot count " + this.minimumSnapshotCount + - " cannot be larger than maximum snapshot count " + this.maximumSnapshotCount); + throw new IllegalArgumentException( + "minimum snapshot count " + + this.minimumSnapshotCount + + " cannot be larger than maximum snapshot count " + + this.maximumSnapshotCount + ); } } @@ -134,9 +143,9 @@ public class SnapshotRetentionConfiguration implements ToXContentObject { return false; } SnapshotRetentionConfiguration other = (SnapshotRetentionConfiguration) obj; - return Objects.equals(this.expireAfter, other.expireAfter) && - Objects.equals(minimumSnapshotCount, other.minimumSnapshotCount) && - Objects.equals(maximumSnapshotCount, other.maximumSnapshotCount); + return Objects.equals(this.expireAfter, other.expireAfter) + && Objects.equals(minimumSnapshotCount, other.minimumSnapshotCount) + && Objects.equals(maximumSnapshotCount, other.maximumSnapshotCount); } @Override diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/slm/StartSLMRequest.java b/client/rest-high-level/src/main/java/org/opensearch/client/slm/StartSLMRequest.java index 74af44e129b..875b82caf5d 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/slm/StartSLMRequest.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/slm/StartSLMRequest.java @@ -34,5 +34,4 @@ package org.opensearch.client.slm; import org.opensearch.client.TimedRequest; -public class StartSLMRequest extends TimedRequest { -} +public class StartSLMRequest extends TimedRequest {} diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/slm/StopSLMRequest.java b/client/rest-high-level/src/main/java/org/opensearch/client/slm/StopSLMRequest.java index 609dec36d65..bf20be79fcb 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/slm/StopSLMRequest.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/slm/StopSLMRequest.java @@ -34,5 +34,4 @@ package org.opensearch.client.slm; import org.opensearch.client.TimedRequest; -public class StopSLMRequest extends TimedRequest { -} +public class StopSLMRequest extends TimedRequest {} diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/CancelTasksRequest.java b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/CancelTasksRequest.java index 239048a0433..aab9f497a84 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/CancelTasksRequest.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/CancelTasksRequest.java @@ -48,7 +48,7 @@ public class CancelTasksRequest implements Validatable { private Optional taskId = Optional.empty(); private Boolean waitForCompletion; - CancelTasksRequest(){} + CancelTasksRequest() {} void setNodes(List nodes) { this.nodes.addAll(nodes); @@ -103,12 +103,12 @@ public class CancelTasksRequest implements Validatable { if (this == o) return true; if (!(o instanceof CancelTasksRequest)) return false; CancelTasksRequest that = (CancelTasksRequest) o; - return Objects.equals(getNodes(), that.getNodes()) && - Objects.equals(getActions(), that.getActions()) && - Objects.equals(getTimeout(), that.getTimeout()) && - Objects.equals(getParentTaskId(), that.getParentTaskId()) && - Objects.equals(getTaskId(), that.getTaskId()) && - Objects.equals(waitForCompletion, that.waitForCompletion); + return Objects.equals(getNodes(), that.getNodes()) + && Objects.equals(getActions(), that.getActions()) + && Objects.equals(getTimeout(), that.getTimeout()) + && Objects.equals(getParentTaskId(), that.getParentTaskId()) + && Objects.equals(getTaskId(), that.getTaskId()) + && Objects.equals(waitForCompletion, that.waitForCompletion); } @Override @@ -118,14 +118,20 @@ public class CancelTasksRequest implements Validatable { @Override public String toString() { - return "CancelTasksRequest{" + - "nodes=" + nodes + - ", actions=" + actions + - ", timeout=" + timeout + - ", parentTaskId=" + parentTaskId + - ", taskId=" + taskId + - ", waitForCompletion=" + waitForCompletion + - '}'; + return "CancelTasksRequest{" + + "nodes=" + + nodes + + ", actions=" + + actions + + ", timeout=" + + timeout + + ", parentTaskId=" + + parentTaskId + + ", taskId=" + + taskId + + ", waitForCompletion=" + + waitForCompletion + + '}'; } public static class Builder { @@ -136,28 +142,28 @@ public class CancelTasksRequest implements Validatable { private List nodesFilter = new ArrayList<>(); private Boolean waitForCompletion; - public Builder withTimeout(TimeValue timeout){ + public Builder withTimeout(TimeValue timeout) { this.timeout = Optional.of(timeout); return this; } - public Builder withTaskId(TaskId taskId){ + public Builder withTaskId(TaskId taskId) { this.taskId = Optional.of(taskId); return this; } - public Builder withParentTaskId(TaskId taskId){ + public Builder withParentTaskId(TaskId taskId) { this.parentTaskId = Optional.of(taskId); return this; } - public Builder withActionsFiltered(List actions){ + public Builder withActionsFiltered(List actions) { this.actionsFilter.clear(); this.actionsFilter.addAll(actions); return this; } - public Builder withNodesFiltered(List nodes){ + public Builder withNodesFiltered(List nodes) { this.nodesFilter.clear(); this.nodesFilter.addAll(nodes); return this; diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/CancelTasksResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/CancelTasksResponse.java index b281f741bd1..9319e7aa5d2 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/CancelTasksResponse.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/CancelTasksResponse.java @@ -48,9 +48,7 @@ import static org.opensearch.common.xcontent.ConstructingObjectParser.optionalCo */ public class CancelTasksResponse extends ListTasksResponse { - CancelTasksResponse(List nodesInfoData, - List taskFailures, - List nodeFailures) { + CancelTasksResponse(List nodesInfoData, List taskFailures, List nodeFailures) { super(nodesInfoData, taskFailures, nodeFailures); } @@ -61,7 +59,9 @@ public class CancelTasksResponse extends ListTasksResponse { private static ConstructingObjectParser PARSER; static { - ConstructingObjectParser parser = new ConstructingObjectParser<>("cancel_tasks_response", true, + ConstructingObjectParser parser = new ConstructingObjectParser<>( + "cancel_tasks_response", + true, constructingObjects -> { int i = 0; @SuppressWarnings("unchecked") @@ -71,12 +71,15 @@ public class CancelTasksResponse extends ListTasksResponse { @SuppressWarnings("unchecked") List nodesInfoData = (List) constructingObjects[i]; return new CancelTasksResponse(nodesInfoData, tasksFailures, nodeFailures); - }); + } + ); - parser.declareObjectArray(optionalConstructorArg(), (p, c) -> - TaskOperationFailure.fromXContent(p), new ParseField("task_failures")); - parser.declareObjectArray(optionalConstructorArg(), (p, c) -> - OpenSearchException.fromXContent(p), new ParseField("node_failures")); + parser.declareObjectArray( + optionalConstructorArg(), + (p, c) -> TaskOperationFailure.fromXContent(p), + new ParseField("task_failures") + ); + parser.declareObjectArray(optionalConstructorArg(), (p, c) -> OpenSearchException.fromXContent(p), new ParseField("node_failures")); parser.declareNamedObjects(optionalConstructorArg(), NodeData.PARSER, new ParseField("nodes")); PARSER = parser; } @@ -93,12 +96,17 @@ public class CancelTasksResponse extends ListTasksResponse { @Override public String toString() { - return "CancelTasksResponse{" + - "taskFailures=" + taskFailures + - ", nodeFailures=" + nodeFailures + - ", nodesInfoData=" + nodesInfoData + - ", tasks=" + tasks + - ", taskGroups=" + taskGroups + - '}'; + return "CancelTasksResponse{" + + "taskFailures=" + + taskFailures + + ", nodeFailures=" + + nodeFailures + + ", nodesInfoData=" + + nodesInfoData + + ", tasks=" + + tasks + + ", taskGroups=" + + taskGroups + + '}'; } } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/GetTaskRequest.java b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/GetTaskRequest.java index 58aecf8b109..67dd469ccb5 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/GetTaskRequest.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/GetTaskRequest.java @@ -113,9 +113,9 @@ public class GetTaskRequest implements Validatable { return false; } GetTaskRequest other = (GetTaskRequest) obj; - return Objects.equals(nodeId, other.nodeId) && - taskId == other.taskId && - waitForCompletion == other.waitForCompletion && - Objects.equals(timeout, other.timeout); + return Objects.equals(nodeId, other.nodeId) + && taskId == other.taskId + && waitForCompletion == other.waitForCompletion + && Objects.equals(timeout, other.timeout); } } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/GetTaskResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/GetTaskResponse.java index b906bca8d11..09aed03f266 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/GetTaskResponse.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/GetTaskResponse.java @@ -57,8 +57,11 @@ public class GetTaskResponse { return taskInfo; } - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>("get_task", - true, a -> new GetTaskResponse((boolean) a[0], (TaskInfo) a[1])); + private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( + "get_task", + true, + a -> new GetTaskResponse((boolean) a[0], (TaskInfo) a[1]) + ); static { PARSER.declareBoolean(constructorArg(), COMPLETED); PARSER.declareObject(constructorArg(), (p, c) -> TaskInfo.fromXContent(p), TASK); diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/ListTasksResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/ListTasksResponse.java index 3ec36379ba2..a34e5d4cf45 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/ListTasksResponse.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/ListTasksResponse.java @@ -50,9 +50,7 @@ public class ListTasksResponse { protected final List tasks = new ArrayList<>(); protected final List taskGroups = new ArrayList<>(); - ListTasksResponse(List nodesInfoData, - List taskFailures, - List nodeFailures) { + ListTasksResponse(List nodesInfoData, List taskFailures, List nodeFailures) { if (taskFailures != null) { this.taskFailures.addAll(taskFailures); } @@ -62,12 +60,7 @@ public class ListTasksResponse { if (nodesInfoData != null) { this.nodesInfoData.addAll(nodesInfoData); } - this.tasks.addAll(this - .nodesInfoData - .stream() - .flatMap(nodeData -> nodeData.getTasks().stream()) - .collect(toList()) - ); + this.tasks.addAll(this.nodesInfoData.stream().flatMap(nodeData -> nodeData.getTasks().stream()).collect(toList())); this.taskGroups.addAll(buildTaskGroups()); } @@ -104,9 +97,7 @@ public class ListTasksResponse { } public Map> getPerNodeTasks() { - return getTasks() - .stream() - .collect(groupingBy(TaskInfo::getNodeId)); + return getTasks().stream().collect(groupingBy(TaskInfo::getNodeId)); } public List getTaskFailures() { @@ -126,12 +117,11 @@ public class ListTasksResponse { if (this == o) return true; if (!(o instanceof ListTasksResponse)) return false; ListTasksResponse response = (ListTasksResponse) o; - return nodesInfoData.equals(response.nodesInfoData) && - Objects.equals - (getTaskFailures(), response.getTaskFailures()) && - Objects.equals(getNodeFailures(), response.getNodeFailures()) && - Objects.equals(getTasks(), response.getTasks()) && - Objects.equals(getTaskGroups(), response.getTaskGroups()); + return nodesInfoData.equals(response.nodesInfoData) + && Objects.equals(getTaskFailures(), response.getTaskFailures()) + && Objects.equals(getNodeFailures(), response.getNodeFailures()) + && Objects.equals(getTasks(), response.getTasks()) + && Objects.equals(getTaskGroups(), response.getTaskGroups()); } @Override @@ -141,12 +131,17 @@ public class ListTasksResponse { @Override public String toString() { - return "CancelTasksResponse{" + - "nodesInfoData=" + nodesInfoData + - ", taskFailures=" + taskFailures + - ", nodeFailures=" + nodeFailures + - ", tasks=" + tasks + - ", taskGroups=" + taskGroups + - '}'; + return "CancelTasksResponse{" + + "nodesInfoData=" + + nodesInfoData + + ", taskFailures=" + + taskFailures + + ", nodeFailures=" + + nodeFailures + + ", tasks=" + + tasks + + ", taskGroups=" + + taskGroups + + '}'; } } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/NodeData.java b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/NodeData.java index 3c68cf6ad0c..5449039e1ee 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/NodeData.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/NodeData.java @@ -48,7 +48,7 @@ class NodeData { private String host; private String ip; private final List roles = new ArrayList<>(); - private final Map attributes = new HashMap<>(); + private final Map attributes = new HashMap<>(); private final List tasks = new ArrayList<>(); NodeData(String nodeId) { @@ -60,7 +60,7 @@ class NodeData { } public void setAttributes(Map attributes) { - if(attributes!=null){ + if (attributes != null) { this.attributes.putAll(attributes); } } @@ -78,7 +78,7 @@ class NodeData { } void setRoles(List roles) { - if(roles!=null){ + if (roles != null) { this.roles.addAll(roles); } } @@ -116,22 +116,34 @@ class NodeData { } void setTasks(List tasks) { - if(tasks!=null){ + if (tasks != null) { this.tasks.addAll(tasks); } } @Override public String toString() { - return "NodeData{" + - "nodeId='" + nodeId + '\'' + - ", name='" + name + '\'' + - ", transportAddress='" + transportAddress + '\'' + - ", host='" + host + '\'' + - ", ip='" + ip + '\'' + - ", roles=" + roles + - ", attributes=" + attributes + - '}'; + return "NodeData{" + + "nodeId='" + + nodeId + + '\'' + + ", name='" + + name + + '\'' + + ", transportAddress='" + + transportAddress + + '\'' + + ", host='" + + host + + '\'' + + ", ip='" + + ip + + '\'' + + ", roles=" + + roles + + ", attributes=" + + attributes + + '}'; } @Override @@ -139,14 +151,14 @@ class NodeData { if (this == o) return true; if (!(o instanceof NodeData)) return false; NodeData nodeData = (NodeData) o; - return Objects.equals(getNodeId(), nodeData.getNodeId()) && - Objects.equals(getName(), nodeData.getName()) && - Objects.equals(getTransportAddress(), nodeData.getTransportAddress()) && - Objects.equals(getHost(), nodeData.getHost()) && - Objects.equals(getIp(), nodeData.getIp()) && - Objects.equals(getRoles(), nodeData.getRoles()) && - Objects.equals(getAttributes(), nodeData.getAttributes()) && - Objects.equals(getTasks(), nodeData.getTasks()); + return Objects.equals(getNodeId(), nodeData.getNodeId()) + && Objects.equals(getName(), nodeData.getName()) + && Objects.equals(getTransportAddress(), nodeData.getTransportAddress()) + && Objects.equals(getHost(), nodeData.getHost()) + && Objects.equals(getIp(), nodeData.getIp()) + && Objects.equals(getRoles(), nodeData.getRoles()) + && Objects.equals(getAttributes(), nodeData.getAttributes()) + && Objects.equals(getTasks(), nodeData.getTasks()); } @Override @@ -163,10 +175,7 @@ class NodeData { parser.declareString(NodeData::setHost, new ParseField("host")); parser.declareString(NodeData::setIp, new ParseField("ip")); parser.declareStringArray(NodeData::setRoles, new ParseField("roles")); - parser.declareField(NodeData::setAttributes, - (p, c) -> p.mapStrings(), - new ParseField("attributes"), - ObjectParser.ValueType.OBJECT); + parser.declareField(NodeData::setAttributes, (p, c) -> p.mapStrings(), new ParseField("attributes"), ObjectParser.ValueType.OBJECT); parser.declareNamedObjects(NodeData::setTasks, TaskInfo.PARSER, new ParseField("tasks")); PARSER = (XContentParser p, Void v, String nodeId) -> parser.parse(p, new NodeData(nodeId), null); } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/OpenSearchException.java b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/OpenSearchException.java index a52133a4599..777da5fc7b6 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/OpenSearchException.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/OpenSearchException.java @@ -30,6 +30,7 @@ */ package org.opensearch.client.tasks; + import org.opensearch.common.ParseField; import org.opensearch.common.xcontent.XContentParser; import java.io.IOException; @@ -83,7 +84,7 @@ public class OpenSearchException { return suppressed; } - void addSuppressed(List suppressed){ + void addSuppressed(List suppressed) { this.suppressed.addAll(suppressed); } @@ -191,7 +192,7 @@ public class OpenSearchException { } void addHeader(String key, List value) { - headers.put(key,value); + headers.put(key, value); } @@ -215,10 +216,10 @@ public class OpenSearchException { if (this == o) return true; if (!(o instanceof OpenSearchException)) return false; OpenSearchException that = (OpenSearchException) o; - return Objects.equals(getMsg(), that.getMsg()) && - Objects.equals(getCause(), that.getCause()) && - Objects.equals(getHeaders(), that.getHeaders()) && - Objects.equals(getSuppressed(), that.getSuppressed()); + return Objects.equals(getMsg(), that.getMsg()) + && Objects.equals(getCause(), that.getCause()) + && Objects.equals(getHeaders(), that.getHeaders()) + && Objects.equals(getSuppressed(), that.getSuppressed()); } @Override @@ -228,11 +229,16 @@ public class OpenSearchException { @Override public String toString() { - return "OpenSearchException{" + - "msg='" + msg + '\'' + - ", cause=" + cause + - ", headers=" + headers + - ", suppressed=" + suppressed + - '}'; + return "OpenSearchException{" + + "msg='" + + msg + + '\'' + + ", cause=" + + cause + + ", headers=" + + headers + + ", suppressed=" + + suppressed + + '}'; } } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/TaskGroup.java b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/TaskGroup.java index d136722e980..c4198847005 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/TaskGroup.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/TaskGroup.java @@ -47,10 +47,7 @@ public class TaskGroup { @Override public String toString() { - return "TaskGroup{" + - "task=" + task + - ", childTasks=" + childTasks + - '}'; + return "TaskGroup{" + "task=" + task + ", childTasks=" + childTasks + '}'; } private final List childTasks = new ArrayList<>(); @@ -69,8 +66,7 @@ public class TaskGroup { if (this == o) return true; if (!(o instanceof TaskGroup)) return false; TaskGroup taskGroup = (TaskGroup) o; - return Objects.equals(task, taskGroup.task) && - Objects.equals(getChildTasks(), taskGroup.getChildTasks()); + return Objects.equals(task, taskGroup.task) && Objects.equals(getChildTasks(), taskGroup.getChildTasks()); } @Override @@ -96,10 +92,7 @@ public class TaskGroup { } public TaskGroup build() { - return new TaskGroup( - taskInfo, - childTasks.stream().map(TaskGroup.Builder::build).collect(Collectors.toList()) - ); + return new TaskGroup(taskInfo, childTasks.stream().map(TaskGroup.Builder::build).collect(Collectors.toList())); } } @@ -111,4 +104,3 @@ public class TaskGroup { return childTasks; } } - diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/TaskId.java b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/TaskId.java index b43c18ccc43..cd036a73295 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/TaskId.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/TaskId.java @@ -87,14 +87,12 @@ public class TaskId { } } - @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof TaskId)) return false; TaskId taskId = (TaskId) o; - return getId() == taskId.getId() && - Objects.equals(getNodeId(), taskId.getNodeId()); + return getId() == taskId.getId() && Objects.equals(getNodeId(), taskId.getNodeId()); } @Override diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/TaskInfo.java b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/TaskInfo.java index 96a15c6c4b5..062fbe56e4e 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/TaskInfo.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/TaskInfo.java @@ -168,40 +168,60 @@ public class TaskInfo { if (this == o) return true; if (!(o instanceof TaskInfo)) return false; TaskInfo taskInfo = (TaskInfo) o; - return getStartTime() == taskInfo.getStartTime() && - getRunningTimeNanos() == taskInfo.getRunningTimeNanos() && - isCancellable() == taskInfo.isCancellable() && - Objects.equals(getTaskId(), taskInfo.getTaskId()) && - Objects.equals(getType(), taskInfo.getType()) && - Objects.equals(getAction(), taskInfo.getAction()) && - Objects.equals(getDescription(), taskInfo.getDescription()) && - Objects.equals(getParentTaskId(), taskInfo.getParentTaskId()) && - Objects.equals(status, taskInfo.status) && - Objects.equals(getHeaders(), taskInfo.getHeaders()); + return getStartTime() == taskInfo.getStartTime() + && getRunningTimeNanos() == taskInfo.getRunningTimeNanos() + && isCancellable() == taskInfo.isCancellable() + && Objects.equals(getTaskId(), taskInfo.getTaskId()) + && Objects.equals(getType(), taskInfo.getType()) + && Objects.equals(getAction(), taskInfo.getAction()) + && Objects.equals(getDescription(), taskInfo.getDescription()) + && Objects.equals(getParentTaskId(), taskInfo.getParentTaskId()) + && Objects.equals(status, taskInfo.status) + && Objects.equals(getHeaders(), taskInfo.getHeaders()); } @Override public int hashCode() { return Objects.hash( - getTaskId(), getType(), getAction(), getDescription(), getStartTime(), - getRunningTimeNanos(), isCancellable(), getParentTaskId(), status, getHeaders() + getTaskId(), + getType(), + getAction(), + getDescription(), + getStartTime(), + getRunningTimeNanos(), + isCancellable(), + getParentTaskId(), + status, + getHeaders() ); } - @Override public String toString() { - return "TaskInfo{" + - "taskId=" + taskId + - ", type='" + type + '\'' + - ", action='" + action + '\'' + - ", description='" + description + '\'' + - ", startTime=" + startTime + - ", runningTimeNanos=" + runningTimeNanos + - ", cancellable=" + cancellable + - ", parentTaskId=" + parentTaskId + - ", status=" + status + - ", headers=" + headers + - '}'; + return "TaskInfo{" + + "taskId=" + + taskId + + ", type='" + + type + + '\'' + + ", action='" + + action + + '\'' + + ", description='" + + description + + '\'' + + ", startTime=" + + startTime + + ", runningTimeNanos=" + + runningTimeNanos + + ", cancellable=" + + cancellable + + ", parentTaskId=" + + parentTaskId + + ", status=" + + status + + ", headers=" + + headers + + '}'; } } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/TaskOperationFailure.java b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/TaskOperationFailure.java index 88ce135618e..f173da9daa8 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/TaskOperationFailure.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/TaskOperationFailure.java @@ -50,7 +50,7 @@ public class TaskOperationFailure { private final OpenSearchException reason; private final String status; - public TaskOperationFailure(String nodeId, long taskId,String status, OpenSearchException reason) { + public TaskOperationFailure(String nodeId, long taskId, String status, OpenSearchException reason) { this.nodeId = nodeId; this.taskId = taskId; this.status = status; @@ -78,38 +78,49 @@ public class TaskOperationFailure { if (this == o) return true; if (!(o instanceof TaskOperationFailure)) return false; TaskOperationFailure that = (TaskOperationFailure) o; - return getTaskId() == that.getTaskId() && - Objects.equals(getNodeId(), that.getNodeId()) && - Objects.equals(getReason(), that.getReason()) && - Objects.equals(getStatus(), that.getStatus()); + return getTaskId() == that.getTaskId() + && Objects.equals(getNodeId(), that.getNodeId()) + && Objects.equals(getReason(), that.getReason()) + && Objects.equals(getStatus(), that.getStatus()); } @Override public int hashCode() { return Objects.hash(getNodeId(), getTaskId(), getReason(), getStatus()); } + @Override public String toString() { - return "TaskOperationFailure{" + - "nodeId='" + nodeId + '\'' + - ", taskId=" + taskId + - ", reason=" + reason + - ", status='" + status + '\'' + - '}'; + return "TaskOperationFailure{" + + "nodeId='" + + nodeId + + '\'' + + ", taskId=" + + taskId + + ", reason=" + + reason + + ", status='" + + status + + '\'' + + '}'; } + public static TaskOperationFailure fromXContent(XContentParser parser) { return PARSER.apply(parser, null); } - private static final ConstructingObjectParser PARSER = - new ConstructingObjectParser<>("task_info", true, constructorObjects -> { + private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( + "task_info", + true, + constructorObjects -> { int i = 0; String nodeId = (String) constructorObjects[i++]; long taskId = (long) constructorObjects[i++]; String status = (String) constructorObjects[i++]; OpenSearchException reason = (OpenSearchException) constructorObjects[i]; return new TaskOperationFailure(nodeId, taskId, status, reason); - }); + } + ); static { PARSER.declareString(constructorArg(), new ParseField("node_id")); diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/TaskSubmissionResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/TaskSubmissionResponse.java index b202de980bb..6077455224b 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/TaskSubmissionResponse.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/TaskSubmissionResponse.java @@ -45,7 +45,9 @@ public class TaskSubmissionResponse { public static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( "task_submission_response", - true, a -> new TaskSubmissionResponse((String) a[0])); + true, + a -> new TaskSubmissionResponse((String) a[0]) + ); static { PARSER.declareString(ConstructingObjectParser.optionalConstructorArg(), TASK); diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/AbstractRequestTestCase.java b/client/rest-high-level/src/test/java/org/opensearch/client/AbstractRequestTestCase.java index d99dc4e42f5..e63375c34f9 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/AbstractRequestTestCase.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/AbstractRequestTestCase.java @@ -61,10 +61,7 @@ public abstract class AbstractRequestTestCase extends O final BytesReference bytes = toShuffledXContent(clientTestInstance, xContentType, ToXContent.EMPTY_PARAMS, randomBoolean()); final XContent xContent = XContentFactory.xContent(xContentType); - final XContentParser parser = xContent.createParser( - xContentRegistry(), - LoggingDeprecationHandler.INSTANCE, - bytes.streamInput()); + final XContentParser parser = xContent.createParser(xContentRegistry(), LoggingDeprecationHandler.INSTANCE, bytes.streamInput()); final S serverInstance = doParseToServerInstance(parser); assertInstances(serverInstance, clientTestInstance); } diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/AbstractResponseTestCase.java b/client/rest-high-level/src/test/java/org/opensearch/client/AbstractResponseTestCase.java index 30e1057680c..06ceee78e55 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/AbstractResponseTestCase.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/AbstractResponseTestCase.java @@ -63,7 +63,8 @@ public abstract class AbstractResponseTestCase extends final XContentParser parser = xContent.createParser( NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, - bytes.streamInput()); + bytes.streamInput() + ); final C clientInstance = doParseToClientInstance(parser); assertInstances(serverTestInstance, clientInstance); } diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/BulkProcessorIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/BulkProcessorIT.java index 32e9de90de0..bf065f77b1d 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/BulkProcessorIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/BulkProcessorIT.java @@ -86,14 +86,20 @@ public class BulkProcessorIT extends OpenSearchRestHighLevelClientTestCase { private static BulkProcessor.Builder initBulkProcessorBuilder(BulkProcessor.Listener listener) { return BulkProcessor.builder( - (request, bulkListener) -> highLevelClient().bulkAsync(request, RequestOptions.DEFAULT, - bulkListener), listener); + (request, bulkListener) -> highLevelClient().bulkAsync(request, RequestOptions.DEFAULT, bulkListener), + listener + ); } private static BulkProcessor.Builder initBulkProcessorBuilderUsingTypes(BulkProcessor.Listener listener) { return BulkProcessor.builder( - (request, bulkListener) -> highLevelClient().bulkAsync(request, expectWarnings(RestBulkAction.TYPES_DEPRECATION_MESSAGE), - bulkListener), listener); + (request, bulkListener) -> highLevelClient().bulkAsync( + request, + expectWarnings(RestBulkAction.TYPES_DEPRECATION_MESSAGE), + bulkListener + ), + listener + ); } public void testThatBulkProcessorCountIsCorrect() throws Exception { @@ -101,11 +107,15 @@ public class BulkProcessorIT extends OpenSearchRestHighLevelClientTestCase { BulkProcessorTestListener listener = new BulkProcessorTestListener(latch); int numDocs = randomIntBetween(10, 100); - try (BulkProcessor processor = initBulkProcessorBuilder(listener) - //let's make sure that the bulk action limit trips, one single execution will index all the documents - .setConcurrentRequests(randomIntBetween(0, 1)).setBulkActions(numDocs) - .setFlushInterval(TimeValue.timeValueHours(24)).setBulkSize(new ByteSizeValue(1, ByteSizeUnit.GB)) - .build()) { + try ( + BulkProcessor processor = initBulkProcessorBuilder(listener) + // let's make sure that the bulk action limit trips, one single execution will index all the documents + .setConcurrentRequests(randomIntBetween(0, 1)) + .setBulkActions(numDocs) + .setFlushInterval(TimeValue.timeValueHours(24)) + .setBulkSize(new ByteSizeValue(1, ByteSizeUnit.GB)) + .build() + ) { MultiGetRequest multiGetRequest = indexDocs(processor, numDocs); @@ -125,15 +135,20 @@ public class BulkProcessorIT extends OpenSearchRestHighLevelClientTestCase { int numDocs = randomIntBetween(10, 100); - try (BulkProcessor processor = initBulkProcessorBuilder(listener) - //let's make sure that this bulk won't be automatically flushed - .setConcurrentRequests(randomIntBetween(0, 10)).setBulkActions(numDocs + randomIntBetween(1, 100)) - .setFlushInterval(TimeValue.timeValueHours(24)).setBulkSize(new ByteSizeValue(1, ByteSizeUnit.GB)).build()) { + try ( + BulkProcessor processor = initBulkProcessorBuilder(listener) + // let's make sure that this bulk won't be automatically flushed + .setConcurrentRequests(randomIntBetween(0, 10)) + .setBulkActions(numDocs + randomIntBetween(1, 100)) + .setFlushInterval(TimeValue.timeValueHours(24)) + .setBulkSize(new ByteSizeValue(1, ByteSizeUnit.GB)) + .build() + ) { MultiGetRequest multiGetRequest = indexDocs(processor, numDocs); assertThat(latch.await(randomInt(500), TimeUnit.MILLISECONDS), equalTo(false)); - //we really need an explicit flush as none of the bulk thresholds was reached + // we really need an explicit flush as none of the bulk thresholds was reached processor.flush(); latch.await(); @@ -160,10 +175,14 @@ public class BulkProcessorIT extends OpenSearchRestHighLevelClientTestCase { MultiGetRequest multiGetRequest; - try (BulkProcessor processor = initBulkProcessorBuilder(listener) - .setConcurrentRequests(concurrentRequests).setBulkActions(bulkActions) - //set interval and size to high values - .setFlushInterval(TimeValue.timeValueHours(24)).setBulkSize(new ByteSizeValue(1, ByteSizeUnit.GB)).build()) { + try ( + BulkProcessor processor = initBulkProcessorBuilder(listener).setConcurrentRequests(concurrentRequests) + .setBulkActions(bulkActions) + // set interval and size to high values + .setFlushInterval(TimeValue.timeValueHours(24)) + .setBulkSize(new ByteSizeValue(1, ByteSizeUnit.GB)) + .build() + ) { multiGetRequest = indexDocs(processor, numDocs); @@ -187,9 +206,9 @@ public class BulkProcessorIT extends OpenSearchRestHighLevelClientTestCase { assertThat(bulkItemResponse.getFailureMessage(), bulkItemResponse.isFailed(), equalTo(false)); assertThat(bulkItemResponse.getIndex(), equalTo("test")); assertThat(bulkItemResponse.getType(), equalTo("_doc")); - //with concurrent requests > 1 we can't rely on the order of the bulk requests + // with concurrent requests > 1 we can't rely on the order of the bulk requests assertThat(Integer.valueOf(bulkItemResponse.getId()), both(greaterThan(0)).and(lessThanOrEqualTo(numDocs))); - //we do want to check that we don't get duplicate ids back + // we do want to check that we don't get duplicate ids back assertThat(ids.add(bulkItemResponse.getId()), equalTo(true)); } @@ -201,11 +220,12 @@ public class BulkProcessorIT extends OpenSearchRestHighLevelClientTestCase { int numDocs = randomIntBetween(10, 100); BulkProcessor processor = initBulkProcessorBuilder(listener) - //let's make sure that the bulk action limit trips, one single execution will index all the documents - .setConcurrentRequests(randomIntBetween(0, 1)).setBulkActions(numDocs) - .setFlushInterval(TimeValue.timeValueHours(24)).setBulkSize(new ByteSizeValue(randomIntBetween(1, 10), - RandomPicks.randomFrom(random(), ByteSizeUnit.values()))) - .build(); + // let's make sure that the bulk action limit trips, one single execution will index all the documents + .setConcurrentRequests(randomIntBetween(0, 1)) + .setBulkActions(numDocs) + .setFlushInterval(TimeValue.timeValueHours(24)) + .setBulkSize(new ByteSizeValue(randomIntBetween(1, 10), RandomPicks.randomFrom(random(), ByteSizeUnit.values()))) + .build(); MultiGetRequest multiGetRequest = indexDocs(processor, numDocs); assertThat(processor.awaitClose(1, TimeUnit.MINUTES), is(true)); @@ -229,14 +249,16 @@ public class BulkProcessorIT extends OpenSearchRestHighLevelClientTestCase { public void testBulkProcessorConcurrentRequestsReadOnlyIndex() throws Exception { Request request = new Request("PUT", "/test-ro"); - request.setJsonEntity("{\n" + - " \"settings\" : {\n" + - " \"index\" : {\n" + - " \"blocks.write\" : true\n" + - " }\n" + - " }\n" + - " \n" + - "}"); + request.setJsonEntity( + "{\n" + + " \"settings\" : {\n" + + " \"index\" : {\n" + + " \"blocks.write\" : true\n" + + " }\n" + + " }\n" + + " \n" + + "}" + ); Response response = client().performRequest(request); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); @@ -255,22 +277,26 @@ public class BulkProcessorIT extends OpenSearchRestHighLevelClientTestCase { MultiGetRequest multiGetRequest = new MultiGetRequest(); BulkProcessorTestListener listener = new BulkProcessorTestListener(latch, closeLatch); - try (BulkProcessor processor = initBulkProcessorBuilder(listener) - .setConcurrentRequests(concurrentRequests).setBulkActions(bulkActions) - //set interval and size to high values - .setFlushInterval(TimeValue.timeValueHours(24)).setBulkSize(new ByteSizeValue(1, ByteSizeUnit.GB)).build()) { + try ( + BulkProcessor processor = initBulkProcessorBuilder(listener).setConcurrentRequests(concurrentRequests) + .setBulkActions(bulkActions) + // set interval and size to high values + .setFlushInterval(TimeValue.timeValueHours(24)) + .setBulkSize(new ByteSizeValue(1, ByteSizeUnit.GB)) + .build() + ) { for (int i = 1; i <= numDocs; i++) { // let's make sure we get at least 1 item in the MultiGetRequest regardless of the randomising roulette if (randomBoolean() || multiGetRequest.getItems().size() == 0) { testDocs++; - processor.add(new IndexRequest("test").id(Integer.toString(testDocs)) - .source(XContentType.JSON, "field", "value")); + processor.add(new IndexRequest("test").id(Integer.toString(testDocs)).source(XContentType.JSON, "field", "value")); multiGetRequest.add("test", Integer.toString(testDocs)); } else { testReadOnlyDocs++; - processor.add(new IndexRequest("test-ro").id(Integer.toString(testReadOnlyDocs)) - .source(XContentType.JSON, "field", "value")); + processor.add( + new IndexRequest("test-ro").id(Integer.toString(testReadOnlyDocs)).source(XContentType.JSON, "field", "value") + ); } } } @@ -289,15 +315,15 @@ public class BulkProcessorIT extends OpenSearchRestHighLevelClientTestCase { assertThat(bulkItemResponse.getType(), equalTo("_doc")); if (bulkItemResponse.getIndex().equals("test")) { assertThat(bulkItemResponse.isFailed(), equalTo(false)); - //with concurrent requests > 1 we can't rely on the order of the bulk requests + // with concurrent requests > 1 we can't rely on the order of the bulk requests assertThat(Integer.valueOf(bulkItemResponse.getId()), both(greaterThan(0)).and(lessThanOrEqualTo(testDocs))); - //we do want to check that we don't get duplicate ids back + // we do want to check that we don't get duplicate ids back assertThat(ids.add(bulkItemResponse.getId()), equalTo(true)); } else { assertThat(bulkItemResponse.isFailed(), equalTo(true)); - //with concurrent requests > 1 we can't rely on the order of the bulk requests + // with concurrent requests > 1 we can't rely on the order of the bulk requests assertThat(Integer.valueOf(bulkItemResponse.getId()), both(greaterThan(0)).and(lessThanOrEqualTo(testReadOnlyDocs))); - //we do want to check that we don't get duplicate ids back + // we do want to check that we don't get duplicate ids back assertThat(readOnlyIds.add(bulkItemResponse.getId()), equalTo(true)); } } @@ -333,7 +359,6 @@ public class BulkProcessorIT extends OpenSearchRestHighLevelClientTestCase { assertThat(hits, everyItem(hasProperty(fieldFromSource("user"), equalTo("some user")))); assertThat(hits, everyItem(hasProperty(fieldFromSource("fieldNameXYZ"), equalTo("valueXYZ")))); - Iterable blogs = searchAll(new SearchRequest("blogs").routing("routing")); assertThat(blogs, everyItem(hasProperty(fieldFromSource("title"), equalTo("some title")))); assertThat(blogs, everyItem(hasProperty(fieldFromSource("fieldNameXYZ"), equalTo("valueXYZ")))); @@ -350,18 +375,22 @@ public class BulkProcessorIT extends OpenSearchRestHighLevelClientTestCase { { final CountDownLatch latch = new CountDownLatch(1); BulkProcessorTestListener listener = new BulkProcessorTestListener(latch); - //Check that untyped document additions inherit the global type + // Check that untyped document additions inherit the global type String globalType = customType; String localType = null; - try (BulkProcessor processor = initBulkProcessorBuilderUsingTypes(listener) - //let's make sure that the bulk action limit trips, one single execution will index all the documents - .setConcurrentRequests(randomIntBetween(0, 1)).setBulkActions(numDocs) - .setFlushInterval(TimeValue.timeValueHours(24)).setBulkSize(new ByteSizeValue(1, ByteSizeUnit.GB)) + try ( + BulkProcessor processor = initBulkProcessorBuilderUsingTypes(listener) + // let's make sure that the bulk action limit trips, one single execution will index all the documents + .setConcurrentRequests(randomIntBetween(0, 1)) + .setBulkActions(numDocs) + .setFlushInterval(TimeValue.timeValueHours(24)) + .setBulkSize(new ByteSizeValue(1, ByteSizeUnit.GB)) .setGlobalIndex("test") .setGlobalType(globalType) .setGlobalRouting("routing") .setGlobalPipeline("pipeline_id") - .build()) { + .build() + ) { indexDocs(processor, numDocs, null, localType, "test", globalType, "pipeline_id"); latch.await(); @@ -380,20 +409,24 @@ public class BulkProcessorIT extends OpenSearchRestHighLevelClientTestCase { } { - //Check that typed document additions don't inherit the global type + // Check that typed document additions don't inherit the global type String globalType = ignoredType; String localType = customType; final CountDownLatch latch = new CountDownLatch(1); BulkProcessorTestListener listener = new BulkProcessorTestListener(latch); - try (BulkProcessor processor = initBulkProcessorBuilderUsingTypes(listener) - //let's make sure that the bulk action limit trips, one single execution will index all the documents - .setConcurrentRequests(randomIntBetween(0, 1)).setBulkActions(numDocs) - .setFlushInterval(TimeValue.timeValueHours(24)).setBulkSize(new ByteSizeValue(1, ByteSizeUnit.GB)) + try ( + BulkProcessor processor = initBulkProcessorBuilderUsingTypes(listener) + // let's make sure that the bulk action limit trips, one single execution will index all the documents + .setConcurrentRequests(randomIntBetween(0, 1)) + .setBulkActions(numDocs) + .setFlushInterval(TimeValue.timeValueHours(24)) + .setBulkSize(new ByteSizeValue(1, ByteSizeUnit.GB)) .setGlobalIndex("test") .setGlobalType(globalType) .setGlobalRouting("routing") .setGlobalPipeline("pipeline_id") - .build()) { + .build() + ) { indexDocs(processor, numDocs, null, localType, "test", globalType, "pipeline_id"); latch.await(); @@ -410,21 +443,25 @@ public class BulkProcessorIT extends OpenSearchRestHighLevelClientTestCase { } } { - //Check that untyped document additions and untyped global inherit the established custom type + // Check that untyped document additions and untyped global inherit the established custom type // (the custom document type introduced to the mapping by the earlier code in this test) String globalType = null; String localType = null; final CountDownLatch latch = new CountDownLatch(1); BulkProcessorTestListener listener = new BulkProcessorTestListener(latch); - try (BulkProcessor processor = initBulkProcessorBuilder(listener) - //let's make sure that the bulk action limit trips, one single execution will index all the documents - .setConcurrentRequests(randomIntBetween(0, 1)).setBulkActions(numDocs) - .setFlushInterval(TimeValue.timeValueHours(24)).setBulkSize(new ByteSizeValue(1, ByteSizeUnit.GB)) + try ( + BulkProcessor processor = initBulkProcessorBuilder(listener) + // let's make sure that the bulk action limit trips, one single execution will index all the documents + .setConcurrentRequests(randomIntBetween(0, 1)) + .setBulkActions(numDocs) + .setFlushInterval(TimeValue.timeValueHours(24)) + .setBulkSize(new ByteSizeValue(1, ByteSizeUnit.GB)) .setGlobalIndex("test") .setGlobalType(globalType) .setGlobalRouting("routing") .setGlobalPipeline("pipeline_id") - .build()) { + .build() + ) { indexDocs(processor, numDocs, null, localType, "test", globalType, "pipeline_id"); latch.await(); @@ -444,19 +481,28 @@ public class BulkProcessorIT extends OpenSearchRestHighLevelClientTestCase { @SuppressWarnings("unchecked") private Matcher[] expectedIds(int numDocs) { - return IntStream.rangeClosed(1, numDocs) - .boxed() - .map(n -> hasId(n.toString())) - .>toArray(Matcher[]::new); + return IntStream.rangeClosed(1, numDocs).boxed().map(n -> hasId(n.toString())).>toArray(Matcher[]::new); } - private MultiGetRequest indexDocs(BulkProcessor processor, int numDocs, String localIndex, String localType, - String globalIndex, String globalType, String globalPipeline) throws Exception { + private MultiGetRequest indexDocs( + BulkProcessor processor, + int numDocs, + String localIndex, + String localType, + String globalIndex, + String globalType, + String globalPipeline + ) throws Exception { MultiGetRequest multiGetRequest = new MultiGetRequest(); for (int i = 1; i <= numDocs; i++) { if (randomBoolean()) { - processor.add(new IndexRequest(localIndex, localType, Integer.toString(i)) - .source(XContentType.JSON, "field", randomRealisticUnicodeOfLengthBetween(1, 30))); + processor.add( + new IndexRequest(localIndex, localType, Integer.toString(i)).source( + XContentType.JSON, + "field", + randomRealisticUnicodeOfLengthBetween(1, 30) + ) + ); } else { BytesArray data = bytesBulkRequest(localIndex, localType, i); processor.add(data, globalIndex, globalType, globalPipeline, XContentType.JSON); @@ -485,10 +531,7 @@ public class BulkProcessorIT extends OpenSearchRestHighLevelClientTestCase { action.field("_id", Integer.toString(id)); action.endObject().endObject(); - XContentBuilder source = jsonBuilder() - .startObject() - .field("field", randomRealisticUnicodeOfLengthBetween(1, 30)) - .endObject(); + XContentBuilder source = jsonBuilder().startObject().field("field", randomRealisticUnicodeOfLengthBetween(1, 30)).endObject(); String request = Strings.toString(action) + "\n" + Strings.toString(source) + "\n"; return new BytesArray(request); @@ -509,8 +552,11 @@ public class BulkProcessorIT extends OpenSearchRestHighLevelClientTestCase { assertThat(bulkItemResponse.getIndex(), equalTo("test")); assertThat(bulkItemResponse.getType(), equalTo(expectedType)); assertThat(bulkItemResponse.getId(), equalTo(Integer.toString(i++))); - assertThat("item " + i + " failed with cause: " + bulkItemResponse.getFailureMessage(), - bulkItemResponse.isFailed(), equalTo(false)); + assertThat( + "item " + i + " failed with cause: " + bulkItemResponse.getFailureMessage(), + bulkItemResponse.isFailed(), + equalTo(false) + ); } } @@ -560,5 +606,4 @@ public class BulkProcessorIT extends OpenSearchRestHighLevelClientTestCase { } } - } diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/BulkProcessorRetryIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/BulkProcessorRetryIT.java index 35f6e82b991..0744fe4e6db 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/BulkProcessorRetryIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/BulkProcessorRetryIT.java @@ -31,7 +31,6 @@ package org.opensearch.client; -import org.opensearch.client.RequestOptions; import org.opensearch.action.admin.indices.refresh.RefreshRequest; import org.opensearch.action.bulk.BackoffPolicy; import org.opensearch.action.bulk.BulkItemResponse; @@ -63,7 +62,9 @@ public class BulkProcessorRetryIT extends OpenSearchRestHighLevelClientTestCase private static BulkProcessor.Builder initBulkProcessorBuilder(BulkProcessor.Listener listener) { return BulkProcessor.builder( - (request, bulkListener) -> highLevelClient().bulkAsync(request, RequestOptions.DEFAULT, bulkListener), listener); + (request, bulkListener) -> highLevelClient().bulkAsync(request, RequestOptions.DEFAULT, bulkListener), + listener + ); } public void testBulkRejectionLoadWithoutBackoff() throws Exception { @@ -84,8 +85,7 @@ public class BulkProcessorRetryIT extends OpenSearchRestHighLevelClientTestCase BulkProcessor bulkProcessor = initBulkProcessorBuilder(new BulkProcessor.Listener() { @Override - public void beforeBulk(long executionId, BulkRequest request) { - } + public void beforeBulk(long executionId, BulkRequest request) {} @Override public void afterBulk(long executionId, BulkRequest request, BulkResponse response) { @@ -100,10 +100,7 @@ public class BulkProcessorRetryIT extends OpenSearchRestHighLevelClientTestCase responses.add(failure); latch.countDown(); } - }).setBulkActions(1) - .setConcurrentRequests(randomIntBetween(0, 100)) - .setBackoffPolicy(internalPolicy) - .build(); + }).setBulkActions(1).setConcurrentRequests(randomIntBetween(0, 100)).setBackoffPolicy(internalPolicy).build(); MultiGetRequest multiGetRequest = indexDocs(bulkProcessor, numberOfAsyncOps); latch.await(10, TimeUnit.SECONDS); @@ -171,8 +168,10 @@ public class BulkProcessorRetryIT extends OpenSearchRestHighLevelClientTestCase private static MultiGetRequest indexDocs(BulkProcessor processor, int numDocs) { MultiGetRequest multiGetRequest = new MultiGetRequest(); for (int i = 1; i <= numDocs; i++) { - processor.add(new IndexRequest(INDEX_NAME).id(Integer.toString(i)) - .source(XContentType.JSON, "field", randomRealisticUnicodeOfCodepointLengthBetween(1, 30))); + processor.add( + new IndexRequest(INDEX_NAME).id(Integer.toString(i)) + .source(XContentType.JSON, "field", randomRealisticUnicodeOfCodepointLengthBetween(1, 30)) + ); multiGetRequest.add(INDEX_NAME, Integer.toString(i)); } return multiGetRequest; diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/BulkRequestWithGlobalParametersIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/BulkRequestWithGlobalParametersIT.java index d8096edf884..531c84eadd3 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/BulkRequestWithGlobalParametersIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/BulkRequestWithGlobalParametersIT.java @@ -61,10 +61,8 @@ public class BulkRequestWithGlobalParametersIT extends OpenSearchRestHighLevelCl createFieldAddingPipleine("xyz", "fieldNameXYZ", "valueXYZ"); BulkRequest request = new BulkRequest(); - request.add(new IndexRequest("test").id("1") - .source(XContentType.JSON, "field", "bulk1")); - request.add(new IndexRequest("test").id("2") - .source(XContentType.JSON, "field", "bulk2")); + request.add(new IndexRequest("test").id("1").source(XContentType.JSON, "field", "bulk1")); + request.add(new IndexRequest("test").id("2").source(XContentType.JSON, "field", "bulk2")); request.pipeline("xyz"); bulk(request); @@ -80,12 +78,8 @@ public class BulkRequestWithGlobalParametersIT extends OpenSearchRestHighLevelCl BulkRequest request = new BulkRequest(); request.pipeline("globalId"); - request.add(new IndexRequest("test").id("1") - .source(XContentType.JSON, "field", "bulk1") - .setPipeline("perIndexId")); - request.add(new IndexRequest("test").id("2") - .source(XContentType.JSON, "field", "bulk2") - .setPipeline("perIndexId")); + request.add(new IndexRequest("test").id("1").source(XContentType.JSON, "field", "bulk1").setPipeline("perIndexId")); + request.add(new IndexRequest("test").id("2").source(XContentType.JSON, "field", "bulk2").setPipeline("perIndexId")); bulk(request); @@ -113,19 +107,19 @@ public class BulkRequestWithGlobalParametersIT extends OpenSearchRestHighLevelCl bulk(request); Iterable hits = searchAll("test"); - assertThat(hits, containsInAnyOrder( - both(hasId("1")) - .and(hasProperty(fieldFromSource("someNewField"), equalTo("someValue"))), - both(hasId("2")) - .and(hasProperty(fieldFromSource("fieldXYZ"), equalTo("valueXYZ"))))); + assertThat( + hits, + containsInAnyOrder( + both(hasId("1")).and(hasProperty(fieldFromSource("someNewField"), equalTo("someValue"))), + both(hasId("2")).and(hasProperty(fieldFromSource("fieldXYZ"), equalTo("valueXYZ"))) + ) + ); } public void testGlobalIndex() throws IOException { BulkRequest request = new BulkRequest("global_index", null); - request.add(new IndexRequest().id("1") - .source(XContentType.JSON, "field", "bulk1")); - request.add(new IndexRequest().id("2") - .source(XContentType.JSON, "field", "bulk2")); + request.add(new IndexRequest().id("1").source(XContentType.JSON, "field", "bulk1")); + request.add(new IndexRequest().id("2").source(XContentType.JSON, "field", "bulk2")); bulk(request); @@ -136,27 +130,22 @@ public class BulkRequestWithGlobalParametersIT extends OpenSearchRestHighLevelCl @SuppressWarnings("unchecked") public void testIndexGlobalAndPerRequest() throws IOException { BulkRequest request = new BulkRequest("global_index", null); - request.add(new IndexRequest("local_index").id("1") - .source(XContentType.JSON, "field", "bulk1")); - request.add(new IndexRequest().id("2") // will take global index - .source(XContentType.JSON, "field", "bulk2")); + request.add(new IndexRequest("local_index").id("1").source(XContentType.JSON, "field", "bulk1")); + request.add( + new IndexRequest().id("2") // will take global index + .source(XContentType.JSON, "field", "bulk2") + ); bulk(request); Iterable hits = searchAll("local_index", "global_index"); - assertThat(hits, containsInAnyOrder( - both(hasId("1")) - .and(hasIndex("local_index")), - both(hasId("2")) - .and(hasIndex("global_index")))); + assertThat(hits, containsInAnyOrder(both(hasId("1")).and(hasIndex("local_index")), both(hasId("2")).and(hasIndex("global_index")))); } public void testGlobalType() throws IOException { BulkRequest request = new BulkRequest(null, "global_type"); - request.add(new IndexRequest("index").id("1") - .source(XContentType.JSON, "field", "bulk1")); - request.add(new IndexRequest("index").id("2") - .source(XContentType.JSON, "field", "bulk2")); + request.add(new IndexRequest("index").id("1").source(XContentType.JSON, "field", "bulk1")); + request.add(new IndexRequest("index").id("2").source(XContentType.JSON, "field", "bulk2")); bulkWithTypes(request); @@ -166,28 +155,23 @@ public class BulkRequestWithGlobalParametersIT extends OpenSearchRestHighLevelCl public void testTypeGlobalAndPerRequest() throws IOException { BulkRequest request = new BulkRequest(null, "global_type"); - request.add(new IndexRequest("index1", "local_type", "1") - .source(XContentType.JSON, "field", "bulk1")); - request.add(new IndexRequest("index2").id("2") // will take global type - .source(XContentType.JSON, "field", "bulk2")); + request.add(new IndexRequest("index1", "local_type", "1").source(XContentType.JSON, "field", "bulk1")); + request.add( + new IndexRequest("index2").id("2") // will take global type + .source(XContentType.JSON, "field", "bulk2") + ); bulkWithTypes(request); Iterable hits = searchAll("index1", "index2"); - assertThat(hits, containsInAnyOrder( - both(hasId("1")) - .and(hasType("local_type")), - both(hasId("2")) - .and(hasType("global_type")))); + assertThat(hits, containsInAnyOrder(both(hasId("1")).and(hasType("local_type")), both(hasId("2")).and(hasType("global_type")))); } public void testGlobalRouting() throws IOException { createIndexWithMultipleShards("index"); BulkRequest request = new BulkRequest((String) null); - request.add(new IndexRequest("index").id("1") - .source(XContentType.JSON, "field", "bulk1")); - request.add(new IndexRequest("index").id("2") - .source(XContentType.JSON, "field", "bulk1")); + request.add(new IndexRequest("index").id("1").source(XContentType.JSON, "field", "bulk1")); + request.add(new IndexRequest("index").id("2").source(XContentType.JSON, "field", "bulk1")); request.routing("1"); bulk(request); @@ -201,11 +185,8 @@ public class BulkRequestWithGlobalParametersIT extends OpenSearchRestHighLevelCl public void testMixLocalAndGlobalRouting() throws IOException { BulkRequest request = new BulkRequest((String) null); request.routing("globalRouting"); - request.add(new IndexRequest("index").id("1") - .source(XContentType.JSON, "field", "bulk1")); - request.add(new IndexRequest("index").id( "2") - .routing("localRouting") - .source(XContentType.JSON, "field", "bulk1")); + request.add(new IndexRequest("index").id("1").source(XContentType.JSON, "field", "bulk1")); + request.add(new IndexRequest("index").id("2").routing("localRouting").source(XContentType.JSON, "field", "bulk1")); bulk(request); @@ -215,10 +196,8 @@ public class BulkRequestWithGlobalParametersIT extends OpenSearchRestHighLevelCl public void testGlobalIndexNoTypes() throws IOException { BulkRequest request = new BulkRequest("global_index"); - request.add(new IndexRequest().id("1") - .source(XContentType.JSON, "field", "bulk1")); - request.add(new IndexRequest().id("2") - .source(XContentType.JSON, "field", "bulk2")); + request.add(new IndexRequest().id("1").source(XContentType.JSON, "field", "bulk1")); + request.add(new IndexRequest().id("2").source(XContentType.JSON, "field", "bulk2")); bulk(request); @@ -227,8 +206,12 @@ public class BulkRequestWithGlobalParametersIT extends OpenSearchRestHighLevelCl } private BulkResponse bulkWithTypes(BulkRequest request) throws IOException { - BulkResponse bulkResponse = execute(request, highLevelClient()::bulk, highLevelClient()::bulkAsync, - expectWarnings(RestBulkAction.TYPES_DEPRECATION_MESSAGE)); + BulkResponse bulkResponse = execute( + request, + highLevelClient()::bulk, + highLevelClient()::bulkAsync, + expectWarnings(RestBulkAction.TYPES_DEPRECATION_MESSAGE) + ); assertFalse(bulkResponse.hasFailures()); return bulkResponse; } diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/ClusterClientIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/ClusterClientIT.java index 6fda18bd8e6..71b869fb59e 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/ClusterClientIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/ClusterClientIT.java @@ -33,8 +33,6 @@ package org.opensearch.client; import org.apache.http.util.EntityUtils; -import org.opensearch.client.Request; -import org.opensearch.client.RequestOptions; import org.opensearch.OpenSearchException; import org.opensearch.OpenSearchStatusException; import org.opensearch.action.admin.cluster.health.ClusterHealthRequest; @@ -101,14 +99,19 @@ public class ClusterClientIT extends OpenSearchRestHighLevelClientTestCase { setRequest.transientSettings(transientSettings); setRequest.persistentSettings(map); - ClusterUpdateSettingsResponse setResponse = execute(setRequest, highLevelClient().cluster()::putSettings, - highLevelClient().cluster()::putSettingsAsync); + ClusterUpdateSettingsResponse setResponse = execute( + setRequest, + highLevelClient().cluster()::putSettings, + highLevelClient().cluster()::putSettingsAsync + ); assertAcked(setResponse); assertThat(setResponse.getTransientSettings().get(transientSettingKey), notNullValue()); assertThat(setResponse.getTransientSettings().get(persistentSettingKey), nullValue()); - assertThat(setResponse.getTransientSettings().get(transientSettingKey), - equalTo(transientSettingValue + ByteSizeUnit.BYTES.getSuffix())); + assertThat( + setResponse.getTransientSettings().get(transientSettingKey), + equalTo(transientSettingValue + ByteSizeUnit.BYTES.getSuffix()) + ); assertThat(setResponse.getPersistentSettings().get(transientSettingKey), nullValue()); assertThat(setResponse.getPersistentSettings().get(persistentSettingKey), notNullValue()); assertThat(setResponse.getPersistentSettings().get(persistentSettingKey), equalTo(persistentSettingValue)); @@ -123,8 +126,11 @@ public class ClusterClientIT extends OpenSearchRestHighLevelClientTestCase { resetRequest.transientSettings(Settings.builder().putNull(transientSettingKey)); resetRequest.persistentSettings("{\"" + persistentSettingKey + "\": null }", XContentType.JSON); - ClusterUpdateSettingsResponse resetResponse = execute(resetRequest, highLevelClient().cluster()::putSettings, - highLevelClient().cluster()::putSettingsAsync); + ClusterUpdateSettingsResponse resetResponse = execute( + resetRequest, + highLevelClient().cluster()::putSettings, + highLevelClient().cluster()::putSettingsAsync + ); assertThat(resetResponse.getTransientSettings().get(transientSettingKey), equalTo(null)); assertThat(resetResponse.getPersistentSettings().get(persistentSettingKey), equalTo(null)); @@ -144,11 +150,19 @@ public class ClusterClientIT extends OpenSearchRestHighLevelClientTestCase { ClusterUpdateSettingsRequest clusterUpdateSettingsRequest = new ClusterUpdateSettingsRequest(); clusterUpdateSettingsRequest.transientSettings(Settings.builder().put(setting, value).build()); - OpenSearchException exception = expectThrows(OpenSearchException.class, () -> execute(clusterUpdateSettingsRequest, - highLevelClient().cluster()::putSettings, highLevelClient().cluster()::putSettingsAsync)); + OpenSearchException exception = expectThrows( + OpenSearchException.class, + () -> execute( + clusterUpdateSettingsRequest, + highLevelClient().cluster()::putSettings, + highLevelClient().cluster()::putSettingsAsync + ) + ); assertThat(exception.status(), equalTo(RestStatus.BAD_REQUEST)); - assertThat(exception.getMessage(), equalTo( - "OpenSearch exception [type=illegal_argument_exception, reason=transient setting [" + setting + "], not recognized]")); + assertThat( + exception.getMessage(), + equalTo("OpenSearch exception [type=illegal_argument_exception, reason=transient setting [" + setting + "], not recognized]") + ); } public void testClusterGetSettings() throws IOException { @@ -158,14 +172,16 @@ public class ClusterClientIT extends OpenSearchRestHighLevelClientTestCase { final String persistentSettingKey = EnableAllocationDecider.CLUSTER_ROUTING_ALLOCATION_ENABLE_SETTING.getKey(); final String persistentSettingValue = EnableAllocationDecider.Allocation.NONE.name(); - Settings transientSettings = - Settings.builder().put(transientSettingKey, transientSettingValue, ByteSizeUnit.BYTES).build(); + Settings transientSettings = Settings.builder().put(transientSettingKey, transientSettingValue, ByteSizeUnit.BYTES).build(); Settings persistentSettings = Settings.builder().put(persistentSettingKey, persistentSettingValue).build(); clusterUpdateSettings(persistentSettings, transientSettings); ClusterGetSettingsRequest request = new ClusterGetSettingsRequest(); ClusterGetSettingsResponse response = execute( - request, highLevelClient().cluster()::getSettings, highLevelClient().cluster()::getSettingsAsync); + request, + highLevelClient().cluster()::getSettings, + highLevelClient().cluster()::getSettingsAsync + ); assertEquals(persistentSettings, response.getPersistentSettings()); assertEquals(transientSettings, response.getTransientSettings()); assertEquals(0, response.getDefaultSettings().size()); @@ -178,14 +194,16 @@ public class ClusterClientIT extends OpenSearchRestHighLevelClientTestCase { final String persistentSettingKey = EnableAllocationDecider.CLUSTER_ROUTING_ALLOCATION_ENABLE_SETTING.getKey(); final String persistentSettingValue = EnableAllocationDecider.Allocation.NONE.name(); - Settings transientSettings = - Settings.builder().put(transientSettingKey, transientSettingValue, ByteSizeUnit.BYTES).build(); + Settings transientSettings = Settings.builder().put(transientSettingKey, transientSettingValue, ByteSizeUnit.BYTES).build(); Settings persistentSettings = Settings.builder().put(persistentSettingKey, persistentSettingValue).build(); clusterUpdateSettings(persistentSettings, transientSettings); ClusterGetSettingsRequest request = new ClusterGetSettingsRequest().includeDefaults(true); ClusterGetSettingsResponse response = execute( - request, highLevelClient().cluster()::getSettings, highLevelClient().cluster()::getSettingsAsync); + request, + highLevelClient().cluster()::getSettings, + highLevelClient().cluster()::getSettingsAsync + ); assertEquals(persistentSettings, response.getPersistentSettings()); assertEquals(transientSettings, response.getTransientSettings()); assertThat(response.getDefaultSettings().size(), greaterThan(0)); @@ -209,8 +227,7 @@ public class ClusterClientIT extends OpenSearchRestHighLevelClientTestCase { request.timeout("5s"); ClusterHealthResponse response = execute(request, highLevelClient().cluster()::health, highLevelClient().cluster()::healthAsync); - logger.info("Shard stats\n{}", EntityUtils.toString( - client().performRequest(new Request("GET", "/_cat/shards")).getEntity())); + logger.info("Shard stats\n{}", EntityUtils.toString(client().performRequest(new Request("GET", "/_cat/shards")).getEntity())); assertThat(response.getIndices().size(), equalTo(0)); } @@ -230,8 +247,7 @@ public class ClusterClientIT extends OpenSearchRestHighLevelClientTestCase { request.level(ClusterHealthRequest.Level.INDICES); ClusterHealthResponse response = execute(request, highLevelClient().cluster()::health, highLevelClient().cluster()::healthAsync); - logger.info("Shard stats\n{}", EntityUtils.toString( - client().performRequest(new Request("GET", "/_cat/shards")).getEntity())); + logger.info("Shard stats\n{}", EntityUtils.toString(client().performRequest(new Request("GET", "/_cat/shards")).getEntity())); assertYellowShards(response); assertThat(response.getIndices().size(), equalTo(2)); for (Map.Entry entry : response.getIndices().entrySet()) { @@ -253,7 +269,6 @@ public class ClusterClientIT extends OpenSearchRestHighLevelClientTestCase { assertThat(response.getUnassignedShards(), equalTo(2)); } - public void testClusterHealthYellowSpecificIndex() throws IOException { createIndex("index", Settings.EMPTY); createIndex("index2", Settings.EMPTY); @@ -280,14 +295,14 @@ public class ClusterClientIT extends OpenSearchRestHighLevelClientTestCase { private static void assertYellowIndex(String indexName, ClusterIndexHealth indexHealth, boolean emptyShards) { assertThat(indexHealth, notNullValue()); - assertThat(indexHealth.getIndex(),equalTo(indexName)); - assertThat(indexHealth.getActivePrimaryShards(),equalTo(1)); - assertThat(indexHealth.getActiveShards(),equalTo(1)); - assertThat(indexHealth.getNumberOfReplicas(),equalTo(1)); - assertThat(indexHealth.getInitializingShards(),equalTo(0)); - assertThat(indexHealth.getUnassignedShards(),equalTo(1)); - assertThat(indexHealth.getRelocatingShards(),equalTo(0)); - assertThat(indexHealth.getStatus(),equalTo(ClusterHealthStatus.YELLOW)); + assertThat(indexHealth.getIndex(), equalTo(indexName)); + assertThat(indexHealth.getActivePrimaryShards(), equalTo(1)); + assertThat(indexHealth.getActiveShards(), equalTo(1)); + assertThat(indexHealth.getNumberOfReplicas(), equalTo(1)); + assertThat(indexHealth.getInitializingShards(), equalTo(0)); + assertThat(indexHealth.getUnassignedShards(), equalTo(1)); + assertThat(indexHealth.getRelocatingShards(), equalTo(0)); + assertThat(indexHealth.getStatus(), equalTo(ClusterHealthStatus.YELLOW)); if (emptyShards) { assertThat(indexHealth.getShards().size(), equalTo(0)); } else { @@ -340,20 +355,21 @@ public class ClusterClientIT extends OpenSearchRestHighLevelClientTestCase { settingsRequest.includeDefaults(true); ClusterGetSettingsResponse settingsResponse = highLevelClient().cluster().getSettings(settingsRequest, RequestOptions.DEFAULT); - List seeds = SniffConnectionStrategy.REMOTE_CLUSTER_SEEDS - .getConcreteSettingForNamespace(clusterAlias) - .get(settingsResponse.getTransientSettings()); - int connectionsPerCluster = SniffConnectionStrategy.REMOTE_CONNECTIONS_PER_CLUSTER - .get(settingsResponse.getTransientSettings()); - TimeValue initialConnectionTimeout = RemoteClusterService.REMOTE_INITIAL_CONNECTION_TIMEOUT_SETTING - .get(settingsResponse.getTransientSettings()); - boolean skipUnavailable = RemoteClusterService.REMOTE_CLUSTER_SKIP_UNAVAILABLE - .getConcreteSettingForNamespace(clusterAlias) - .get(settingsResponse.getTransientSettings()); + List seeds = SniffConnectionStrategy.REMOTE_CLUSTER_SEEDS.getConcreteSettingForNamespace(clusterAlias) + .get(settingsResponse.getTransientSettings()); + int connectionsPerCluster = SniffConnectionStrategy.REMOTE_CONNECTIONS_PER_CLUSTER.get(settingsResponse.getTransientSettings()); + TimeValue initialConnectionTimeout = RemoteClusterService.REMOTE_INITIAL_CONNECTION_TIMEOUT_SETTING.get( + settingsResponse.getTransientSettings() + ); + boolean skipUnavailable = RemoteClusterService.REMOTE_CLUSTER_SKIP_UNAVAILABLE.getConcreteSettingForNamespace(clusterAlias) + .get(settingsResponse.getTransientSettings()); RemoteInfoRequest request = new RemoteInfoRequest(); - RemoteInfoResponse response = execute(request, highLevelClient().cluster()::remoteInfo, - highLevelClient().cluster()::remoteInfoAsync); + RemoteInfoResponse response = execute( + request, + highLevelClient().cluster()::remoteInfo, + highLevelClient().cluster()::remoteInfoAsync + ); assertThat(response, notNullValue()); assertThat(response.getInfos().size(), equalTo(1)); @@ -376,40 +392,61 @@ public class ClusterClientIT extends OpenSearchRestHighLevelClientTestCase { AliasMetadata alias = AliasMetadata.builder("alias").writeIndex(true).build(); Template template = new Template(settings, mappings, Collections.singletonMap("alias", alias)); ComponentTemplate componentTemplate = new ComponentTemplate(template, 1L, new HashMap<>()); - PutComponentTemplateRequest putComponentTemplateRequest = - new PutComponentTemplateRequest().name(templateName).create(true).componentTemplate(componentTemplate); + PutComponentTemplateRequest putComponentTemplateRequest = new PutComponentTemplateRequest().name(templateName) + .create(true) + .componentTemplate(componentTemplate); - AcknowledgedResponse response = execute(putComponentTemplateRequest, - highLevelClient().cluster()::putComponentTemplate, highLevelClient().cluster()::putComponentTemplateAsync); + AcknowledgedResponse response = execute( + putComponentTemplateRequest, + highLevelClient().cluster()::putComponentTemplate, + highLevelClient().cluster()::putComponentTemplateAsync + ); assertThat(response.isAcknowledged(), equalTo(true)); ComponentTemplatesExistRequest componentTemplatesExistRequest = new ComponentTemplatesExistRequest(templateName); - boolean exist = execute(componentTemplatesExistRequest, - highLevelClient().cluster()::existsComponentTemplate, highLevelClient().cluster()::existsComponentTemplateAsync); + boolean exist = execute( + componentTemplatesExistRequest, + highLevelClient().cluster()::existsComponentTemplate, + highLevelClient().cluster()::existsComponentTemplateAsync + ); assertTrue(exist); GetComponentTemplatesRequest getComponentTemplatesRequest = new GetComponentTemplatesRequest(templateName); - GetComponentTemplatesResponse getResponse = execute(getComponentTemplatesRequest, - highLevelClient().cluster()::getComponentTemplate, highLevelClient().cluster()::getComponentTemplateAsync); + GetComponentTemplatesResponse getResponse = execute( + getComponentTemplatesRequest, + highLevelClient().cluster()::getComponentTemplate, + highLevelClient().cluster()::getComponentTemplateAsync + ); assertThat(getResponse.getComponentTemplates().size(), equalTo(1)); assertThat(getResponse.getComponentTemplates().containsKey(templateName), equalTo(true)); assertThat(getResponse.getComponentTemplates().get(templateName), equalTo(componentTemplate)); DeleteComponentTemplateRequest deleteComponentTemplateRequest = new DeleteComponentTemplateRequest(templateName); - response = execute(deleteComponentTemplateRequest, highLevelClient().cluster()::deleteComponentTemplate, - highLevelClient().cluster()::deleteComponentTemplateAsync); + response = execute( + deleteComponentTemplateRequest, + highLevelClient().cluster()::deleteComponentTemplate, + highLevelClient().cluster()::deleteComponentTemplateAsync + ); assertThat(response.isAcknowledged(), equalTo(true)); - OpenSearchStatusException statusException = expectThrows(OpenSearchStatusException.class, - () -> execute(getComponentTemplatesRequest, - highLevelClient().cluster()::getComponentTemplate, highLevelClient().cluster()::getComponentTemplateAsync)); + OpenSearchStatusException statusException = expectThrows( + OpenSearchStatusException.class, + () -> execute( + getComponentTemplatesRequest, + highLevelClient().cluster()::getComponentTemplate, + highLevelClient().cluster()::getComponentTemplateAsync + ) + ); assertThat(statusException.status(), equalTo(RestStatus.NOT_FOUND)); - exist = execute(componentTemplatesExistRequest, - highLevelClient().cluster()::existsComponentTemplate, highLevelClient().cluster()::existsComponentTemplateAsync); + exist = execute( + componentTemplatesExistRequest, + highLevelClient().cluster()::existsComponentTemplate, + highLevelClient().cluster()::existsComponentTemplateAsync + ); assertFalse(exist); } diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/ClusterRequestConvertersTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/ClusterRequestConvertersTests.java index 894241db169..2af164a51db 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/ClusterRequestConvertersTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/ClusterRequestConvertersTests.java @@ -34,7 +34,6 @@ package org.opensearch.client; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPut; -import org.opensearch.client.Request; import org.opensearch.action.admin.cluster.health.ClusterHealthRequest; import org.opensearch.action.admin.cluster.settings.ClusterGetSettingsRequest; import org.opensearch.action.admin.cluster.settings.ClusterUpdateSettingsRequest; 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 13a764cf010..56d46357726 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 @@ -32,7 +32,6 @@ package org.opensearch.client; -import org.opensearch.client.RequestOptions; import org.opensearch.OpenSearchException; import org.opensearch.OpenSearchStatusException; import org.opensearch.action.DocWriteRequest; @@ -104,7 +103,9 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { // Testing deletion String docId = "id"; IndexResponse indexResponse = highLevelClient().index( - new IndexRequest("index").id(docId).source(Collections.singletonMap("foo", "bar")), RequestOptions.DEFAULT); + new IndexRequest("index").id(docId).source(Collections.singletonMap("foo", "bar")), + RequestOptions.DEFAULT + ); assertThat(indexResponse.getSeqNo(), greaterThanOrEqualTo(0L)); DeleteRequest deleteRequest = new DeleteRequest("index", docId); if (randomBoolean()) { @@ -131,23 +132,35 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { // Testing version conflict String docId = "version_conflict"; highLevelClient().index( - new IndexRequest("index").id( docId).source(Collections.singletonMap("foo", "bar")), RequestOptions.DEFAULT); + new IndexRequest("index").id(docId).source(Collections.singletonMap("foo", "bar")), + RequestOptions.DEFAULT + ); DeleteRequest deleteRequest = new DeleteRequest("index", docId).setIfSeqNo(2).setIfPrimaryTerm(2); - OpenSearchException exception = expectThrows(OpenSearchException.class, - () -> execute(deleteRequest, highLevelClient()::delete, highLevelClient()::deleteAsync)); + OpenSearchException exception = expectThrows( + OpenSearchException.class, + () -> execute(deleteRequest, highLevelClient()::delete, highLevelClient()::deleteAsync) + ); assertEquals(RestStatus.CONFLICT, exception.status()); - assertEquals("OpenSearch exception [type=version_conflict_engine_exception, reason=[" + docId + "]: " + - "version conflict, required seqNo [2], primary term [2]. current document has seqNo [3] and primary term [1]]", - exception.getMessage()); + assertEquals( + "OpenSearch exception [type=version_conflict_engine_exception, reason=[" + + docId + + "]: " + + "version conflict, required seqNo [2], primary term [2]. current document has seqNo [3] and primary term [1]]", + exception.getMessage() + ); assertEquals("index", exception.getMetadata("opensearch.index").get(0)); } { // Testing version type String docId = "version_type"; highLevelClient().index( - new IndexRequest("index").id(docId).source(Collections.singletonMap("foo", "bar")) - .versionType(VersionType.EXTERNAL).version(12), RequestOptions.DEFAULT); - DeleteRequest deleteRequest = new DeleteRequest("index", docId).versionType(VersionType.EXTERNAL).version(13); + new IndexRequest("index").id(docId) + .source(Collections.singletonMap("foo", "bar")) + .versionType(VersionType.EXTERNAL) + .version(12), + RequestOptions.DEFAULT + ); + DeleteRequest deleteRequest = new DeleteRequest("index", docId).versionType(VersionType.EXTERNAL).version(13); DeleteResponse deleteResponse = execute(deleteRequest, highLevelClient()::delete, highLevelClient()::deleteAsync); assertEquals("index", deleteResponse.getIndex()); assertEquals("_doc", deleteResponse.getType()); @@ -158,23 +171,33 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { // Testing version type with a wrong version String docId = "wrong_version"; highLevelClient().index( - new IndexRequest("index").id(docId).source(Collections.singletonMap("foo", "bar")) - .versionType(VersionType.EXTERNAL).version(12), RequestOptions.DEFAULT); + new IndexRequest("index").id(docId) + .source(Collections.singletonMap("foo", "bar")) + .versionType(VersionType.EXTERNAL) + .version(12), + RequestOptions.DEFAULT + ); OpenSearchStatusException exception = expectThrows(OpenSearchStatusException.class, () -> { - DeleteRequest deleteRequest = new DeleteRequest("index", docId).versionType(VersionType.EXTERNAL).version(10); + DeleteRequest deleteRequest = new DeleteRequest("index", docId).versionType(VersionType.EXTERNAL).version(10); execute(deleteRequest, highLevelClient()::delete, highLevelClient()::deleteAsync); }); assertEquals(RestStatus.CONFLICT, exception.status()); - assertEquals("OpenSearch exception [type=version_conflict_engine_exception, reason=[" + - docId + "]: version conflict, current version [12] is higher or equal to the one provided [10]]", exception.getMessage()); + assertEquals( + "OpenSearch exception [type=version_conflict_engine_exception, reason=[" + + docId + + "]: version conflict, current version [12] is higher or equal to the one provided [10]]", + exception.getMessage() + ); assertEquals("index", exception.getMetadata("opensearch.index").get(0)); } { // Testing routing String docId = "routing"; - highLevelClient().index(new IndexRequest("index").id(docId).source(Collections.singletonMap("foo", "bar")).routing("foo"), - RequestOptions.DEFAULT); - DeleteRequest deleteRequest = new DeleteRequest("index", docId).routing("foo"); + highLevelClient().index( + new IndexRequest("index").id(docId).source(Collections.singletonMap("foo", "bar")).routing("foo"), + RequestOptions.DEFAULT + ); + DeleteRequest deleteRequest = new DeleteRequest("index", docId).routing("foo"); DeleteResponse deleteResponse = execute(deleteRequest, highLevelClient()::delete, highLevelClient()::deleteAsync); assertEquals("index", deleteResponse.getIndex()); assertEquals("_doc", deleteResponse.getType()); @@ -187,17 +210,20 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { String docId = "id"; IndexRequest indexRequest = new IndexRequest("index", "type", docId); indexRequest.source(Collections.singletonMap("foo", "bar")); - execute(indexRequest, + execute( + indexRequest, highLevelClient()::index, highLevelClient()::indexAsync, expectWarnings(RestIndexAction.TYPES_DEPRECATION_MESSAGE) ); DeleteRequest deleteRequest = new DeleteRequest("index", "type", docId); - DeleteResponse deleteResponse = execute(deleteRequest, + DeleteResponse deleteResponse = execute( + deleteRequest, highLevelClient()::delete, highLevelClient()::deleteAsync, - expectWarnings(RestDeleteAction.TYPES_DEPRECATION_MESSAGE)); + expectWarnings(RestDeleteAction.TYPES_DEPRECATION_MESSAGE) + ); assertEquals("index", deleteResponse.getIndex()); assertEquals("type", deleteResponse.getType()); @@ -276,20 +302,16 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { final String noSourceIndex = "no_source"; { // Prepare - Settings settings = Settings.builder() - .put("number_of_shards", 1) - .put("number_of_replicas", 0) - .build(); + Settings settings = Settings.builder().put("number_of_shards", 1).put("number_of_replicas", 0).build(); String mapping = "\"_source\": {\"enabled\": false}"; createIndex(noSourceIndex, settings, mapping); assertEquals( RestStatus.OK, highLevelClient().bulk( - new BulkRequest() - .add(new IndexRequest(noSourceIndex).id("1") - .source(Collections.singletonMap("foo", 1), XContentType.JSON)) - .add(new IndexRequest(noSourceIndex).id("2") - .source(Collections.singletonMap("foo", 2), XContentType.JSON)) + new BulkRequest().add( + new IndexRequest(noSourceIndex).id("1").source(Collections.singletonMap("foo", 1), XContentType.JSON) + ) + .add(new IndexRequest(noSourceIndex).id("2").source(Collections.singletonMap("foo", 2), XContentType.JSON)) .setRefreshPolicy(RefreshPolicy.IMMEDIATE), RequestOptions.DEFAULT ).status() @@ -309,8 +331,10 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { public void testGet() throws IOException { { GetRequest getRequest = new GetRequest("index", "id"); - OpenSearchException exception = expectThrows(OpenSearchException.class, - () -> execute(getRequest, highLevelClient()::get, highLevelClient()::getAsync)); + OpenSearchException exception = expectThrows( + OpenSearchException.class, + () -> execute(getRequest, highLevelClient()::get, highLevelClient()::getAsync) + ); assertEquals(RestStatus.NOT_FOUND, exception.status()); assertEquals("OpenSearch exception [type=index_not_found_exception, reason=no such index [index]]", exception.getMessage()); assertEquals("index", exception.getMetadata("opensearch.index").get(0)); @@ -322,11 +346,17 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { highLevelClient().index(index, RequestOptions.DEFAULT); { GetRequest getRequest = new GetRequest("index", "id").version(2); - OpenSearchException exception = expectThrows(OpenSearchException.class, - () -> execute(getRequest, highLevelClient()::get, highLevelClient()::getAsync)); + OpenSearchException exception = expectThrows( + OpenSearchException.class, + () -> execute(getRequest, highLevelClient()::get, highLevelClient()::getAsync) + ); assertEquals(RestStatus.CONFLICT, exception.status()); - assertEquals("OpenSearch exception [type=version_conflict_engine_exception, " + "reason=[id]: " + - "version conflict, current version [1] is different than the one provided [2]]", exception.getMessage()); + assertEquals( + "OpenSearch exception [type=version_conflict_engine_exception, " + + "reason=[id]: " + + "version conflict, current version [1] is different than the one provided [2]]", + exception.getMessage() + ); assertEquals("index", exception.getMetadata("opensearch.index").get(0)); } { @@ -369,9 +399,9 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { { GetRequest getRequest = new GetRequest("index", "id"); if (randomBoolean()) { - getRequest.fetchSourceContext(new FetchSourceContext(true, new String[]{"field1"}, Strings.EMPTY_ARRAY)); + getRequest.fetchSourceContext(new FetchSourceContext(true, new String[] { "field1" }, Strings.EMPTY_ARRAY)); } else { - getRequest.fetchSourceContext(new FetchSourceContext(true, Strings.EMPTY_ARRAY, new String[]{"field2"})); + getRequest.fetchSourceContext(new FetchSourceContext(true, Strings.EMPTY_ARRAY, new String[] { "field2" })); } GetResponse getResponse = execute(getRequest, highLevelClient()::get, highLevelClient()::getAsync); assertEquals("index", getResponse.getIndex()); @@ -391,17 +421,20 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { IndexRequest indexRequest = new IndexRequest("index", "type", "id"); indexRequest.source(document, XContentType.JSON); indexRequest.setRefreshPolicy(RefreshPolicy.IMMEDIATE); - execute(indexRequest, + execute( + indexRequest, highLevelClient()::index, highLevelClient()::indexAsync, expectWarnings(RestIndexAction.TYPES_DEPRECATION_MESSAGE) ); GetRequest getRequest = new GetRequest("index", "type", "id"); - GetResponse getResponse = execute(getRequest, + GetResponse getResponse = execute( + getRequest, highLevelClient()::get, highLevelClient()::getAsync, - expectWarnings(RestGetAction.TYPES_DEPRECATION_MESSAGE)); + expectWarnings(RestGetAction.TYPES_DEPRECATION_MESSAGE) + ); assertEquals("index", getResponse.getIndex()); assertEquals("type", getResponse.getType()); @@ -426,16 +459,20 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { assertEquals("id1", response.getResponses()[0].getFailure().getId()); assertNull(response.getResponses()[0].getFailure().getType()); assertEquals("index", response.getResponses()[0].getFailure().getIndex()); - assertEquals("OpenSearch exception [type=index_not_found_exception, reason=no such index [index]]", - response.getResponses()[0].getFailure().getFailure().getMessage()); + assertEquals( + "OpenSearch exception [type=index_not_found_exception, reason=no such index [index]]", + response.getResponses()[0].getFailure().getFailure().getMessage() + ); assertTrue(response.getResponses()[1].isFailed()); assertNull(response.getResponses()[1].getResponse()); assertEquals("id2", response.getResponses()[1].getId()); assertNull(response.getResponses()[1].getType()); assertEquals("index", response.getResponses()[1].getIndex()); - assertEquals("OpenSearch exception [type=index_not_found_exception, reason=no such index [index]]", - response.getResponses()[1].getFailure().getFailure().getMessage()); + assertEquals( + "OpenSearch exception [type=index_not_found_exception, reason=no such index [index]]", + response.getResponses()[1].getFailure().getFailure().getMessage() + ); } BulkRequest bulk = new BulkRequest(); bulk.setRefreshPolicy(RefreshPolicy.IMMEDIATE); @@ -472,20 +509,20 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { public void testMultiGetWithTypes() throws IOException { BulkRequest bulk = new BulkRequest(); bulk.setRefreshPolicy(RefreshPolicy.IMMEDIATE); - bulk.add(new IndexRequest("index", "type", "id1") - .source("{\"field\":\"value1\"}", XContentType.JSON)); - bulk.add(new IndexRequest("index", "type", "id2") - .source("{\"field\":\"value2\"}", XContentType.JSON)); + bulk.add(new IndexRequest("index", "type", "id1").source("{\"field\":\"value1\"}", XContentType.JSON)); + bulk.add(new IndexRequest("index", "type", "id2").source("{\"field\":\"value2\"}", XContentType.JSON)); highLevelClient().bulk(bulk, expectWarnings(RestBulkAction.TYPES_DEPRECATION_MESSAGE)); MultiGetRequest multiGetRequest = new MultiGetRequest(); multiGetRequest.add("index", "id1"); multiGetRequest.add("index", "type", "id2"); - MultiGetResponse response = execute(multiGetRequest, + MultiGetResponse response = execute( + multiGetRequest, highLevelClient()::mget, highLevelClient()::mgetAsync, - expectWarnings(RestMultiGetAction.TYPES_DEPRECATION_MESSAGE)); + expectWarnings(RestMultiGetAction.TYPES_DEPRECATION_MESSAGE) + ); assertEquals(2, response.getResponses().length); GetResponse firstResponse = response.getResponses()[0].getResponse(); @@ -502,8 +539,10 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { public void testGetSource() throws IOException { { GetSourceRequest getRequest = new GetSourceRequest("index", "id"); - OpenSearchException exception = expectThrows(OpenSearchException.class, - () -> execute(getRequest, highLevelClient()::getSource, highLevelClient()::getSourceAsync)); + OpenSearchException exception = expectThrows( + OpenSearchException.class, + () -> execute(getRequest, highLevelClient()::getSource, highLevelClient()::getSourceAsync) + ); assertEquals(RestStatus.NOT_FOUND, exception.status()); assertEquals("OpenSearch exception [type=index_not_found_exception, reason=no such index [index]]", exception.getMessage()); assertEquals("index", exception.getMetadata("opensearch.index").get(0)); @@ -523,11 +562,15 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { } { GetSourceRequest getRequest = new GetSourceRequest("index", "does_not_exist"); - OpenSearchException exception = expectThrows(OpenSearchException.class, - () -> execute(getRequest, highLevelClient()::getSource, highLevelClient()::getSourceAsync)); + OpenSearchException exception = expectThrows( + OpenSearchException.class, + () -> execute(getRequest, highLevelClient()::getSource, highLevelClient()::getSourceAsync) + ); assertEquals(RestStatus.NOT_FOUND, exception.status()); - assertEquals("OpenSearch exception [type=resource_not_found_exception, " + - "reason=Document not found [index]/[_doc]/[does_not_exist]]", exception.getMessage()); + assertEquals( + "OpenSearch exception [type=resource_not_found_exception, " + "reason=Document not found [index]/[_doc]/[does_not_exist]]", + exception.getMessage() + ); } { GetSourceRequest getRequest = new GetSourceRequest("index", "id"); @@ -540,7 +583,7 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { } { GetSourceRequest getRequest = new GetSourceRequest("index", "id"); - getRequest.fetchSourceContext(new FetchSourceContext(true, new String[]{"field1"}, Strings.EMPTY_ARRAY)); + getRequest.fetchSourceContext(new FetchSourceContext(true, new String[] { "field1" }, Strings.EMPTY_ARRAY)); GetSourceResponse response = execute(getRequest, highLevelClient()::getSource, highLevelClient()::getSourceAsync); Map expectedResponse = new HashMap<>(); expectedResponse.put("field1", "value1"); @@ -548,7 +591,7 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { } { GetSourceRequest getRequest = new GetSourceRequest("index", "id"); - getRequest.fetchSourceContext(new FetchSourceContext(true, Strings.EMPTY_ARRAY, new String[]{"field1"})); + getRequest.fetchSourceContext(new FetchSourceContext(true, Strings.EMPTY_ARRAY, new String[] { "field1" })); GetSourceResponse response = execute(getRequest, highLevelClient()::getSource, highLevelClient()::getSourceAsync); Map expectedResponse = new HashMap<>(); expectedResponse.put("field2", "value2"); @@ -557,10 +600,15 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { { GetSourceRequest getRequest = new GetSourceRequest("index", "id"); getRequest.fetchSourceContext(new FetchSourceContext(false)); - OpenSearchException exception = expectThrows(OpenSearchException.class, - () -> execute(getRequest, highLevelClient()::getSource, highLevelClient()::getSourceAsync)); - assertEquals("OpenSearch exception [type=action_request_validation_exception, " + - "reason=Validation Failed: 1: fetching source can not be disabled;]", exception.getMessage()); + OpenSearchException exception = expectThrows( + OpenSearchException.class, + () -> execute(getRequest, highLevelClient()::getSource, highLevelClient()::getSourceAsync) + ); + assertEquals( + "OpenSearch exception [type=action_request_validation_exception, " + + "reason=Validation Failed: 1: fetching source can not be disabled;]", + exception.getMessage() + ); } } @@ -616,9 +664,11 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { execute(wrongRequest, highLevelClient()::index, highLevelClient()::indexAsync); }); assertEquals(RestStatus.CONFLICT, exception.status()); - assertEquals("OpenSearch exception [type=version_conflict_engine_exception, reason=[id]: " + - "version conflict, required seqNo [1], primary term [5]. current document has seqNo [2] and primary term [1]]", - exception.getMessage()); + assertEquals( + "OpenSearch exception [type=version_conflict_engine_exception, reason=[id]: " + + "version conflict, required seqNo [1], primary term [5]. current document has seqNo [2] and primary term [1]]", + exception.getMessage() + ); assertEquals("index", exception.getMetadata("opensearch.index").get(0)); } { @@ -631,8 +681,10 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { }); assertEquals(RestStatus.BAD_REQUEST, exception.status()); - assertEquals("OpenSearch exception [type=illegal_argument_exception, " + - "reason=pipeline with id [missing] does not exist]", exception.getMessage()); + assertEquals( + "OpenSearch exception [type=illegal_argument_exception, " + "reason=pipeline with id [missing] does not exist]", + exception.getMessage() + ); } { IndexRequest indexRequest = new IndexRequest("index").id("external_version_type"); @@ -658,13 +710,17 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { assertEquals("_doc", indexResponse.getType()); 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("OpenSearch exception [type=version_conflict_engine_exception, reason=[with_create_op_type]: " + - "version conflict, document already exists (current version [1])]", exception.getMessage()); + assertEquals( + "OpenSearch exception [type=version_conflict_engine_exception, reason=[with_create_op_type]: " + + "version conflict, document already exists (current version [1])]", + exception.getMessage() + ); } } @@ -681,7 +737,7 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { assertEquals(RestStatus.CREATED, indexResponse.status()); assertEquals("index", indexResponse.getIndex()); assertEquals("some_type", indexResponse.getType()); - assertEquals("some_id",indexResponse.getId()); + assertEquals("some_id", indexResponse.getId()); } public void testUpdate() throws IOException { @@ -689,19 +745,22 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { UpdateRequest updateRequest = new UpdateRequest("index", "does_not_exist"); updateRequest.doc(singletonMap("field", "value"), randomFrom(XContentType.values())); - OpenSearchStatusException exception = expectThrows(OpenSearchStatusException.class, () -> - execute(updateRequest, highLevelClient()::update, highLevelClient()::updateAsync)); + OpenSearchStatusException exception = expectThrows( + OpenSearchStatusException.class, + () -> execute(updateRequest, highLevelClient()::update, highLevelClient()::updateAsync) + ); assertEquals(RestStatus.NOT_FOUND, exception.status()); - assertEquals("OpenSearch exception [type=document_missing_exception, reason=[_doc][does_not_exist]: document missing]", - exception.getMessage()); + assertEquals( + "OpenSearch exception [type=document_missing_exception, reason=[_doc][does_not_exist]: document missing]", + exception.getMessage() + ); } { - IndexRequest indexRequest = new IndexRequest("index").id( "id"); + IndexRequest indexRequest = new IndexRequest("index").id("id"); indexRequest.source(singletonMap("field", "value")); IndexResponse indexResponse = highLevelClient().index(indexRequest, RequestOptions.DEFAULT); assertEquals(RestStatus.CREATED, indexResponse.status()); - long lastUpdateSeqNo; long lastUpdatePrimaryTerm; { @@ -726,9 +785,11 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { updateRequest.setIfSeqNo(lastUpdateSeqNo + (randomBoolean() ? 0 : 1)); updateRequest.setIfPrimaryTerm(lastUpdatePrimaryTerm + 1); } - OpenSearchStatusException exception = expectThrows(OpenSearchStatusException.class, () -> - execute(updateRequest, highLevelClient()::update, highLevelClient()::updateAsync)); - assertEquals(exception.toString(),RestStatus.CONFLICT, exception.status()); + OpenSearchStatusException exception = expectThrows( + OpenSearchStatusException.class, + () -> execute(updateRequest, highLevelClient()::update, highLevelClient()::updateAsync) + ); + assertEquals(exception.toString(), RestStatus.CONFLICT, exception.status()); assertThat(exception.getMessage(), containsString("OpenSearch exception [type=version_conflict_engine_exception")); } { @@ -860,15 +921,18 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { updateRequest.upsert(new IndexRequest().source(Collections.singletonMap("field", "upsert"), XContentType.YAML)); execute(updateRequest, highLevelClient()::update, highLevelClient()::updateAsync); }); - assertEquals("Update request cannot have different content types for doc [JSON] and upsert [YAML] documents", - exception.getMessage()); + assertEquals( + "Update request cannot have different content types for doc [JSON] and upsert [YAML] documents", + exception.getMessage() + ); } } public void testUpdateWithTypes() throws IOException { IndexRequest indexRequest = new IndexRequest("index", "type", "id"); indexRequest.source(singletonMap("field", "value")); - IndexResponse indexResponse = execute(indexRequest, + IndexResponse indexResponse = execute( + indexRequest, highLevelClient()::index, highLevelClient()::indexAsync, expectWarnings(RestIndexAction.TYPES_DEPRECATION_MESSAGE) @@ -876,10 +940,12 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { UpdateRequest updateRequest = new UpdateRequest("index", "type", "id"); updateRequest.doc(singletonMap("field", "updated"), randomFrom(XContentType.values())); - UpdateResponse updateResponse = execute(updateRequest, + UpdateResponse updateResponse = execute( + updateRequest, highLevelClient()::update, highLevelClient()::updateAsync, - expectWarnings(RestUpdateAction.TYPES_DEPRECATION_MESSAGE)); + expectWarnings(RestUpdateAction.TYPES_DEPRECATION_MESSAGE) + ); assertEquals(RestStatus.OK, updateResponse.status()); assertEquals(indexResponse.getVersion() + 1, updateResponse.getVersion()); @@ -900,16 +966,18 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { DocWriteRequest.OpType opType = randomFrom(DocWriteRequest.OpType.values()); if (opType == DocWriteRequest.OpType.DELETE) { if (erroneous == false) { - assertEquals(RestStatus.CREATED, - highLevelClient().index( - new IndexRequest("index").id(id).source("field", -1), RequestOptions.DEFAULT).status()); + assertEquals( + RestStatus.CREATED, + highLevelClient().index(new IndexRequest("index").id(id).source("field", -1), RequestOptions.DEFAULT).status() + ); } DeleteRequest deleteRequest = new DeleteRequest("index", id); bulkRequest.add(deleteRequest); } else { - BytesReference source = BytesReference.bytes(XContentBuilder.builder(xContentType.xContent()) - .startObject().field("id", i).endObject()); + BytesReference source = BytesReference.bytes( + XContentBuilder.builder(xContentType.xContent()).startObject().field("id", i).endObject() + ); if (opType == DocWriteRequest.OpType.INDEX) { IndexRequest indexRequest = new IndexRequest("index").id(id).source(source, xContentType); if (erroneous) { @@ -926,12 +994,12 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { bulkRequest.add(createRequest); } else if (opType == DocWriteRequest.OpType.UPDATE) { - UpdateRequest updateRequest = new UpdateRequest("index", id) - .doc(new IndexRequest().source(source, xContentType)); + UpdateRequest updateRequest = new UpdateRequest("index", id).doc(new IndexRequest().source(source, xContentType)); if (erroneous == false) { - assertEquals(RestStatus.CREATED, - highLevelClient().index( - new IndexRequest("index").id(id).source("field", -1), RequestOptions.DEFAULT).status()); + assertEquals( + RestStatus.CREATED, + highLevelClient().index(new IndexRequest("index").id(id).source("field", -1), RequestOptions.DEFAULT).status() + ); } bulkRequest.add(updateRequest); } @@ -974,13 +1042,12 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { } }; - try (BulkProcessor processor = BulkProcessor.builder( - (request, bulkListener) -> highLevelClient().bulkAsync(request, - RequestOptions.DEFAULT, bulkListener), listener) - .setConcurrentRequests(0) - .setBulkSize(new ByteSizeValue(5, ByteSizeUnit.GB)) - .setBulkActions(nbItems + 1) - .build()) { + try ( + BulkProcessor processor = BulkProcessor.builder( + (request, bulkListener) -> highLevelClient().bulkAsync(request, RequestOptions.DEFAULT, bulkListener), + listener + ).setConcurrentRequests(0).setBulkSize(new ByteSizeValue(5, ByteSizeUnit.GB)).setBulkActions(nbItems + 1).build() + ) { for (int i = 0; i < nbItems; i++) { String id = String.valueOf(i); boolean erroneous = randomBoolean(); @@ -989,9 +1056,10 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { DocWriteRequest.OpType opType = randomFrom(DocWriteRequest.OpType.values()); if (opType == DocWriteRequest.OpType.DELETE) { if (erroneous == false) { - assertEquals(RestStatus.CREATED, - highLevelClient().index( - new IndexRequest("index").id(id).source("field", -1), RequestOptions.DEFAULT).status()); + assertEquals( + RestStatus.CREATED, + highLevelClient().index(new IndexRequest("index").id(id).source("field", -1), RequestOptions.DEFAULT).status() + ); } DeleteRequest deleteRequest = new DeleteRequest("index", id); processor.add(deleteRequest); @@ -1013,12 +1081,13 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { processor.add(createRequest); } else if (opType == DocWriteRequest.OpType.UPDATE) { - UpdateRequest updateRequest = new UpdateRequest("index", id) - .doc(new IndexRequest().source(xContentType, "id", i)); + UpdateRequest updateRequest = new UpdateRequest("index", id).doc(new IndexRequest().source(xContentType, "id", i)); if (erroneous == false) { - assertEquals(RestStatus.CREATED, - highLevelClient().index( - new IndexRequest("index").id(id).source("field", -1), RequestOptions.DEFAULT).status()); + assertEquals( + RestStatus.CREATED, + highLevelClient().index(new IndexRequest("index").id(id).source("field", -1), RequestOptions.DEFAULT) + .status() + ); } processor.add(updateRequest); } @@ -1028,7 +1097,6 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { assertNull(requestRef.get()); } - BulkResponse bulkResponse = responseRef.get(); BulkRequest bulkRequest = requestRef.get(); @@ -1065,8 +1133,8 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { public void testUrlEncode() throws IOException { String indexPattern = ""; - String expectedIndex = "logstash-" + - DateTimeFormat.forPattern("YYYY.MM.dd").print(new DateTime(DateTimeZone.UTC).monthOfYear().roundFloorCopy()); + String expectedIndex = "logstash-" + + DateTimeFormat.forPattern("YYYY.MM.dd").print(new DateTime(DateTimeZone.UTC).monthOfYear().roundFloorCopy()); { IndexRequest indexRequest = new IndexRequest(indexPattern).id("id#1"); indexRequest.source("field", "value"); @@ -1106,7 +1174,7 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { } public void testParamsEncode() throws IOException { - //parameters are encoded by the low-level client but let's test that everything works the same when we use the high-level one + // parameters are encoded by the low-level client but let's test that everything works the same when we use the high-level one String routing = "routing/中文value#1?"; { IndexRequest indexRequest = new IndexRequest("index").id("id"); @@ -1151,20 +1219,16 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { final String sourceIndex = "index1"; { // prepare : index docs - Settings settings = Settings.builder() - .put("number_of_shards", 1) - .put("number_of_replicas", 0) - .build(); + Settings settings = Settings.builder().put("number_of_shards", 1).put("number_of_replicas", 0).build(); String mappings = "\"properties\":{\"field\":{\"type\":\"text\"}}"; createIndex(sourceIndex, settings, mappings); assertEquals( RestStatus.OK, highLevelClient().bulk( - new BulkRequest() - .add(new IndexRequest(sourceIndex).id("1") - .source(Collections.singletonMap("field", "value1"), XContentType.JSON)) - .add(new IndexRequest(sourceIndex).id("2") - .source(Collections.singletonMap("field", "value2"), XContentType.JSON)) + new BulkRequest().add( + new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("field", "value1"), XContentType.JSON) + ) + .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("field", "value2"), XContentType.JSON)) .setRefreshPolicy(RefreshPolicy.IMMEDIATE), RequestOptions.DEFAULT ).status() @@ -1178,11 +1242,19 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { TermVectorsResponse.TermVector.Token expectedToken = new TermVectorsResponse.TermVector.Token(0, 6, 0, null); TermVectorsResponse.TermVector.Term expectedTerm = new TermVectorsResponse.TermVector.Term( - "value1", 1, null, null, null, Collections.singletonList(expectedToken)); - TermVectorsResponse.TermVector.FieldStatistics expectedFieldStats = - new TermVectorsResponse.TermVector.FieldStatistics(2, 2, 2); - TermVectorsResponse.TermVector expectedTV = - new TermVectorsResponse.TermVector("field", expectedFieldStats, Collections.singletonList(expectedTerm)); + "value1", + 1, + null, + null, + null, + Collections.singletonList(expectedToken) + ); + TermVectorsResponse.TermVector.FieldStatistics expectedFieldStats = new TermVectorsResponse.TermVector.FieldStatistics(2, 2, 2); + TermVectorsResponse.TermVector expectedTV = new TermVectorsResponse.TermVector( + "field", + expectedFieldStats, + Collections.singletonList(expectedTerm) + ); List expectedTVlist = Collections.singletonList(expectedTV); assertThat(tvResponse.getIndex(), equalTo(sourceIndex)); @@ -1200,11 +1272,19 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { TermVectorsResponse.TermVector.Token expectedToken = new TermVectorsResponse.TermVector.Token(0, 6, 0, null); TermVectorsResponse.TermVector.Term expectedTerm = new TermVectorsResponse.TermVector.Term( - "valuex", 1, null, null, null, Collections.singletonList(expectedToken)); - TermVectorsResponse.TermVector.FieldStatistics expectedFieldStats = - new TermVectorsResponse.TermVector.FieldStatistics(2, 2, 2); - TermVectorsResponse.TermVector expectedTV = - new TermVectorsResponse.TermVector("field", expectedFieldStats, Collections.singletonList(expectedTerm)); + "valuex", + 1, + null, + null, + null, + Collections.singletonList(expectedToken) + ); + TermVectorsResponse.TermVector.FieldStatistics expectedFieldStats = new TermVectorsResponse.TermVector.FieldStatistics(2, 2, 2); + TermVectorsResponse.TermVector expectedTV = new TermVectorsResponse.TermVector( + "field", + expectedFieldStats, + Collections.singletonList(expectedTerm) + ); List expectedTVlist = Collections.singletonList(expectedTV); assertThat(tvResponse.getIndex(), equalTo(sourceIndex)); @@ -1217,8 +1297,10 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { public void testTermvectorsWithNonExistentIndex() { TermVectorsRequest request = new TermVectorsRequest("non-existent", "non-existent"); - OpenSearchException exception = expectThrows(OpenSearchException.class, - () -> execute(request, highLevelClient()::termvectors, highLevelClient()::termvectorsAsync)); + OpenSearchException exception = expectThrows( + OpenSearchException.class, + () -> execute(request, highLevelClient()::termvectors, highLevelClient()::termvectorsAsync) + ); assertEquals(RestStatus.NOT_FOUND, exception.status()); } @@ -1227,10 +1309,7 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { final String sourceIndex = "index1"; { // prepare : index docs - Settings settings = Settings.builder() - .put("number_of_shards", 1) - .put("number_of_replicas", 0) - .build(); + Settings settings = Settings.builder().put("number_of_shards", 1).put("number_of_replicas", 0).build(); String mappings = "\"properties\":{\"field\":{\"type\":\"text\"}, \"field2\":{\"type\":\"text\"}}"; createIndex(sourceIndex, settings, mappings); final Map doc1 = new HashMap<>(); @@ -1242,8 +1321,7 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { assertEquals( RestStatus.OK, highLevelClient().bulk( - new BulkRequest() - .add(new IndexRequest(sourceIndex).id("1").source(doc1, XContentType.JSON)) + new BulkRequest().add(new IndexRequest(sourceIndex).id("1").source(doc1, XContentType.JSON)) .add(new IndexRequest(sourceIndex).id("2").source(doc2, XContentType.JSON)) .setRefreshPolicy(RefreshPolicy.IMMEDIATE), RequestOptions.DEFAULT @@ -1252,16 +1330,19 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { } { // test _mtermvectors where MultiTermVectorsRequest is constructed with ids and a template - String[] expectedIds = {"1", "2"}; + String[] expectedIds = { "1", "2" }; TermVectorsRequest tvRequestTemplate = new TermVectorsRequest(sourceIndex, "fake_id"); tvRequestTemplate.setFields("field"); MultiTermVectorsRequest mtvRequest = new MultiTermVectorsRequest(expectedIds, tvRequestTemplate); - MultiTermVectorsResponse mtvResponse = - execute(mtvRequest, highLevelClient()::mtermvectors, highLevelClient()::mtermvectorsAsync); + MultiTermVectorsResponse mtvResponse = execute( + mtvRequest, + highLevelClient()::mtermvectors, + highLevelClient()::mtermvectorsAsync + ); List ids = new ArrayList<>(); - for (TermVectorsResponse tvResponse: mtvResponse.getTermVectorsResponses()) { + for (TermVectorsResponse tvResponse : mtvResponse.getTermVectorsResponses()) { assertThat(tvResponse.getIndex(), equalTo(sourceIndex)); assertTrue(tvResponse.getFound()); ids.add(tvResponse.getId()); @@ -1281,9 +1362,12 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { TermVectorsRequest tvRequest2 = new TermVectorsRequest(sourceIndex, docBuilder); mtvRequest.add(tvRequest2); - MultiTermVectorsResponse mtvResponse = - execute(mtvRequest, highLevelClient()::mtermvectors, highLevelClient()::mtermvectorsAsync); - for (TermVectorsResponse tvResponse: mtvResponse.getTermVectorsResponses()) { + MultiTermVectorsResponse mtvResponse = execute( + mtvRequest, + highLevelClient()::mtermvectors, + highLevelClient()::mtermvectorsAsync + ); + for (TermVectorsResponse tvResponse : mtvResponse.getTermVectorsResponses()) { assertThat(tvResponse.getIndex(), equalTo(sourceIndex)); assertTrue(tvResponse.getFound()); } @@ -1304,8 +1388,11 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { tvRequest3.setFields("field", "field2"); mtvRequest.add(tvRequest3); - MultiTermVectorsResponse mtvResponse = - execute(mtvRequest, highLevelClient()::mtermvectors, highLevelClient()::mtermvectorsAsync); + MultiTermVectorsResponse mtvResponse = execute( + mtvRequest, + highLevelClient()::mtermvectors, + highLevelClient()::mtermvectorsAsync + ); final List expectedFields = new ArrayList<>(); expectedFields.add("field"); expectedFields.add("field2"); @@ -1322,7 +1409,8 @@ public class CrudIT extends OpenSearchRestHighLevelClientTestCase { assertEquals(expectedRespFields.get(i).size(), tvResponse.getTermVectorsList().size()); assertEquals( expectedRespFields.get(i), - tvResponse.getTermVectorsList().stream().map(tv -> tv.getFieldName()).collect(Collectors.toList())); + tvResponse.getTermVectorsList().stream().map(tv -> tv.getFieldName()).collect(Collectors.toList()) + ); } } } diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/CustomRestHighLevelClientTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/CustomRestHighLevelClientTests.java index a70ea7a6ef0..256549f7891 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/CustomRestHighLevelClientTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/CustomRestHighLevelClientTests.java @@ -43,11 +43,6 @@ import org.apache.http.message.BasicStatusLine; import org.apache.http.nio.entity.NByteArrayEntity; import org.apache.lucene.util.BytesRef; import org.opensearch.Build; -import org.opensearch.client.Request; -import org.opensearch.client.RequestOptions; -import org.opensearch.client.Response; -import org.opensearch.client.ResponseListener; -import org.opensearch.client.RestClient; import org.opensearch.Version; import org.opensearch.action.ActionListener; import org.opensearch.action.main.MainRequest; @@ -92,15 +87,11 @@ public class CustomRestHighLevelClientTests extends OpenSearchTestCase { final RestClient restClient = mock(RestClient.class); restHighLevelClient = new CustomRestClient(restClient); - doAnswer(inv -> mockPerformRequest((Request) inv.getArguments()[0])) - .when(restClient) - .performRequest(any(Request.class)); + doAnswer(inv -> mockPerformRequest((Request) inv.getArguments()[0])).when(restClient).performRequest(any(Request.class)); - doAnswer(inv -> mockPerformRequestAsync( - ((Request) inv.getArguments()[0]), - (ResponseListener) inv.getArguments()[1])) - .when(restClient) - .performRequestAsync(any(Request.class), any(ResponseListener.class)); + doAnswer(inv -> mockPerformRequestAsync(((Request) inv.getArguments()[0]), (ResponseListener) inv.getArguments()[1])).when( + restClient + ).performRequestAsync(any(Request.class), any(ResponseListener.class)); } } @@ -140,21 +131,21 @@ public class CustomRestHighLevelClientTests extends OpenSearchTestCase { */ @SuppressForbidden(reason = "We're forced to uses Class#getDeclaredMethods() here because this test checks protected methods") public void testMethodsVisibility() { - final String[] methodNames = new String[]{"convertExistsResponse", - "parseEntity", - "parseResponseException", - "performRequest", - "performRequestAndParseEntity", - "performRequestAndParseOptionalEntity", - "performRequestAsync", - "performRequestAsyncAndParseEntity", - "performRequestAsyncAndParseOptionalEntity" - }; + final String[] methodNames = new String[] { + "convertExistsResponse", + "parseEntity", + "parseResponseException", + "performRequest", + "performRequestAndParseEntity", + "performRequestAndParseOptionalEntity", + "performRequestAsync", + "performRequestAsyncAndParseEntity", + "performRequestAsyncAndParseOptionalEntity" }; - final Set protectedMethods = Arrays.stream(RestHighLevelClient.class.getDeclaredMethods()) - .filter(method -> Modifier.isProtected(method.getModifiers())) - .map(Method::getName) - .collect(Collectors.toCollection(TreeSet::new)); + final Set protectedMethods = Arrays.stream(RestHighLevelClient.class.getDeclaredMethods()) + .filter(method -> Modifier.isProtected(method.getModifiers())) + .map(Method::getName) + .collect(Collectors.toCollection(TreeSet::new)); assertThat(protectedMethods, contains(methodNames)); } diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/GetAliasesResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/GetAliasesResponseTests.java index 89f6eec4868..67b1c0bc3b9 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/GetAliasesResponseTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/GetAliasesResponseTests.java @@ -97,8 +97,8 @@ public class GetAliasesResponseTests extends AbstractXContentTestCase getRandomFieldsExcludeFilter() { return p -> p.equals("") // do not add elements at the top-level as any element at this level is parsed as a new index - || p.endsWith(".aliases") // do not add new alias - || p.contains(".filter"); // do not insert random data into AliasMetadata#filter + || p.endsWith(".aliases") // do not add new alias + || p.contains(".filter"); // do not insert random data into AliasMetadata#filter } @Override @@ -116,44 +116,41 @@ public class GetAliasesResponseTests extends AbstractXContentTestCase getIndexResponse = getAsMap(indexName); assertEquals("2", XContentMapValues.extractValue(indexName + ".settings.index.number_of_replicas", getIndexResponse)); - Map aliasData = - (Map)XContentMapValues.extractValue(indexName + ".aliases.alias_name", getIndexResponse); + Map aliasData = (Map) XContentMapValues.extractValue( + indexName + ".aliases.alias_name", + getIndexResponse + ); assertNotNull(aliasData); assertEquals("1", aliasData.get("index_routing")); Map filter = (Map) aliasData.get("filter"); @@ -284,7 +279,7 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { } } - @SuppressWarnings({"unchecked", "rawtypes"}) + @SuppressWarnings({ "unchecked", "rawtypes" }) public void testCreateIndexWithTypes() throws IOException { { // Create index @@ -298,7 +293,8 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { createIndexRequest, highLevelClient().indices()::create, highLevelClient().indices()::createAsync, - expectWarnings(RestCreateIndexAction.TYPES_DEPRECATION_MESSAGE)); + expectWarnings(RestCreateIndexAction.TYPES_DEPRECATION_MESSAGE) + ); assertTrue(createIndexResponse.isAcknowledged()); assertTrue(indexExists(indexName)); @@ -330,14 +326,17 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { createIndexRequest, highLevelClient().indices()::create, highLevelClient().indices()::createAsync, - expectWarnings(RestCreateIndexAction.TYPES_DEPRECATION_MESSAGE)); + expectWarnings(RestCreateIndexAction.TYPES_DEPRECATION_MESSAGE) + ); assertTrue(createIndexResponse.isAcknowledged()); Map getIndexResponse = getAsMap(indexName); assertEquals("2", XContentMapValues.extractValue(indexName + ".settings.index.number_of_replicas", getIndexResponse)); - Map aliasData = - (Map)XContentMapValues.extractValue(indexName + ".aliases.alias_name", getIndexResponse); + Map aliasData = (Map) XContentMapValues.extractValue( + indexName + ".aliases.alias_name", + getIndexResponse + ); assertNotNull(aliasData); assertEquals("1", aliasData.get("index_routing")); Map filter = (Map) aliasData.get("filter"); @@ -350,23 +349,26 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { public void testGetSettings() throws IOException { String indexName = "get_settings_index"; - Settings basicSettings = Settings.builder() - .put("number_of_shards", 1) - .put("number_of_replicas", 0) - .build(); + Settings basicSettings = Settings.builder().put("number_of_shards", 1).put("number_of_replicas", 0).build(); createIndex(indexName, basicSettings); GetSettingsRequest getSettingsRequest = new GetSettingsRequest().indices(indexName); - GetSettingsResponse getSettingsResponse = execute(getSettingsRequest, highLevelClient().indices()::getSettings, - highLevelClient().indices()::getSettingsAsync); + GetSettingsResponse getSettingsResponse = execute( + getSettingsRequest, + highLevelClient().indices()::getSettings, + highLevelClient().indices()::getSettingsAsync + ); assertNull(getSettingsResponse.getSetting(indexName, "index.refresh_interval")); assertEquals("1", getSettingsResponse.getSetting(indexName, "index.number_of_shards")); updateIndexSettings(indexName, Settings.builder().put("refresh_interval", "30s")); - GetSettingsResponse updatedResponse = execute(getSettingsRequest, highLevelClient().indices()::getSettings, - highLevelClient().indices()::getSettingsAsync); + GetSettingsResponse updatedResponse = execute( + getSettingsRequest, + highLevelClient().indices()::getSettings, + highLevelClient().indices()::getSettingsAsync + ); assertEquals("30s", updatedResponse.getSetting(indexName, "index.refresh_interval")); } @@ -375,8 +377,10 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { assertFalse(indexExists(nonExistentIndex)); GetSettingsRequest getSettingsRequest = new GetSettingsRequest().indices(nonExistentIndex); - OpenSearchException exception = expectThrows(OpenSearchException.class, - () -> execute(getSettingsRequest, highLevelClient().indices()::getSettings, highLevelClient().indices()::getSettingsAsync)); + OpenSearchException exception = expectThrows( + OpenSearchException.class, + () -> execute(getSettingsRequest, highLevelClient().indices()::getSettings, highLevelClient().indices()::getSettingsAsync) + ); assertEquals(RestStatus.NOT_FOUND, exception.status()); } @@ -388,8 +392,11 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { createIndex(indexName2, Settings.builder().put("number_of_shards", 3).build()); GetSettingsRequest getSettingsRequest = new GetSettingsRequest().indices("get_multiple_settings*"); - GetSettingsResponse getSettingsResponse = execute(getSettingsRequest, highLevelClient().indices()::getSettings, - highLevelClient().indices()::getSettingsAsync); + GetSettingsResponse getSettingsResponse = execute( + getSettingsRequest, + highLevelClient().indices()::getSettings, + highLevelClient().indices()::getSettingsAsync + ); assertEquals("2", getSettingsResponse.getSetting(indexName1, "index.number_of_shards")); assertEquals("3", getSettingsResponse.getSetting(indexName2, "index.number_of_shards")); @@ -397,15 +404,15 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { public void testGetSettingsFiltered() throws IOException { String indexName = "get_settings_index"; - Settings basicSettings = Settings.builder() - .put("number_of_shards", 1) - .put("number_of_replicas", 0) - .build(); + Settings basicSettings = Settings.builder().put("number_of_shards", 1).put("number_of_replicas", 0).build(); createIndex(indexName, basicSettings); GetSettingsRequest getSettingsRequest = new GetSettingsRequest().indices(indexName).names("index.number_of_shards"); - GetSettingsResponse getSettingsResponse = execute(getSettingsRequest, highLevelClient().indices()::getSettings, - highLevelClient().indices()::getSettingsAsync); + GetSettingsResponse getSettingsResponse = execute( + getSettingsRequest, + highLevelClient().indices()::getSettings, + highLevelClient().indices()::getSettingsAsync + ); assertNull(getSettingsResponse.getSetting(indexName, "index.number_of_replicas")); assertEquals("1", getSettingsResponse.getSetting(indexName, "index.number_of_shards")); @@ -414,36 +421,37 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { public void testGetSettingsWithDefaults() throws IOException { String indexName = "get_settings_index"; - Settings basicSettings = Settings.builder() - .put("number_of_shards", 1) - .put("number_of_replicas", 0) - .build(); + Settings basicSettings = Settings.builder().put("number_of_shards", 1).put("number_of_replicas", 0).build(); createIndex(indexName, basicSettings); GetSettingsRequest getSettingsRequest = new GetSettingsRequest().indices(indexName).includeDefaults(true); - GetSettingsResponse getSettingsResponse = execute(getSettingsRequest, highLevelClient().indices()::getSettings, - highLevelClient().indices()::getSettingsAsync); + GetSettingsResponse getSettingsResponse = execute( + getSettingsRequest, + highLevelClient().indices()::getSettings, + highLevelClient().indices()::getSettingsAsync + ); assertNotNull(getSettingsResponse.getSetting(indexName, "index.refresh_interval")); - assertEquals(IndexSettings.DEFAULT_REFRESH_INTERVAL, - getSettingsResponse.getIndexToDefaultSettings().get("get_settings_index").getAsTime("index.refresh_interval", null)); + assertEquals( + IndexSettings.DEFAULT_REFRESH_INTERVAL, + getSettingsResponse.getIndexToDefaultSettings().get("get_settings_index").getAsTime("index.refresh_interval", null) + ); assertEquals("1", getSettingsResponse.getSetting(indexName, "index.number_of_shards")); } public void testGetSettingsWithDefaultsFiltered() throws IOException { String indexName = "get_settings_index"; - Settings basicSettings = Settings.builder() - .put("number_of_shards", 1) - .put("number_of_replicas", 0) - .build(); + Settings basicSettings = Settings.builder().put("number_of_shards", 1).put("number_of_replicas", 0).build(); createIndex(indexName, basicSettings); - GetSettingsRequest getSettingsRequest = new GetSettingsRequest() - .indices(indexName) + GetSettingsRequest getSettingsRequest = new GetSettingsRequest().indices(indexName) .names("index.refresh_interval") .includeDefaults(true); - GetSettingsResponse getSettingsResponse = execute(getSettingsRequest, highLevelClient().indices()::getSettings, - highLevelClient().indices()::getSettingsAsync); + GetSettingsResponse getSettingsResponse = execute( + getSettingsRequest, + highLevelClient().indices()::getSettings, + highLevelClient().indices()::getSettingsAsync + ); assertNull(getSettingsResponse.getSetting(indexName, "index.number_of_replicas")); assertNull(getSettingsResponse.getSetting(indexName, "index.number_of_shards")); @@ -454,16 +462,16 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { @SuppressWarnings("unchecked") public void testGetIndex() throws IOException { String indexName = "get_index_test"; - Settings basicSettings = Settings.builder() - .put(SETTING_NUMBER_OF_SHARDS, 1) - .put(SETTING_NUMBER_OF_REPLICAS, 0) - .build(); + Settings basicSettings = Settings.builder().put(SETTING_NUMBER_OF_SHARDS, 1).put(SETTING_NUMBER_OF_REPLICAS, 0).build(); String mappings = "\"properties\":{\"field-1\":{\"type\":\"integer\"}}"; createIndex(indexName, basicSettings, mappings); GetIndexRequest getIndexRequest = new GetIndexRequest(indexName).includeDefaults(false); - GetIndexResponse getIndexResponse = - execute(getIndexRequest, highLevelClient().indices()::get, highLevelClient().indices()::getAsync); + GetIndexResponse getIndexResponse = execute( + getIndexRequest, + highLevelClient().indices()::get, + highLevelClient().indices()::getAsync + ); // default settings should be null assertNull(getIndexResponse.getSetting(indexName, "index.refresh_interval")); @@ -477,9 +485,9 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { assertEquals("{\"properties\":{\"field-1\":{\"type\":\"integer\"}}}", mappingMetadata.source().string()); Object o = mappingMetadata.getSourceAsMap().get("properties"); assertThat(o, instanceOf(Map.class)); - //noinspection unchecked + // noinspection unchecked assertThat(((Map) o).get("field-1"), instanceOf(Map.class)); - //noinspection unchecked + // noinspection unchecked Map fieldMapping = (Map) ((Map) o).get("field-1"); assertEquals("integer", fieldMapping.get("type")); } @@ -487,18 +495,18 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { @SuppressWarnings("unchecked") public void testGetIndexWithTypes() throws IOException { String indexName = "get_index_test"; - Settings basicSettings = Settings.builder() - .put(SETTING_NUMBER_OF_SHARDS, 1) - .put(SETTING_NUMBER_OF_REPLICAS, 0) - .build(); + Settings basicSettings = Settings.builder().put(SETTING_NUMBER_OF_SHARDS, 1).put(SETTING_NUMBER_OF_REPLICAS, 0).build(); String mappings = "\"properties\":{\"field-1\":{\"type\":\"integer\"}}"; createIndex(indexName, basicSettings, mappings); org.opensearch.action.admin.indices.get.GetIndexRequest getIndexRequest = - new org.opensearch.action.admin.indices.get.GetIndexRequest().indices(indexName).includeDefaults(false); - org.opensearch.action.admin.indices.get.GetIndexResponse getIndexResponse = execute(getIndexRequest, - highLevelClient().indices()::get, highLevelClient().indices()::getAsync, - expectWarnings(RestGetIndicesAction.TYPES_DEPRECATION_MESSAGE)); + new org.opensearch.action.admin.indices.get.GetIndexRequest().indices(indexName).includeDefaults(false); + org.opensearch.action.admin.indices.get.GetIndexResponse getIndexResponse = execute( + getIndexRequest, + highLevelClient().indices()::get, + highLevelClient().indices()::getAsync, + expectWarnings(RestGetIndicesAction.TYPES_DEPRECATION_MESSAGE) + ); // default settings should be null assertNull(getIndexResponse.getSetting(indexName, "index.refresh_interval")); @@ -514,20 +522,22 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { @SuppressWarnings("unchecked") public void testGetIndexWithDefaults() throws IOException { String indexName = "get_index_test"; - Settings basicSettings = Settings.builder() - .put(SETTING_NUMBER_OF_SHARDS, 1) - .put(SETTING_NUMBER_OF_REPLICAS, 0) - .build(); + Settings basicSettings = Settings.builder().put(SETTING_NUMBER_OF_SHARDS, 1).put(SETTING_NUMBER_OF_REPLICAS, 0).build(); String mappings = "\"properties\":{\"field-1\":{\"type\":\"integer\"}}"; createIndex(indexName, basicSettings, mappings); GetIndexRequest getIndexRequest = new GetIndexRequest(indexName).includeDefaults(true); - GetIndexResponse getIndexResponse = - execute(getIndexRequest, highLevelClient().indices()::get, highLevelClient().indices()::getAsync); + GetIndexResponse getIndexResponse = execute( + getIndexRequest, + highLevelClient().indices()::get, + highLevelClient().indices()::getAsync + ); assertNotNull(getIndexResponse.getSetting(indexName, "index.refresh_interval")); - assertEquals(IndexSettings.DEFAULT_REFRESH_INTERVAL, - getIndexResponse.getDefaultSettings().get(indexName).getAsTime("index.refresh_interval", null)); + assertEquals( + IndexSettings.DEFAULT_REFRESH_INTERVAL, + getIndexResponse.getDefaultSettings().get(indexName).getAsTime("index.refresh_interval", null) + ); assertEquals("1", getIndexResponse.getSetting(indexName, SETTING_NUMBER_OF_SHARDS)); assertEquals("0", getIndexResponse.getSetting(indexName, SETTING_NUMBER_OF_REPLICAS)); assertNotNull(getIndexResponse.getMappings().get(indexName)); @@ -544,8 +554,10 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { assertFalse(indexExists(nonExistentIndex)); GetIndexRequest getIndexRequest = new GetIndexRequest(nonExistentIndex); - OpenSearchException exception = expectThrows(OpenSearchException.class, - () -> execute(getIndexRequest, highLevelClient().indices()::get, highLevelClient().indices()::getAsync)); + OpenSearchException exception = expectThrows( + OpenSearchException.class, + () -> execute(getIndexRequest, highLevelClient().indices()::get, highLevelClient().indices()::getAsync) + ); assertEquals(RestStatus.NOT_FOUND, exception.status()); } @@ -560,14 +572,15 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { mappingBuilder.endObject().endObject().endObject(); putMappingRequest.source(mappingBuilder); - AcknowledgedResponse putMappingResponse = execute(putMappingRequest, + AcknowledgedResponse putMappingResponse = execute( + putMappingRequest, highLevelClient().indices()::putMapping, - highLevelClient().indices()::putMappingAsync); + highLevelClient().indices()::putMappingAsync + ); assertTrue(putMappingResponse.isAcknowledged()); Map getIndexResponse = getAsMap(indexName); - assertEquals("text", XContentMapValues.extractValue(indexName + ".mappings.properties.field.type", - getIndexResponse)); + assertEquals("text", XContentMapValues.extractValue(indexName + ".mappings.properties.field.type", getIndexResponse)); } public void testPutMappingWithTypes() throws IOException { @@ -584,15 +597,16 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { mappingBuilder.endObject().endObject().endObject(); putMappingRequest.source(mappingBuilder); - AcknowledgedResponse putMappingResponse = execute(putMappingRequest, + AcknowledgedResponse putMappingResponse = execute( + putMappingRequest, highLevelClient().indices()::putMapping, highLevelClient().indices()::putMappingAsync, - expectWarnings(RestPutMappingAction.TYPES_DEPRECATION_MESSAGE)); + expectWarnings(RestPutMappingAction.TYPES_DEPRECATION_MESSAGE) + ); assertTrue(putMappingResponse.isAcknowledged()); Map getIndexResponse = getAsMap(indexName); - assertEquals("text", XContentMapValues.extractValue(indexName + ".mappings.properties.field.type", - getIndexResponse)); + assertEquals("text", XContentMapValues.extractValue(indexName + ".mappings.properties.field.type", getIndexResponse)); } public void testGetMapping() throws IOException { @@ -606,9 +620,11 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { mappingBuilder.endObject().endObject().endObject(); putMappingRequest.source(mappingBuilder); - AcknowledgedResponse putMappingResponse = execute(putMappingRequest, + AcknowledgedResponse putMappingResponse = execute( + putMappingRequest, highLevelClient().indices()::putMapping, - highLevelClient().indices()::putMappingAsync); + highLevelClient().indices()::putMappingAsync + ); assertTrue(putMappingResponse.isAcknowledged()); Map getIndexResponse = getAsMap(indexName); @@ -619,7 +635,8 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { GetMappingsResponse getMappingsResponse = execute( request, highLevelClient().indices()::getMapping, - highLevelClient().indices()::getMappingAsync); + highLevelClient().indices()::getMappingAsync + ); Map mappings = getMappingsResponse.mappings().get(indexName).sourceAsMap(); Map type = new HashMap<>(); @@ -642,9 +659,11 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { mappingBuilder.endObject().endObject().endObject(); putMappingRequest.source(mappingBuilder); - AcknowledgedResponse putMappingResponse = execute(putMappingRequest, + AcknowledgedResponse putMappingResponse = execute( + putMappingRequest, highLevelClient().indices()::putMapping, - highLevelClient().indices()::putMappingAsync); + highLevelClient().indices()::putMappingAsync + ); assertTrue(putMappingResponse.isAcknowledged()); Map getIndexResponse = getAsMap(indexName); @@ -657,7 +676,8 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { request, highLevelClient().indices()::getMapping, highLevelClient().indices()::getMappingAsync, - expectWarnings(RestGetMappingAction.TYPES_DEPRECATION_MESSAGE)); + expectWarnings(RestGetMappingAction.TYPES_DEPRECATION_MESSAGE) + ); Map mappings = getMappingsResponse.getMappings().get(indexName).get("_doc").sourceAsMap(); Map type = new HashMap<>(); @@ -680,25 +700,28 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { mappingBuilder.endObject().endObject().endObject(); putMappingRequest.source(mappingBuilder); - AcknowledgedResponse putMappingResponse = - execute(putMappingRequest, highLevelClient().indices()::putMapping, highLevelClient().indices()::putMappingAsync); + AcknowledgedResponse putMappingResponse = execute( + putMappingRequest, + highLevelClient().indices()::putMapping, + highLevelClient().indices()::putMappingAsync + ); assertTrue(putMappingResponse.isAcknowledged()); - GetFieldMappingsRequest getFieldMappingsRequest = new GetFieldMappingsRequest() - .indices(indexName) - .fields("field"); + GetFieldMappingsRequest getFieldMappingsRequest = new GetFieldMappingsRequest().indices(indexName).fields("field"); - GetFieldMappingsResponse getFieldMappingsResponse = - execute(getFieldMappingsRequest, - highLevelClient().indices()::getFieldMapping, - highLevelClient().indices()::getFieldMappingAsync); + GetFieldMappingsResponse getFieldMappingsResponse = execute( + getFieldMappingsRequest, + highLevelClient().indices()::getFieldMapping, + highLevelClient().indices()::getFieldMappingAsync + ); - final Map fieldMappingMap = - getFieldMappingsResponse.mappings().get(indexName); + final Map fieldMappingMap = getFieldMappingsResponse.mappings() + .get(indexName); - final GetFieldMappingsResponse.FieldMappingMetadata metadata = - new GetFieldMappingsResponse.FieldMappingMetadata("field", - new BytesArray("{\"field\":{\"type\":\"text\"}}")); + final GetFieldMappingsResponse.FieldMappingMetadata metadata = new GetFieldMappingsResponse.FieldMappingMetadata( + "field", + new BytesArray("{\"field\":{\"type\":\"text\"}}") + ); assertThat(fieldMappingMap, equalTo(Collections.singletonMap("field", metadata))); } @@ -713,28 +736,31 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { mappingBuilder.endObject().endObject().endObject(); putMappingRequest.source(mappingBuilder); - AcknowledgedResponse putMappingResponse = - execute(putMappingRequest, highLevelClient().indices()::putMapping, highLevelClient().indices()::putMappingAsync); + AcknowledgedResponse putMappingResponse = execute( + putMappingRequest, + highLevelClient().indices()::putMapping, + highLevelClient().indices()::putMappingAsync + ); assertTrue(putMappingResponse.isAcknowledged()); org.opensearch.action.admin.indices.mapping.get.GetFieldMappingsRequest getFieldMappingsRequest = - new org.opensearch.action.admin.indices.mapping.get.GetFieldMappingsRequest() - .indices(indexName) - .types("_doc") - .fields("field"); + new org.opensearch.action.admin.indices.mapping.get.GetFieldMappingsRequest().indices(indexName).types("_doc").fields("field"); - org.opensearch.action.admin.indices.mapping.get.GetFieldMappingsResponse getFieldMappingsResponse = - execute(getFieldMappingsRequest, - highLevelClient().indices()::getFieldMapping, - highLevelClient().indices()::getFieldMappingAsync, - expectWarnings(RestGetFieldMappingAction.TYPES_DEPRECATION_MESSAGE)); + org.opensearch.action.admin.indices.mapping.get.GetFieldMappingsResponse getFieldMappingsResponse = execute( + getFieldMappingsRequest, + highLevelClient().indices()::getFieldMapping, + highLevelClient().indices()::getFieldMappingAsync, + expectWarnings(RestGetFieldMappingAction.TYPES_DEPRECATION_MESSAGE) + ); - final Map - fieldMappingMap = getFieldMappingsResponse.mappings().get(indexName).get("_doc"); + final Map fieldMappingMap = + getFieldMappingsResponse.mappings().get(indexName).get("_doc"); - final org.opensearch.action.admin.indices.mapping.get.GetFieldMappingsResponse.FieldMappingMetadata metadata = - new org.opensearch.action.admin.indices.mapping.get.GetFieldMappingsResponse.FieldMappingMetadata("field", - new BytesArray("{\"field\":{\"type\":\"text\"}}")); + final org.opensearch.action.admin.indices.mapping.get.GetFieldMappingsResponse.FieldMappingMetadata metadata = + new org.opensearch.action.admin.indices.mapping.get.GetFieldMappingsResponse.FieldMappingMetadata( + "field", + new BytesArray("{\"field\":{\"type\":\"text\"}}") + ); assertThat(fieldMappingMap, equalTo(Collections.singletonMap("field", metadata))); } @@ -745,8 +771,11 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { createIndex(indexName, Settings.EMPTY); DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(indexName); - AcknowledgedResponse deleteIndexResponse = - execute(deleteIndexRequest, highLevelClient().indices()::delete, highLevelClient().indices()::deleteAsync); + AcknowledgedResponse deleteIndexResponse = execute( + deleteIndexRequest, + highLevelClient().indices()::delete, + highLevelClient().indices()::deleteAsync + ); assertTrue(deleteIndexResponse.isAcknowledged()); assertFalse(indexExists(indexName)); @@ -758,8 +787,10 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(nonExistentIndex); - OpenSearchException exception = expectThrows(OpenSearchException.class, - () -> execute(deleteIndexRequest, highLevelClient().indices()::delete, highLevelClient().indices()::deleteAsync)); + OpenSearchException exception = expectThrows( + OpenSearchException.class, + () -> execute(deleteIndexRequest, highLevelClient().indices()::delete, highLevelClient().indices()::deleteAsync) + ); assertEquals(RestStatus.NOT_FOUND, exception.status()); } } @@ -780,8 +811,11 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { } addAction.routing("routing").searchRouting("search_routing").filter("{\"term\":{\"year\":2016}}"); aliasesAddRequest.addAliasAction(addAction); - AcknowledgedResponse aliasesAddResponse = execute(aliasesAddRequest, highLevelClient().indices()::updateAliases, - highLevelClient().indices()::updateAliasesAsync); + AcknowledgedResponse aliasesAddResponse = execute( + aliasesAddRequest, + highLevelClient().indices()::updateAliases, + highLevelClient().indices()::updateAliasesAsync + ); assertTrue(aliasesAddResponse.isAcknowledged()); assertThat(aliasExists(alias), equalTo(true)); assertThat(aliasExists(index, alias), equalTo(true)); @@ -800,8 +834,11 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { aliasesAddRemoveRequest.addAliasAction(addAction); AliasActions removeAction = new AliasActions(AliasActions.Type.REMOVE).index(index).alias(alias); aliasesAddRemoveRequest.addAliasAction(removeAction); - AcknowledgedResponse aliasesAddRemoveResponse = execute(aliasesAddRemoveRequest, highLevelClient().indices()::updateAliases, - highLevelClient().indices()::updateAliasesAsync); + AcknowledgedResponse aliasesAddRemoveResponse = execute( + aliasesAddRemoveRequest, + highLevelClient().indices()::updateAliases, + highLevelClient().indices()::updateAliasesAsync + ); assertTrue(aliasesAddRemoveResponse.isAcknowledged()); assertThat(aliasExists(alias), equalTo(false)); assertThat(aliasExists(alias2), equalTo(true)); @@ -811,8 +848,11 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { IndicesAliasesRequest aliasesRemoveIndexRequest = new IndicesAliasesRequest(); AliasActions removeIndexAction = new AliasActions(AliasActions.Type.REMOVE_INDEX).index(index); aliasesRemoveIndexRequest.addAliasAction(removeIndexAction); - AcknowledgedResponse aliasesRemoveIndexResponse = execute(aliasesRemoveIndexRequest, highLevelClient().indices()::updateAliases, - highLevelClient().indices()::updateAliasesAsync); + AcknowledgedResponse aliasesRemoveIndexResponse = execute( + aliasesRemoveIndexRequest, + highLevelClient().indices()::updateAliases, + highLevelClient().indices()::updateAliasesAsync + ); assertTrue(aliasesRemoveIndexResponse.isAcknowledged()); assertThat(aliasExists(alias), equalTo(false)); assertThat(aliasExists(alias2), equalTo(false)); @@ -828,22 +868,34 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { IndicesAliasesRequest nonExistentIndexRequest = new IndicesAliasesRequest(); nonExistentIndexRequest.addAliasAction(new AliasActions(AliasActions.Type.ADD).index(nonExistentIndex).alias(alias)); - OpenSearchException exception = expectThrows(OpenSearchException.class, () -> execute(nonExistentIndexRequest, - highLevelClient().indices()::updateAliases, highLevelClient().indices()::updateAliasesAsync)); + OpenSearchException exception = expectThrows( + OpenSearchException.class, + () -> execute( + nonExistentIndexRequest, + highLevelClient().indices()::updateAliases, + highLevelClient().indices()::updateAliasesAsync + ) + ); assertThat(exception.status(), equalTo(RestStatus.NOT_FOUND)); - assertThat(exception.getMessage(), - equalTo("OpenSearch exception [type=index_not_found_exception, reason=no such index [non_existent_index]]")); + assertThat( + exception.getMessage(), + equalTo("OpenSearch exception [type=index_not_found_exception, reason=no such index [non_existent_index]]") + ); assertThat(exception.getMetadata("opensearch.index"), hasItem(nonExistentIndex)); createIndex(index, Settings.EMPTY); IndicesAliasesRequest mixedRequest = new IndicesAliasesRequest(); mixedRequest.addAliasAction(new AliasActions(AliasActions.Type.ADD).indices(index).aliases(alias)); mixedRequest.addAliasAction(new AliasActions(AliasActions.Type.REMOVE).indices(nonExistentIndex).alias(alias)); - exception = expectThrows(OpenSearchStatusException.class, - () -> execute(mixedRequest, highLevelClient().indices()::updateAliases, highLevelClient().indices()::updateAliasesAsync)); + exception = expectThrows( + OpenSearchStatusException.class, + () -> execute(mixedRequest, highLevelClient().indices()::updateAliases, highLevelClient().indices()::updateAliasesAsync) + ); assertThat(exception.status(), equalTo(RestStatus.NOT_FOUND)); - assertThat(exception.getMessage(), - equalTo("OpenSearch exception [type=index_not_found_exception, reason=no such index [non_existent_index]]")); + assertThat( + exception.getMessage(), + equalTo("OpenSearch exception [type=index_not_found_exception, reason=no such index [non_existent_index]]") + ); assertThat(exception.getMetadata("opensearch.index"), hasItem(nonExistentIndex)); assertThat(exception.getMetadata("opensearch.index"), not(hasItem(index))); assertThat(aliasExists(index, alias), equalTo(false)); @@ -852,11 +904,15 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { IndicesAliasesRequest removeIndexRequest = new IndicesAliasesRequest(); removeIndexRequest.addAliasAction(new AliasActions(AliasActions.Type.ADD).index(nonExistentIndex).alias(alias)); removeIndexRequest.addAliasAction(new AliasActions(AliasActions.Type.REMOVE_INDEX).indices(nonExistentIndex)); - exception = expectThrows(OpenSearchException.class, () -> execute(removeIndexRequest, highLevelClient().indices()::updateAliases, - highLevelClient().indices()::updateAliasesAsync)); + exception = expectThrows( + OpenSearchException.class, + () -> execute(removeIndexRequest, highLevelClient().indices()::updateAliases, highLevelClient().indices()::updateAliasesAsync) + ); assertThat(exception.status(), equalTo(RestStatus.NOT_FOUND)); - assertThat(exception.getMessage(), - equalTo("OpenSearch exception [type=index_not_found_exception, reason=no such index [non_existent_index]]")); + assertThat( + exception.getMessage(), + equalTo("OpenSearch exception [type=index_not_found_exception, reason=no such index [non_existent_index]]") + ); assertThat(exception.getMetadata("opensearch.index"), hasItem(nonExistentIndex)); assertThat(exception.getMetadata("opensearch.index"), not(hasItem(index))); assertThat(aliasExists(index, alias), equalTo(false)); @@ -867,14 +923,19 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { String index = "index"; createIndex(index, Settings.EMPTY); closeIndex(index); - ResponseException exception = expectThrows(ResponseException.class, - () -> client().performRequest(new Request(HttpGet.METHOD_NAME, index + "/_search"))); + ResponseException exception = expectThrows( + ResponseException.class, + () -> client().performRequest(new Request(HttpGet.METHOD_NAME, index + "/_search")) + ); assertThat(exception.getResponse().getStatusLine().getStatusCode(), equalTo(RestStatus.BAD_REQUEST.getStatus())); assertThat(exception.getMessage().contains(index), equalTo(true)); OpenIndexRequest openIndexRequest = new OpenIndexRequest(index); - OpenIndexResponse openIndexResponse = execute(openIndexRequest, highLevelClient().indices()::open, - highLevelClient().indices()::openAsync); + OpenIndexResponse openIndexResponse = execute( + openIndexRequest, + highLevelClient().indices()::open, + highLevelClient().indices()::openAsync + ); assertTrue(openIndexResponse.isAcknowledged()); Response response = client().performRequest(new Request(HttpGet.METHOD_NAME, index + "/_search")); @@ -886,20 +947,27 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { assertFalse(indexExists(nonExistentIndex)); OpenIndexRequest openIndexRequest = new OpenIndexRequest(nonExistentIndex); - OpenSearchException exception = expectThrows(OpenSearchException.class, - () -> execute(openIndexRequest, highLevelClient().indices()::open, highLevelClient().indices()::openAsync)); + OpenSearchException exception = expectThrows( + OpenSearchException.class, + () -> execute(openIndexRequest, highLevelClient().indices()::open, highLevelClient().indices()::openAsync) + ); assertEquals(RestStatus.NOT_FOUND, exception.status()); OpenIndexRequest lenientOpenIndexRequest = new OpenIndexRequest(nonExistentIndex); lenientOpenIndexRequest.indicesOptions(IndicesOptions.lenientExpandOpen()); - OpenIndexResponse lenientOpenIndexResponse = execute(lenientOpenIndexRequest, highLevelClient().indices()::open, - highLevelClient().indices()::openAsync); + OpenIndexResponse lenientOpenIndexResponse = execute( + lenientOpenIndexRequest, + highLevelClient().indices()::open, + highLevelClient().indices()::openAsync + ); assertThat(lenientOpenIndexResponse.isAcknowledged(), equalTo(true)); OpenIndexRequest strictOpenIndexRequest = new OpenIndexRequest(nonExistentIndex); strictOpenIndexRequest.indicesOptions(IndicesOptions.strictExpandOpen()); - OpenSearchException strictException = expectThrows(OpenSearchException.class, - () -> execute(openIndexRequest, highLevelClient().indices()::open, highLevelClient().indices()::openAsync)); + OpenSearchException strictException = expectThrows( + OpenSearchException.class, + () -> execute(openIndexRequest, highLevelClient().indices()::open, highLevelClient().indices()::openAsync) + ); assertEquals(RestStatus.NOT_FOUND, strictException.status()); } @@ -912,8 +980,11 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { } CloseIndexRequest closeIndexRequest = new CloseIndexRequest(indices); - CloseIndexResponse closeIndexResponse = execute(closeIndexRequest, - highLevelClient().indices()::close, highLevelClient().indices()::closeAsync); + CloseIndexResponse closeIndexResponse = execute( + closeIndexRequest, + highLevelClient().indices()::close, + highLevelClient().indices()::closeAsync + ); assertTrue(closeIndexResponse.isAcknowledged()); assertTrue(closeIndexResponse.isShardsAcknowledged()); assertThat(closeIndexResponse.getIndices(), notNullValue()); @@ -922,8 +993,10 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { assertThat(indexResult.getIndex(), startsWith("index-")); assertThat(indexResult.hasFailures(), is(false)); - ResponseException exception = expectThrows(ResponseException.class, - () -> client().performRequest(new Request(HttpGet.METHOD_NAME, indexResult.getIndex() + "/_search"))); + ResponseException exception = expectThrows( + ResponseException.class, + () -> client().performRequest(new Request(HttpGet.METHOD_NAME, indexResult.getIndex() + "/_search")) + ); assertThat(exception.getResponse().getStatusLine().getStatusCode(), equalTo(RestStatus.BAD_REQUEST.getStatus())); assertThat(exception.getMessage().contains(indexResult.getIndex()), equalTo(true)); }); @@ -934,30 +1007,34 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { assertFalse(indexExists(nonExistentIndex)); CloseIndexRequest closeIndexRequest = new CloseIndexRequest(nonExistentIndex); - OpenSearchException exception = expectThrows(OpenSearchException.class, - () -> execute(closeIndexRequest, highLevelClient().indices()::close, highLevelClient().indices()::closeAsync)); + OpenSearchException exception = expectThrows( + OpenSearchException.class, + () -> execute(closeIndexRequest, highLevelClient().indices()::close, highLevelClient().indices()::closeAsync) + ); assertEquals(RestStatus.NOT_FOUND, exception.status()); } public void testCloseEmptyOrNullIndex() { String[] indices = randomBoolean() ? Strings.EMPTY_ARRAY : null; CloseIndexRequest closeIndexRequest = new CloseIndexRequest(indices); - org.opensearch.client.ValidationException exception = expectThrows(org.opensearch.client.ValidationException.class, - () -> execute(closeIndexRequest, highLevelClient().indices()::close, highLevelClient().indices()::closeAsync)); + org.opensearch.client.ValidationException exception = expectThrows( + org.opensearch.client.ValidationException.class, + () -> execute(closeIndexRequest, highLevelClient().indices()::close, highLevelClient().indices()::closeAsync) + ); assertThat(exception.validationErrors().get(0), equalTo("index is missing")); } public void testRefresh() throws IOException { { String index = "index"; - Settings settings = Settings.builder() - .put("number_of_shards", 1) - .put("number_of_replicas", 0) - .build(); + Settings settings = Settings.builder().put("number_of_shards", 1).put("number_of_replicas", 0).build(); createIndex(index, settings); RefreshRequest refreshRequest = new RefreshRequest(index); - RefreshResponse refreshResponse = - execute(refreshRequest, highLevelClient().indices()::refresh, highLevelClient().indices()::refreshAsync); + RefreshResponse refreshResponse = execute( + refreshRequest, + highLevelClient().indices()::refresh, + highLevelClient().indices()::refreshAsync + ); assertThat(refreshResponse.getTotalShards(), equalTo(1)); assertThat(refreshResponse.getSuccessfulShards(), equalTo(1)); assertThat(refreshResponse.getFailedShards(), equalTo(0)); @@ -967,8 +1044,10 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { String nonExistentIndex = "non_existent_index"; assertFalse(indexExists(nonExistentIndex)); RefreshRequest refreshRequest = new RefreshRequest(nonExistentIndex); - OpenSearchException exception = expectThrows(OpenSearchException.class, - () -> execute(refreshRequest, highLevelClient().indices()::refresh, highLevelClient().indices()::refreshAsync)); + OpenSearchException exception = expectThrows( + OpenSearchException.class, + () -> execute(refreshRequest, highLevelClient().indices()::refresh, highLevelClient().indices()::refreshAsync) + ); assertEquals(RestStatus.NOT_FOUND, exception.status()); } } @@ -976,14 +1055,14 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { public void testFlush() throws IOException { { String index = "index"; - Settings settings = Settings.builder() - .put("number_of_shards", 1) - .put("number_of_replicas", 0) - .build(); + Settings settings = Settings.builder().put("number_of_shards", 1).put("number_of_replicas", 0).build(); createIndex(index, settings); FlushRequest flushRequest = new FlushRequest(index); - FlushResponse flushResponse = - execute(flushRequest, highLevelClient().indices()::flush, highLevelClient().indices()::flushAsync); + FlushResponse flushResponse = execute( + flushRequest, + highLevelClient().indices()::flush, + highLevelClient().indices()::flushAsync + ); assertThat(flushResponse.getTotalShards(), equalTo(1)); assertThat(flushResponse.getSuccessfulShards(), equalTo(1)); assertThat(flushResponse.getFailedShards(), equalTo(0)); @@ -993,8 +1072,10 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { String nonExistentIndex = "non_existent_index"; assertFalse(indexExists(nonExistentIndex)); FlushRequest flushRequest = new FlushRequest(nonExistentIndex); - OpenSearchException exception = expectThrows(OpenSearchException.class, - () -> execute(flushRequest, highLevelClient().indices()::flush, highLevelClient().indices()::flushAsync)); + OpenSearchException exception = expectThrows( + OpenSearchException.class, + () -> execute(flushRequest, highLevelClient().indices()::flush, highLevelClient().indices()::flushAsync) + ); assertEquals(RestStatus.NOT_FOUND, exception.status()); } } @@ -1002,15 +1083,15 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { public void testSyncedFlush() throws IOException { { String index = "index"; - Settings settings = Settings.builder() - .put("number_of_shards", 1) - .put("number_of_replicas", 0) - .build(); + Settings settings = Settings.builder().put("number_of_shards", 1).put("number_of_replicas", 0).build(); createIndex(index, settings); SyncedFlushRequest syncedFlushRequest = new SyncedFlushRequest(index); - SyncedFlushResponse flushResponse = - execute(syncedFlushRequest, highLevelClient().indices()::flushSynced, highLevelClient().indices()::flushSyncedAsync, - expectWarnings(SyncedFlushService.SYNCED_FLUSH_DEPRECATION_MESSAGE)); + SyncedFlushResponse flushResponse = execute( + syncedFlushRequest, + highLevelClient().indices()::flushSynced, + highLevelClient().indices()::flushSyncedAsync, + expectWarnings(SyncedFlushService.SYNCED_FLUSH_DEPRECATION_MESSAGE) + ); assertThat(flushResponse.totalShards(), equalTo(1)); assertThat(flushResponse.successfulShards(), equalTo(1)); assertThat(flushResponse.failedShards(), equalTo(0)); @@ -1021,30 +1102,28 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { SyncedFlushRequest syncedFlushRequest = new SyncedFlushRequest(nonExistentIndex); OpenSearchException exception = expectThrows( OpenSearchException.class, - () -> - execute( - syncedFlushRequest, - highLevelClient().indices()::flushSynced, - highLevelClient().indices()::flushSyncedAsync, - expectWarnings(SyncedFlushService.SYNCED_FLUSH_DEPRECATION_MESSAGE) - ) + () -> execute( + syncedFlushRequest, + highLevelClient().indices()::flushSynced, + highLevelClient().indices()::flushSyncedAsync, + expectWarnings(SyncedFlushService.SYNCED_FLUSH_DEPRECATION_MESSAGE) + ) ); assertEquals(RestStatus.NOT_FOUND, exception.status()); } } - public void testClearCache() throws IOException { { String index = "index"; - Settings settings = Settings.builder() - .put("number_of_shards", 1) - .put("number_of_replicas", 0) - .build(); + Settings settings = Settings.builder().put("number_of_shards", 1).put("number_of_replicas", 0).build(); createIndex(index, settings); ClearIndicesCacheRequest clearCacheRequest = new ClearIndicesCacheRequest(index); - ClearIndicesCacheResponse clearCacheResponse = - execute(clearCacheRequest, highLevelClient().indices()::clearCache, highLevelClient().indices()::clearCacheAsync); + ClearIndicesCacheResponse clearCacheResponse = execute( + clearCacheRequest, + highLevelClient().indices()::clearCache, + highLevelClient().indices()::clearCacheAsync + ); assertThat(clearCacheResponse.getTotalShards(), equalTo(1)); assertThat(clearCacheResponse.getSuccessfulShards(), equalTo(1)); assertThat(clearCacheResponse.getFailedShards(), equalTo(0)); @@ -1054,9 +1133,10 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { String nonExistentIndex = "non_existent_index"; assertFalse(indexExists(nonExistentIndex)); ClearIndicesCacheRequest clearCacheRequest = new ClearIndicesCacheRequest(nonExistentIndex); - OpenSearchException exception = expectThrows(OpenSearchException.class, - () -> execute(clearCacheRequest, highLevelClient().indices()::clearCache, - highLevelClient().indices()::clearCacheAsync)); + OpenSearchException exception = expectThrows( + OpenSearchException.class, + () -> execute(clearCacheRequest, highLevelClient().indices()::clearCache, highLevelClient().indices()::clearCacheAsync) + ); assertEquals(RestStatus.NOT_FOUND, exception.status()); } } @@ -1064,14 +1144,14 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { public void testForceMerge() throws IOException { { String index = "index"; - Settings settings = Settings.builder() - .put("number_of_shards", 1) - .put("number_of_replicas", 0) - .build(); + Settings settings = Settings.builder().put("number_of_shards", 1).put("number_of_replicas", 0).build(); createIndex(index, settings); ForceMergeRequest forceMergeRequest = new ForceMergeRequest(index); - ForceMergeResponse forceMergeResponse = - execute(forceMergeRequest, highLevelClient().indices()::forcemerge, highLevelClient().indices()::forcemergeAsync); + ForceMergeResponse forceMergeResponse = execute( + forceMergeRequest, + highLevelClient().indices()::forcemerge, + highLevelClient().indices()::forcemergeAsync + ); assertThat(forceMergeResponse.getTotalShards(), equalTo(1)); assertThat(forceMergeResponse.getSuccessfulShards(), equalTo(1)); assertThat(forceMergeResponse.getFailedShards(), equalTo(0)); @@ -1083,8 +1163,10 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { String nonExistentIndex = "non_existent_index"; assertFalse(indexExists(nonExistentIndex)); ForceMergeRequest forceMergeRequest = new ForceMergeRequest(nonExistentIndex); - OpenSearchException exception = expectThrows(OpenSearchException.class, - () -> execute(forceMergeRequest, highLevelClient().indices()::forcemerge, highLevelClient().indices()::forcemergeAsync)); + OpenSearchException exception = expectThrows( + OpenSearchException.class, + () -> execute(forceMergeRequest, highLevelClient().indices()::forcemerge, highLevelClient().indices()::forcemergeAsync) + ); assertEquals(RestStatus.NOT_FOUND, exception.status()); assertThat(forceMergeRequest.getDescription(), containsString(nonExistentIndex)); @@ -1112,78 +1194,94 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { Map nodes = getAsMap("_nodes"); String firstNode = ((Map) nodes.get("nodes")).keySet().iterator().next(); createIndex("source", Settings.builder().put("index.number_of_shards", 4).put("index.number_of_replicas", 0).build()); - updateIndexSettings("source", Settings.builder().put("index.routing.allocation.require._name", firstNode) - .put("index.blocks.write", true)); + updateIndexSettings( + "source", + Settings.builder().put("index.routing.allocation.require._name", firstNode).put("index.blocks.write", true) + ); ResizeRequest resizeRequest = new ResizeRequest("target", "source"); resizeRequest.setResizeType(ResizeType.SHRINK); - Settings targetSettings = - Settings.builder() - .put("index.number_of_shards", 2) - .put("index.number_of_replicas", 0) - .putNull("index.routing.allocation.require._name") - .build(); - resizeRequest.setTargetIndex(new org.opensearch.action.admin.indices.create.CreateIndexRequest("target") - .settings(targetSettings) - .alias(new Alias("alias"))); - ResizeResponse resizeResponse = execute(resizeRequest, highLevelClient().indices()::shrink, - highLevelClient().indices()::shrinkAsync); + Settings targetSettings = Settings.builder() + .put("index.number_of_shards", 2) + .put("index.number_of_replicas", 0) + .putNull("index.routing.allocation.require._name") + .build(); + resizeRequest.setTargetIndex( + new org.opensearch.action.admin.indices.create.CreateIndexRequest("target").settings(targetSettings).alias(new Alias("alias")) + ); + ResizeResponse resizeResponse = execute( + resizeRequest, + highLevelClient().indices()::shrink, + highLevelClient().indices()::shrinkAsync + ); assertTrue(resizeResponse.isAcknowledged()); assertTrue(resizeResponse.isShardsAcknowledged()); Map getIndexResponse = getAsMap("target"); - Map indexSettings = (Map)XContentMapValues.extractValue("target.settings.index", getIndexResponse); + Map indexSettings = (Map) XContentMapValues.extractValue("target.settings.index", getIndexResponse); assertNotNull(indexSettings); assertEquals("2", indexSettings.get("number_of_shards")); assertEquals("0", indexSettings.get("number_of_replicas")); - Map aliasData = (Map)XContentMapValues.extractValue("target.aliases.alias", getIndexResponse); + Map aliasData = (Map) XContentMapValues.extractValue("target.aliases.alias", getIndexResponse); assertNotNull(aliasData); } @SuppressWarnings("unchecked") public void testSplit() throws IOException { - createIndex("source", Settings.builder().put("index.number_of_shards", 2).put("index.number_of_replicas", 0) - .put("index.number_of_routing_shards", 4).build()); + createIndex( + "source", + Settings.builder() + .put("index.number_of_shards", 2) + .put("index.number_of_replicas", 0) + .put("index.number_of_routing_shards", 4) + .build() + ); updateIndexSettings("source", Settings.builder().put("index.blocks.write", true)); ResizeRequest resizeRequest = new ResizeRequest("target", "source"); resizeRequest.setResizeType(ResizeType.SPLIT); Settings targetSettings = Settings.builder().put("index.number_of_shards", 4).put("index.number_of_replicas", 0).build(); - resizeRequest.setTargetIndex(new org.opensearch.action.admin.indices.create.CreateIndexRequest("target") - .settings(targetSettings) - .alias(new Alias("alias"))); + resizeRequest.setTargetIndex( + new org.opensearch.action.admin.indices.create.CreateIndexRequest("target").settings(targetSettings).alias(new Alias("alias")) + ); ResizeResponse resizeResponse = execute(resizeRequest, highLevelClient().indices()::split, highLevelClient().indices()::splitAsync); assertTrue(resizeResponse.isAcknowledged()); assertTrue(resizeResponse.isShardsAcknowledged()); Map getIndexResponse = getAsMap("target"); - Map indexSettings = (Map)XContentMapValues.extractValue("target.settings.index", getIndexResponse); + Map indexSettings = (Map) XContentMapValues.extractValue("target.settings.index", getIndexResponse); assertNotNull(indexSettings); assertEquals("4", indexSettings.get("number_of_shards")); assertEquals("0", indexSettings.get("number_of_replicas")); - Map aliasData = (Map)XContentMapValues.extractValue("target.aliases.alias", getIndexResponse); + Map aliasData = (Map) XContentMapValues.extractValue("target.aliases.alias", getIndexResponse); assertNotNull(aliasData); } @SuppressWarnings("unchecked") public void testClone() throws IOException { - createIndex("source", Settings.builder().put("index.number_of_shards", 2).put("index.number_of_replicas", 0) - .put("index.number_of_routing_shards", 4).build()); + createIndex( + "source", + Settings.builder() + .put("index.number_of_shards", 2) + .put("index.number_of_replicas", 0) + .put("index.number_of_routing_shards", 4) + .build() + ); updateIndexSettings("source", Settings.builder().put("index.blocks.write", true)); ResizeRequest resizeRequest = new ResizeRequest("target", "source"); resizeRequest.setResizeType(ResizeType.CLONE); Settings targetSettings = Settings.builder().put("index.number_of_shards", 2).put("index.number_of_replicas", 0).build(); - resizeRequest.setTargetIndex(new org.opensearch.action.admin.indices.create.CreateIndexRequest("target") - .settings(targetSettings) - .alias(new Alias("alias"))); + resizeRequest.setTargetIndex( + new org.opensearch.action.admin.indices.create.CreateIndexRequest("target").settings(targetSettings).alias(new Alias("alias")) + ); ResizeResponse resizeResponse = execute(resizeRequest, highLevelClient().indices()::clone, highLevelClient().indices()::cloneAsync); assertTrue(resizeResponse.isAcknowledged()); assertTrue(resizeResponse.isShardsAcknowledged()); Map getIndexResponse = getAsMap("target"); - Map indexSettings = (Map)XContentMapValues.extractValue("target.settings.index", getIndexResponse); + Map indexSettings = (Map) XContentMapValues.extractValue("target.settings.index", getIndexResponse); assertNotNull(indexSettings); assertEquals("2", indexSettings.get("number_of_shards")); assertEquals("0", indexSettings.get("number_of_replicas")); - Map aliasData = (Map)XContentMapValues.extractValue("target.aliases.alias", getIndexResponse); + Map aliasData = (Map) XContentMapValues.extractValue("target.aliases.alias", getIndexResponse); assertNotNull(aliasData); } @@ -1193,8 +1291,11 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { rolloverRequest.addMaxIndexDocsCondition(1); { - RolloverResponse rolloverResponse = execute(rolloverRequest, highLevelClient().indices()::rollover, - highLevelClient().indices()::rolloverAsync); + RolloverResponse rolloverResponse = execute( + rolloverRequest, + highLevelClient().indices()::rollover, + highLevelClient().indices()::rolloverAsync + ); assertFalse(rolloverResponse.isRolledOver()); assertFalse(rolloverResponse.isDryRun()); Map conditionStatus = rolloverResponse.getConditionStatus(); @@ -1205,15 +1306,20 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { } highLevelClient().index(new IndexRequest("test").id("1").source("field", "value"), RequestOptions.DEFAULT); - highLevelClient().index(new IndexRequest("test").id("2").source("field", "value") - .setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL), RequestOptions.DEFAULT); - //without the refresh the rollover may not happen as the number of docs seen may be off + highLevelClient().index( + new IndexRequest("test").id("2").source("field", "value").setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL), + RequestOptions.DEFAULT + ); + // without the refresh the rollover may not happen as the number of docs seen may be off { rolloverRequest.addMaxIndexAgeCondition(new TimeValue(1)); rolloverRequest.dryRun(true); - RolloverResponse rolloverResponse = execute(rolloverRequest, highLevelClient().indices()::rollover, - highLevelClient().indices()::rolloverAsync); + RolloverResponse rolloverResponse = execute( + rolloverRequest, + highLevelClient().indices()::rollover, + highLevelClient().indices()::rolloverAsync + ); assertFalse(rolloverResponse.isRolledOver()); assertTrue(rolloverResponse.isDryRun()); Map conditionStatus = rolloverResponse.getConditionStatus(); @@ -1228,8 +1334,11 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { rolloverRequest.getCreateIndexRequest().mapping(mappings, XContentType.JSON); rolloverRequest.dryRun(false); rolloverRequest.addMaxIndexSizeCondition(new ByteSizeValue(1, ByteSizeUnit.MB)); - RolloverResponse rolloverResponse = execute(rolloverRequest, highLevelClient().indices()::rollover, - highLevelClient().indices()::rolloverAsync); + RolloverResponse rolloverResponse = execute( + rolloverRequest, + highLevelClient().indices()::rollover, + highLevelClient().indices()::rolloverAsync + ); assertTrue(rolloverResponse.isRolledOver()); assertFalse(rolloverResponse.isDryRun()); Map conditionStatus = rolloverResponse.getConditionStatus(); @@ -1245,8 +1354,10 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { public void testRolloverWithTypes() throws IOException { highLevelClient().indices().create(new CreateIndexRequest("test").alias(new Alias("alias")), RequestOptions.DEFAULT); highLevelClient().index(new IndexRequest("test").id("1").source("field", "value"), RequestOptions.DEFAULT); - highLevelClient().index(new IndexRequest("test").id("2").source("field", "value") - .setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL), RequestOptions.DEFAULT); + highLevelClient().index( + new IndexRequest("test").id("2").source("field", "value").setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL), + RequestOptions.DEFAULT + ); org.opensearch.action.admin.indices.rollover.RolloverRequest rolloverRequest = new org.opensearch.action.admin.indices.rollover.RolloverRequest("alias", "test_new"); @@ -1279,8 +1390,11 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { } { GetAliasesRequest getAliasesRequest = new GetAliasesRequest().aliases("alias1"); - GetAliasesResponse getAliasesResponse = execute(getAliasesRequest, highLevelClient().indices()::getAlias, - highLevelClient().indices()::getAliasAsync); + GetAliasesResponse getAliasesResponse = execute( + getAliasesRequest, + highLevelClient().indices()::getAlias, + highLevelClient().indices()::getAliasAsync + ); assertThat(getAliasesResponse.getAliases().size(), equalTo(1)); assertThat(getAliasesResponse.getAliases().get("index1").size(), equalTo(1)); @@ -1293,8 +1407,11 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { } { GetAliasesRequest getAliasesRequest = new GetAliasesRequest().aliases("alias*"); - GetAliasesResponse getAliasesResponse = execute(getAliasesRequest, highLevelClient().indices()::getAlias, - highLevelClient().indices()::getAliasAsync); + GetAliasesResponse getAliasesResponse = execute( + getAliasesRequest, + highLevelClient().indices()::getAlias, + highLevelClient().indices()::getAliasAsync + ); assertThat(getAliasesResponse.getAliases().size(), equalTo(2)); assertThat(getAliasesResponse.getAliases().get("index1").size(), equalTo(1)); @@ -1308,8 +1425,11 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { } { GetAliasesRequest getAliasesRequest = new GetAliasesRequest().aliases("_all"); - GetAliasesResponse getAliasesResponse = execute(getAliasesRequest, highLevelClient().indices()::getAlias, - highLevelClient().indices()::getAliasAsync); + GetAliasesResponse getAliasesResponse = execute( + getAliasesRequest, + highLevelClient().indices()::getAlias, + highLevelClient().indices()::getAliasAsync + ); assertThat(getAliasesResponse.getAliases().size(), equalTo(2)); assertThat(getAliasesResponse.getAliases().get("index1").size(), equalTo(1)); @@ -1323,8 +1443,11 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { } { GetAliasesRequest getAliasesRequest = new GetAliasesRequest().aliases("*"); - GetAliasesResponse getAliasesResponse = execute(getAliasesRequest, highLevelClient().indices()::getAlias, - highLevelClient().indices()::getAliasAsync); + GetAliasesResponse getAliasesResponse = execute( + getAliasesRequest, + highLevelClient().indices()::getAlias, + highLevelClient().indices()::getAliasAsync + ); assertThat(getAliasesResponse.getAliases().size(), equalTo(2)); assertThat(getAliasesResponse.getAliases().get("index1").size(), equalTo(1)); @@ -1338,11 +1461,17 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { } { GetAliasesRequest getAliasesRequest = new GetAliasesRequest().indices("_all"); - GetAliasesResponse getAliasesResponse = execute(getAliasesRequest, highLevelClient().indices()::getAlias, - highLevelClient().indices()::getAliasAsync); + GetAliasesResponse getAliasesResponse = execute( + getAliasesRequest, + highLevelClient().indices()::getAlias, + highLevelClient().indices()::getAliasAsync + ); - assertThat("Unexpected number of aliases, got: " + getAliasesResponse.getAliases().toString(), - getAliasesResponse.getAliases().size(), equalTo(3)); + assertThat( + "Unexpected number of aliases, got: " + getAliasesResponse.getAliases().toString(), + getAliasesResponse.getAliases().size(), + equalTo(3) + ); assertThat(getAliasesResponse.getAliases().get("index1").size(), equalTo(1)); AliasMetadata aliasMetadata1 = getAliasesResponse.getAliases().get("index1").iterator().next(); assertThat(aliasMetadata1, notNullValue()); @@ -1355,8 +1484,11 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { } { GetAliasesRequest getAliasesRequest = new GetAliasesRequest().indices("ind*"); - GetAliasesResponse getAliasesResponse = execute(getAliasesRequest, highLevelClient().indices()::getAlias, - highLevelClient().indices()::getAliasAsync); + GetAliasesResponse getAliasesResponse = execute( + getAliasesRequest, + highLevelClient().indices()::getAlias, + highLevelClient().indices()::getAliasAsync + ); assertThat(getAliasesResponse.getAliases().size(), equalTo(3)); assertThat(getAliasesResponse.getAliases().get("index1").size(), equalTo(1)); @@ -1371,8 +1503,11 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { } { GetAliasesRequest getAliasesRequest = new GetAliasesRequest(); - GetAliasesResponse getAliasesResponse = execute(getAliasesRequest, highLevelClient().indices()::getAlias, - highLevelClient().indices()::getAliasAsync); + GetAliasesResponse getAliasesResponse = execute( + getAliasesRequest, + highLevelClient().indices()::getAlias, + highLevelClient().indices()::getAliasAsync + ); assertThat(getAliasesResponse.getAliases().size(), equalTo(3)); assertThat(getAliasesResponse.getAliases().get("index1").size(), equalTo(1)); @@ -1396,16 +1531,24 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { String index = "index"; { GetAliasesRequest getAliasesRequest = new GetAliasesRequest().indices(index); - GetAliasesResponse getAliasesResponse = execute(getAliasesRequest, highLevelClient().indices()::getAlias, - highLevelClient().indices()::getAliasAsync); + GetAliasesResponse getAliasesResponse = execute( + getAliasesRequest, + highLevelClient().indices()::getAlias, + highLevelClient().indices()::getAliasAsync + ); assertThat(getAliasesResponse.status(), equalTo(RestStatus.NOT_FOUND)); - assertThat(getAliasesResponse.getException().getMessage(), - equalTo("OpenSearch exception [type=index_not_found_exception, reason=no such index [index]]")); + assertThat( + getAliasesResponse.getException().getMessage(), + equalTo("OpenSearch exception [type=index_not_found_exception, reason=no such index [index]]") + ); } { GetAliasesRequest getAliasesRequest = new GetAliasesRequest(alias); - GetAliasesResponse getAliasesResponse = execute(getAliasesRequest, highLevelClient().indices()::getAlias, - highLevelClient().indices()::getAliasAsync); + GetAliasesResponse getAliasesResponse = execute( + getAliasesRequest, + highLevelClient().indices()::getAlias, + highLevelClient().indices()::getAliasAsync + ); assertThat(getAliasesResponse.status(), equalTo(RestStatus.NOT_FOUND)); assertThat(getAliasesResponse.getError(), equalTo("alias [" + alias + "] missing")); assertThat(getAliasesResponse.getException(), nullValue()); @@ -1414,27 +1557,40 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { client().performRequest(new Request(HttpPut.METHOD_NAME, index + "/_alias/" + alias)); { GetAliasesRequest getAliasesRequest = new GetAliasesRequest().indices(index, "non_existent_index"); - GetAliasesResponse getAliasesResponse = execute(getAliasesRequest, highLevelClient().indices()::getAlias, - highLevelClient().indices()::getAliasAsync); + GetAliasesResponse getAliasesResponse = execute( + getAliasesRequest, + highLevelClient().indices()::getAlias, + highLevelClient().indices()::getAliasAsync + ); assertThat(getAliasesResponse.getAliases().size(), equalTo(0)); assertThat(getAliasesResponse.status(), equalTo(RestStatus.NOT_FOUND)); assertThat(getAliasesResponse.getError(), nullValue()); - assertThat(getAliasesResponse.getException().getMessage(), - equalTo("OpenSearch exception [type=index_not_found_exception, reason=no such index [non_existent_index]]")); + assertThat( + getAliasesResponse.getException().getMessage(), + equalTo("OpenSearch exception [type=index_not_found_exception, reason=no such index [non_existent_index]]") + ); } { GetAliasesRequest getAliasesRequest = new GetAliasesRequest().indices(index, "non_existent_index").aliases(alias); - GetAliasesResponse getAliasesResponse = execute(getAliasesRequest, highLevelClient().indices()::getAlias, - highLevelClient().indices()::getAliasAsync); + GetAliasesResponse getAliasesResponse = execute( + getAliasesRequest, + highLevelClient().indices()::getAlias, + highLevelClient().indices()::getAliasAsync + ); assertThat(getAliasesResponse.getAliases().size(), equalTo(0)); assertThat(getAliasesResponse.status(), equalTo(RestStatus.NOT_FOUND)); - assertThat(getAliasesResponse.getException().getMessage(), - equalTo("OpenSearch exception [type=index_not_found_exception, reason=no such index [non_existent_index]]")); + assertThat( + getAliasesResponse.getException().getMessage(), + equalTo("OpenSearch exception [type=index_not_found_exception, reason=no such index [non_existent_index]]") + ); } { GetAliasesRequest getAliasesRequest = new GetAliasesRequest().indices("non_existent_index*"); - GetAliasesResponse getAliasesResponse = execute(getAliasesRequest, highLevelClient().indices()::getAlias, - highLevelClient().indices()::getAliasAsync); + GetAliasesResponse getAliasesResponse = execute( + getAliasesRequest, + highLevelClient().indices()::getAlias, + highLevelClient().indices()::getAliasAsync + ); assertThat(getAliasesResponse.status(), equalTo(RestStatus.OK)); assertThat(getAliasesResponse.getAliases().size(), equalTo(0)); assertThat(getAliasesResponse.getException(), nullValue()); @@ -1442,8 +1598,11 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { } { GetAliasesRequest getAliasesRequest = new GetAliasesRequest().indices(index).aliases(alias, "non_existent_alias"); - GetAliasesResponse getAliasesResponse = execute(getAliasesRequest, highLevelClient().indices()::getAlias, - highLevelClient().indices()::getAliasAsync); + GetAliasesResponse getAliasesResponse = execute( + getAliasesRequest, + highLevelClient().indices()::getAlias, + highLevelClient().indices()::getAliasAsync + ); assertThat(getAliasesResponse.status(), equalTo(RestStatus.NOT_FOUND)); assertThat(getAliasesResponse.getError(), equalTo("alias [non_existent_alias] missing")); @@ -1467,8 +1626,11 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { } { GetAliasesRequest getAliasesRequest = new GetAliasesRequest().aliases("non_existent_alias*"); - GetAliasesResponse getAliasesResponse = execute(getAliasesRequest, highLevelClient().indices()::getAlias, - highLevelClient().indices()::getAliasAsync); + GetAliasesResponse getAliasesResponse = execute( + getAliasesRequest, + highLevelClient().indices()::getAlias, + highLevelClient().indices()::getAliasAsync + ); assertThat(getAliasesResponse.status(), equalTo(RestStatus.OK)); assertThat(getAliasesResponse.getAliases().size(), equalTo(0)); } @@ -1494,8 +1656,11 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { assertThat(dynamicSetting.getDefault(Settings.EMPTY), not(dynamicSettingValue)); UpdateSettingsRequest dynamicSettingRequest = new UpdateSettingsRequest(index); dynamicSettingRequest.settings(Settings.builder().put(dynamicSettingKey, dynamicSettingValue).build()); - AcknowledgedResponse response = execute(dynamicSettingRequest, highLevelClient().indices()::putSettings, - highLevelClient().indices()::putSettingsAsync); + AcknowledgedResponse response = execute( + dynamicSettingRequest, + highLevelClient().indices()::putSettings, + highLevelClient().indices()::putSettingsAsync + ); assertTrue(response.isAcknowledged()); Map indexSettingsAsMap = getIndexSettingsAsMap(index); @@ -1504,18 +1669,23 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { assertThat(staticSetting.getDefault(Settings.EMPTY), not(staticSettingValue)); UpdateSettingsRequest staticSettingRequest = new UpdateSettingsRequest(index); staticSettingRequest.settings(Settings.builder().put(staticSettingKey, staticSettingValue).build()); - OpenSearchException exception = expectThrows(OpenSearchException.class, () -> execute(staticSettingRequest, - highLevelClient().indices()::putSettings, highLevelClient().indices()::putSettingsAsync)); - assertThat(exception.getMessage(), - startsWith("OpenSearch exception [type=illegal_argument_exception, " - + "reason=Can't update non dynamic settings [[index.shard.check_on_startup]] for open indices [[index/")); + OpenSearchException exception = expectThrows( + OpenSearchException.class, + () -> execute(staticSettingRequest, highLevelClient().indices()::putSettings, highLevelClient().indices()::putSettingsAsync) + ); + assertThat( + exception.getMessage(), + startsWith( + "OpenSearch exception [type=illegal_argument_exception, " + + "reason=Can't update non dynamic settings [[index.shard.check_on_startup]] for open indices [[index/" + ) + ); indexSettingsAsMap = getIndexSettingsAsMap(index); assertNull(indexSettingsAsMap.get(staticSettingKey)); closeIndex(index); - response = execute(staticSettingRequest, highLevelClient().indices()::putSettings, - highLevelClient().indices()::putSettingsAsync); + response = execute(staticSettingRequest, highLevelClient().indices()::putSettings, highLevelClient().indices()::putSettingsAsync); assertTrue(response.isAcknowledged()); openIndex(index); indexSettingsAsMap = getIndexSettingsAsMap(index); @@ -1524,17 +1694,37 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { assertThat(unmodifiableSetting.getDefault(Settings.EMPTY), not(unmodifiableSettingValue)); UpdateSettingsRequest unmodifiableSettingRequest = new UpdateSettingsRequest(index); unmodifiableSettingRequest.settings(Settings.builder().put(unmodifiableSettingKey, unmodifiableSettingValue).build()); - exception = expectThrows(OpenSearchException.class, () -> execute(unmodifiableSettingRequest, - highLevelClient().indices()::putSettings, highLevelClient().indices()::putSettingsAsync)); - assertThat(exception.getMessage(), startsWith( + exception = expectThrows( + OpenSearchException.class, + () -> execute( + unmodifiableSettingRequest, + highLevelClient().indices()::putSettings, + highLevelClient().indices()::putSettingsAsync + ) + ); + assertThat( + exception.getMessage(), + startsWith( "OpenSearch exception [type=illegal_argument_exception, " - + "reason=Can't update non dynamic settings [[index.number_of_shards]] for open indices [[index/")); + + "reason=Can't update non dynamic settings [[index.number_of_shards]] for open indices [[index/" + ) + ); closeIndex(index); - exception = expectThrows(OpenSearchException.class, () -> execute(unmodifiableSettingRequest, - highLevelClient().indices()::putSettings, highLevelClient().indices()::putSettingsAsync)); - assertThat(exception.getMessage(), startsWith( + exception = expectThrows( + OpenSearchException.class, + () -> execute( + unmodifiableSettingRequest, + highLevelClient().indices()::putSettings, + highLevelClient().indices()::putSettingsAsync + ) + ); + assertThat( + exception.getMessage(), + startsWith( "OpenSearch exception [type=illegal_argument_exception, " - + "reason=final index setting [index.number_of_shards], not updateable")); + + "reason=final index setting [index.number_of_shards], not updateable" + ) + ); } public void testIndexPutSettingNonExistent() throws IOException { @@ -1545,38 +1735,55 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { int value = 10; indexUpdateSettingsRequest.settings(Settings.builder().put(setting, value).build()); - OpenSearchException exception = expectThrows(OpenSearchException.class, () -> execute(indexUpdateSettingsRequest, - highLevelClient().indices()::putSettings, highLevelClient().indices()::putSettingsAsync)); + OpenSearchException exception = expectThrows( + OpenSearchException.class, + () -> execute( + indexUpdateSettingsRequest, + highLevelClient().indices()::putSettings, + highLevelClient().indices()::putSettingsAsync + ) + ); assertEquals(RestStatus.NOT_FOUND, exception.status()); - assertThat(exception.getMessage(), - equalTo("OpenSearch exception [type=index_not_found_exception, reason=no such index [index]]")); + assertThat(exception.getMessage(), equalTo("OpenSearch exception [type=index_not_found_exception, reason=no such index [index]]")); createIndex(index, Settings.EMPTY); - exception = expectThrows(OpenSearchException.class, () -> execute(indexUpdateSettingsRequest, - highLevelClient().indices()::putSettings, highLevelClient().indices()::putSettingsAsync)); + exception = expectThrows( + OpenSearchException.class, + () -> execute( + indexUpdateSettingsRequest, + highLevelClient().indices()::putSettings, + highLevelClient().indices()::putSettingsAsync + ) + ); assertThat(exception.status(), equalTo(RestStatus.BAD_REQUEST)); - assertThat(exception.getMessage(), equalTo( + assertThat( + exception.getMessage(), + equalTo( "OpenSearch exception [type=illegal_argument_exception, " - + "reason=unknown setting [index.no_idea_what_you_are_talking_about] please check that any required plugins are installed, " - + "or check the breaking changes documentation for removed settings]")); + + "reason=unknown setting [index.no_idea_what_you_are_talking_about] please check that any required plugins are installed, " + + "or check the breaking changes documentation for removed settings]" + ) + ); } @SuppressWarnings("unchecked") public void testPutTemplateWithTypes() throws Exception { org.opensearch.action.admin.indices.template.put.PutIndexTemplateRequest putTemplateRequest = - new org.opensearch.action.admin.indices.template.put.PutIndexTemplateRequest() - .name("my-template") - .patterns(Arrays.asList("pattern-1", "name-*")) - .order(10) - .create(randomBoolean()) - .settings(Settings.builder().put("number_of_shards", "3").put("number_of_replicas", "0")) - .mapping("doc", "host_name", "type=keyword", "description", "type=text") - .alias(new Alias("alias-1").indexRouting("abc")).alias(new Alias("{index}-write").searchRouting("xyz")); + new org.opensearch.action.admin.indices.template.put.PutIndexTemplateRequest().name("my-template") + .patterns(Arrays.asList("pattern-1", "name-*")) + .order(10) + .create(randomBoolean()) + .settings(Settings.builder().put("number_of_shards", "3").put("number_of_replicas", "0")) + .mapping("doc", "host_name", "type=keyword", "description", "type=text") + .alias(new Alias("alias-1").indexRouting("abc")) + .alias(new Alias("{index}-write").searchRouting("xyz")); - AcknowledgedResponse putTemplateResponse = execute(putTemplateRequest, - highLevelClient().indices()::putTemplate, highLevelClient().indices()::putTemplateAsync, + AcknowledgedResponse putTemplateResponse = execute( + putTemplateRequest, + highLevelClient().indices()::putTemplate, + highLevelClient().indices()::putTemplateAsync, expectWarnings(RestPutIndexTemplateAction.TYPES_DEPRECATION_MESSAGE) - ); + ); assertThat(putTemplateResponse.isAcknowledged(), equalTo(true)); Map templates = getAsMap("/_template/my-template"); @@ -1593,17 +1800,22 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { @SuppressWarnings("unchecked") public void testPutTemplate() throws Exception { - PutIndexTemplateRequest putTemplateRequest = new PutIndexTemplateRequest("my-template") - .patterns(Arrays.asList("pattern-1", "name-*")) + PutIndexTemplateRequest putTemplateRequest = new PutIndexTemplateRequest("my-template").patterns( + Arrays.asList("pattern-1", "name-*") + ) .order(10) .create(randomBoolean()) .settings(Settings.builder().put("number_of_shards", "3").put("number_of_replicas", "0")) .mapping("{ \"properties\": { \"host_name\": { \"type\": \"keyword\" } } }", XContentType.JSON) .alias(new Alias("alias-1").indexRouting("abc")) - .alias(new Alias("alias-1").indexRouting("abc")).alias(new Alias("{index}-write").searchRouting("xyz")); + .alias(new Alias("alias-1").indexRouting("abc")) + .alias(new Alias("{index}-write").searchRouting("xyz")); - AcknowledgedResponse putTemplateResponse = execute(putTemplateRequest, - highLevelClient().indices()::putTemplate, highLevelClient().indices()::putTemplateAsync); + AcknowledgedResponse putTemplateResponse = execute( + putTemplateRequest, + highLevelClient().indices()::putTemplate, + highLevelClient().indices()::putTemplateAsync + ); assertThat(putTemplateResponse.isAcknowledged(), equalTo(true)); Map templates = getAsMap("/_template/my-template"); @@ -1618,21 +1830,24 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { } public void testPutTemplateWithDeprecatedTemplateField() throws Exception { - PutIndexTemplateRequest putTemplateRequest = new PutIndexTemplateRequest("my-template") - .source(XContentFactory.jsonBuilder() + PutIndexTemplateRequest putTemplateRequest = new PutIndexTemplateRequest("my-template").source( + XContentFactory.jsonBuilder() .startObject() - .field("template", "name-*") - .field("order", 10) - .startObject("settings") - .field("number_of_shards", 3) - .field("number_of_replicas", 0) - .endObject() - .endObject()); + .field("template", "name-*") + .field("order", 10) + .startObject("settings") + .field("number_of_shards", 3) + .field("number_of_replicas", 0) + .endObject() + .endObject() + ); - AcknowledgedResponse putTemplateResponse = execute(putTemplateRequest, + AcknowledgedResponse putTemplateResponse = execute( + putTemplateRequest, highLevelClient().indices()::putTemplate, highLevelClient().indices()::putTemplateAsync, - expectWarnings("Deprecated field [template] used, replaced by [index_patterns]")); + expectWarnings("Deprecated field [template] used, replaced by [index_patterns]") + ); assertThat(putTemplateResponse.isAcknowledged(), equalTo(true)); Map templates = getAsMap("/_template/my-template"); @@ -1644,8 +1859,9 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { } public void testPutTemplateWithTypesUsingUntypedAPI() throws Exception { - PutIndexTemplateRequest putTemplateRequest = new PutIndexTemplateRequest("my-template") - .patterns(Arrays.asList("pattern-1", "name-*")) + PutIndexTemplateRequest putTemplateRequest = new PutIndexTemplateRequest("my-template").patterns( + Arrays.asList("pattern-1", "name-*") + ) .order(10) .create(randomBoolean()) .settings(Settings.builder().put("number_of_shards", "3").put("number_of_replicas", "0")) @@ -1661,39 +1877,47 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { + "}", XContentType.JSON ) - .alias(new Alias("alias-1").indexRouting("abc")).alias(new Alias("{index}-write").searchRouting("xyz")); + .alias(new Alias("alias-1").indexRouting("abc")) + .alias(new Alias("{index}-write").searchRouting("xyz")); - - OpenSearchStatusException badMappingError = expectThrows(OpenSearchStatusException.class, - () -> execute(putTemplateRequest, - highLevelClient().indices()::putTemplate, highLevelClient().indices()::putTemplateAsync)); - assertThat(badMappingError.getDetailedMessage(), - containsString("Root mapping definition has unsupported parameters: [my_doc_type")); + OpenSearchStatusException badMappingError = expectThrows( + OpenSearchStatusException.class, + () -> execute(putTemplateRequest, highLevelClient().indices()::putTemplate, highLevelClient().indices()::putTemplateAsync) + ); + assertThat( + badMappingError.getDetailedMessage(), + containsString("Root mapping definition has unsupported parameters: [my_doc_type") + ); } @SuppressWarnings("unchecked") public void testPutTemplateWithNoTypesUsingTypedApi() throws Exception { org.opensearch.action.admin.indices.template.put.PutIndexTemplateRequest putTemplateRequest = - new org.opensearch.action.admin.indices.template.put.PutIndexTemplateRequest() - .name("my-template") - .patterns(Arrays.asList("pattern-1", "name-*")) - .order(10) - .create(randomBoolean()) - .settings(Settings.builder().put("number_of_shards", "3").put("number_of_replicas", "0")) - .mapping("my_doc_type", + new org.opensearch.action.admin.indices.template.put.PutIndexTemplateRequest().name("my-template") + .patterns(Arrays.asList("pattern-1", "name-*")) + .order(10) + .create(randomBoolean()) + .settings(Settings.builder().put("number_of_shards", "3").put("number_of_replicas", "0")) + .mapping( + "my_doc_type", // Note that the declared type is missing from the mapping "{ " - + "\"properties\":{" - + "\"host_name\": {\"type\":\"keyword\"}," - + "\"description\": {\"type\":\"text\"}" - + "}" - + "}", XContentType.JSON) - .alias(new Alias("alias-1").indexRouting("abc")).alias(new Alias("{index}-write").searchRouting("xyz")); + + "\"properties\":{" + + "\"host_name\": {\"type\":\"keyword\"}," + + "\"description\": {\"type\":\"text\"}" + + "}" + + "}", + XContentType.JSON + ) + .alias(new Alias("alias-1").indexRouting("abc")) + .alias(new Alias("{index}-write").searchRouting("xyz")); - AcknowledgedResponse putTemplateResponse = execute(putTemplateRequest, - highLevelClient().indices()::putTemplate, highLevelClient().indices()::putTemplateAsync, + AcknowledgedResponse putTemplateResponse = execute( + putTemplateRequest, + highLevelClient().indices()::putTemplate, + highLevelClient().indices()::putTemplateAsync, expectWarnings(RestPutIndexTemplateAction.TYPES_DEPRECATION_MESSAGE) - ); + ); assertThat(putTemplateResponse.isAcknowledged(), equalTo(true)); Map templates = getAsMap("/_template/my-template"); @@ -1713,45 +1937,54 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { // Failed to validate because index patterns are missing PutIndexTemplateRequest withoutPattern = new PutIndexTemplateRequest("t1"); - ValidationException withoutPatternError = expectThrows(ValidationException.class, - () -> execute(withoutPattern, client.indices()::putTemplate, client.indices()::putTemplateAsync)); + ValidationException withoutPatternError = expectThrows( + ValidationException.class, + () -> execute(withoutPattern, client.indices()::putTemplate, client.indices()::putTemplateAsync) + ); assertThat(withoutPatternError.validationErrors(), contains("index patterns are missing")); // Create-only specified but an template exists already PutIndexTemplateRequest goodTemplate = new PutIndexTemplateRequest("t2").patterns(Arrays.asList("qa-*", "prod-*")); assertTrue(execute(goodTemplate, client.indices()::putTemplate, client.indices()::putTemplateAsync).isAcknowledged()); goodTemplate.create(true); - OpenSearchException alreadyExistsError = expectThrows(OpenSearchException.class, - () -> execute(goodTemplate, client.indices()::putTemplate, client.indices()::putTemplateAsync)); - assertThat(alreadyExistsError.getDetailedMessage(), - containsString("[type=illegal_argument_exception, reason=index_template [t2] already exists]")); + OpenSearchException alreadyExistsError = expectThrows( + OpenSearchException.class, + () -> execute(goodTemplate, client.indices()::putTemplate, client.indices()::putTemplateAsync) + ); + assertThat( + alreadyExistsError.getDetailedMessage(), + containsString("[type=illegal_argument_exception, reason=index_template [t2] already exists]") + ); goodTemplate.create(false); assertTrue(execute(goodTemplate, client.indices()::putTemplate, client.indices()::putTemplateAsync).isAcknowledged()); // Rejected due to unknown settings - PutIndexTemplateRequest unknownSettingTemplate = new PutIndexTemplateRequest("t3") - .patterns(Collections.singletonList("any")) + PutIndexTemplateRequest unknownSettingTemplate = new PutIndexTemplateRequest("t3").patterns(Collections.singletonList("any")) .settings(Settings.builder().put("this-setting-does-not-exist", 100)); - OpenSearchStatusException unknownSettingError = expectThrows(OpenSearchStatusException.class, - () -> execute(unknownSettingTemplate, client.indices()::putTemplate, client.indices()::putTemplateAsync)); + OpenSearchStatusException unknownSettingError = expectThrows( + OpenSearchStatusException.class, + () -> execute(unknownSettingTemplate, client.indices()::putTemplate, client.indices()::putTemplateAsync) + ); assertThat(unknownSettingError.getDetailedMessage(), containsString("unknown setting [index.this-setting-does-not-exist]")); } - public void testValidateQuery() throws IOException{ + public void testValidateQuery() throws IOException { String index = "some_index"; createIndex(index, Settings.EMPTY); - QueryBuilder builder = QueryBuilders - .boolQuery() + QueryBuilder builder = QueryBuilders.boolQuery() .must(QueryBuilders.queryStringQuery("*:*")) .filter(QueryBuilders.termQuery("user", "foobar")); ValidateQueryRequest request = new ValidateQueryRequest(index).query(builder); request.explain(randomBoolean()); - ValidateQueryResponse response = execute(request, highLevelClient().indices()::validateQuery, - highLevelClient().indices()::validateQueryAsync); + ValidateQueryResponse response = execute( + request, + highLevelClient().indices()::validateQuery, + highLevelClient().indices()::validateQueryAsync + ); assertTrue(response.isValid()); } - public void testInvalidValidateQuery() throws IOException{ + public void testInvalidValidateQuery() throws IOException { String index = "shakespeare"; createIndex(index, Settings.EMPTY); @@ -1769,13 +2002,14 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { ); assertOK(client().performRequest(postDoc)); - QueryBuilder builder = QueryBuilders - .queryStringQuery("line_id:foo") - .lenient(false); + QueryBuilder builder = QueryBuilders.queryStringQuery("line_id:foo").lenient(false); ValidateQueryRequest request = new ValidateQueryRequest(index).query(builder); request.explain(true); - ValidateQueryResponse response = execute(request, highLevelClient().indices()::validateQuery, - highLevelClient().indices()::validateQueryAsync); + ValidateQueryResponse response = execute( + request, + highLevelClient().indices()::validateQuery, + highLevelClient().indices()::validateQueryAsync + ); assertFalse(response.isValid()); } @@ -1785,34 +2019,51 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { org.opensearch.action.admin.indices.template.put.PutIndexTemplateRequest putTemplate1 = new org.opensearch.action.admin.indices.template.put.PutIndexTemplateRequest().name("template-1") - .patterns(Arrays.asList("pattern-1", "name-1")).alias(new Alias("alias-1")); - assertThat(execute(putTemplate1, client.indices()::putTemplate, client.indices()::putTemplateAsync - , expectWarnings(RestPutIndexTemplateAction.TYPES_DEPRECATION_MESSAGE)) - .isAcknowledged(), equalTo(true)); + .patterns(Arrays.asList("pattern-1", "name-1")) + .alias(new Alias("alias-1")); + assertThat( + execute( + putTemplate1, + client.indices()::putTemplate, + client.indices()::putTemplateAsync, + expectWarnings(RestPutIndexTemplateAction.TYPES_DEPRECATION_MESSAGE) + ).isAcknowledged(), + equalTo(true) + ); org.opensearch.action.admin.indices.template.put.PutIndexTemplateRequest putTemplate2 = new org.opensearch.action.admin.indices.template.put.PutIndexTemplateRequest().name("template-2") - .patterns(Arrays.asList("pattern-2", "name-2")) - .mapping("custom_doc_type", "name", "type=text") - .settings(Settings.builder().put("number_of_shards", "2").put("number_of_replicas", "0")); - assertThat(execute(putTemplate2, client.indices()::putTemplate, client.indices()::putTemplateAsync, - expectWarnings(RestPutIndexTemplateAction.TYPES_DEPRECATION_MESSAGE)) - .isAcknowledged(), equalTo(true)); + .patterns(Arrays.asList("pattern-2", "name-2")) + .mapping("custom_doc_type", "name", "type=text") + .settings(Settings.builder().put("number_of_shards", "2").put("number_of_replicas", "0")); + assertThat( + execute( + putTemplate2, + client.indices()::putTemplate, + client.indices()::putTemplateAsync, + expectWarnings(RestPutIndexTemplateAction.TYPES_DEPRECATION_MESSAGE) + ).isAcknowledged(), + equalTo(true) + ); org.opensearch.action.admin.indices.template.get.GetIndexTemplatesResponse getTemplate1 = execute( - new GetIndexTemplatesRequest("template-1"), - client.indices()::getTemplate, client.indices()::getTemplateAsync, - expectWarnings(RestGetIndexTemplateAction.TYPES_DEPRECATION_MESSAGE)); + new GetIndexTemplatesRequest("template-1"), + client.indices()::getTemplate, + client.indices()::getTemplateAsync, + expectWarnings(RestGetIndexTemplateAction.TYPES_DEPRECATION_MESSAGE) + ); assertThat(getTemplate1.getIndexTemplates(), hasSize(1)); org.opensearch.cluster.metadata.IndexTemplateMetadata template1 = getTemplate1.getIndexTemplates().get(0); assertThat(template1.name(), equalTo("template-1")); assertThat(template1.patterns(), contains("pattern-1", "name-1")); assertTrue(template1.aliases().containsKey("alias-1")); - //Check the typed version of the call - org.opensearch.action.admin.indices.template.get.GetIndexTemplatesResponse getTemplate2 = - execute(new GetIndexTemplatesRequest("template-2"), - client.indices()::getTemplate, client.indices()::getTemplateAsync, - expectWarnings(RestGetIndexTemplateAction.TYPES_DEPRECATION_MESSAGE)); + // Check the typed version of the call + org.opensearch.action.admin.indices.template.get.GetIndexTemplatesResponse getTemplate2 = execute( + new GetIndexTemplatesRequest("template-2"), + client.indices()::getTemplate, + client.indices()::getTemplateAsync, + expectWarnings(RestGetIndexTemplateAction.TYPES_DEPRECATION_MESSAGE) + ); assertThat(getTemplate2.getIndexTemplates(), hasSize(1)); org.opensearch.cluster.metadata.IndexTemplateMetadata template2 = getTemplate2.getIndexTemplates().get(0); assertThat(template2.name(), equalTo("template-2")); @@ -1823,74 +2074,129 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { // Ugly deprecated form of API requires use of doc type to get at mapping object which is CompressedXContent assertTrue(template2.mappings().containsKey("custom_doc_type")); - List names = randomBoolean() - ? Arrays.asList("*plate-1", "template-2") - : Arrays.asList("template-*"); + List names = randomBoolean() ? Arrays.asList("*plate-1", "template-2") : Arrays.asList("template-*"); GetIndexTemplatesRequest getBothRequest = new GetIndexTemplatesRequest(names); org.opensearch.action.admin.indices.template.get.GetIndexTemplatesResponse getBoth = execute( - getBothRequest, client.indices()::getTemplate, client.indices()::getTemplateAsync, - expectWarnings(RestGetIndexTemplateAction.TYPES_DEPRECATION_MESSAGE)); + getBothRequest, + client.indices()::getTemplate, + client.indices()::getTemplateAsync, + expectWarnings(RestGetIndexTemplateAction.TYPES_DEPRECATION_MESSAGE) + ); assertThat(getBoth.getIndexTemplates(), hasSize(2)); - assertThat(getBoth.getIndexTemplates().stream().map(org.opensearch.cluster.metadata.IndexTemplateMetadata::getName).toArray(), - arrayContainingInAnyOrder("template-1", "template-2")); + assertThat( + getBoth.getIndexTemplates().stream().map(org.opensearch.cluster.metadata.IndexTemplateMetadata::getName).toArray(), + arrayContainingInAnyOrder("template-1", "template-2") + ); GetIndexTemplatesRequest getAllRequest = new GetIndexTemplatesRequest(); org.opensearch.action.admin.indices.template.get.GetIndexTemplatesResponse getAll = execute( - getAllRequest, client.indices()::getTemplate, client.indices()::getTemplateAsync, - expectWarnings(RestGetIndexTemplateAction.TYPES_DEPRECATION_MESSAGE)); + getAllRequest, + client.indices()::getTemplate, + client.indices()::getTemplateAsync, + expectWarnings(RestGetIndexTemplateAction.TYPES_DEPRECATION_MESSAGE) + ); assertThat(getAll.getIndexTemplates().size(), greaterThanOrEqualTo(2)); - assertThat(getAll.getIndexTemplates().stream().map(org.opensearch.cluster.metadata.IndexTemplateMetadata::getName) + assertThat( + getAll.getIndexTemplates() + .stream() + .map(org.opensearch.cluster.metadata.IndexTemplateMetadata::getName) .collect(Collectors.toList()), - hasItems("template-1", "template-2")); + hasItems("template-1", "template-2") + ); - assertTrue(execute(new DeleteIndexTemplateRequest("template-1"), - client.indices()::deleteTemplate, client.indices()::deleteTemplateAsync).isAcknowledged()); - assertThat(expectThrows(OpenSearchException.class, () -> execute(new GetIndexTemplatesRequest("template-1"), - client.indices()::getTemplate, client.indices()::getTemplateAsync)).status(), equalTo(RestStatus.NOT_FOUND)); - assertThat(expectThrows(OpenSearchException.class, () -> execute(new DeleteIndexTemplateRequest("template-1"), - client.indices()::deleteTemplate, client.indices()::deleteTemplateAsync)).status(), equalTo(RestStatus.NOT_FOUND)); + assertTrue( + execute(new DeleteIndexTemplateRequest("template-1"), client.indices()::deleteTemplate, client.indices()::deleteTemplateAsync) + .isAcknowledged() + ); + assertThat( + expectThrows( + OpenSearchException.class, + () -> execute(new GetIndexTemplatesRequest("template-1"), client.indices()::getTemplate, client.indices()::getTemplateAsync) + ).status(), + equalTo(RestStatus.NOT_FOUND) + ); + assertThat( + expectThrows( + OpenSearchException.class, + () -> execute( + new DeleteIndexTemplateRequest("template-1"), + client.indices()::deleteTemplate, + client.indices()::deleteTemplateAsync + ) + ).status(), + equalTo(RestStatus.NOT_FOUND) + ); - assertThat(execute(new GetIndexTemplatesRequest("template-*"), - client.indices()::getTemplate, client.indices()::getTemplateAsync, - expectWarnings(RestGetIndexTemplateAction.TYPES_DEPRECATION_MESSAGE)).getIndexTemplates(), hasSize(1)); - assertThat(execute(new GetIndexTemplatesRequest("template-*"), - client.indices()::getTemplate, client.indices()::getTemplateAsync, - expectWarnings(RestGetIndexTemplateAction.TYPES_DEPRECATION_MESSAGE)).getIndexTemplates() - .get(0).name(), equalTo("template-2")); + assertThat( + execute( + new GetIndexTemplatesRequest("template-*"), + client.indices()::getTemplate, + client.indices()::getTemplateAsync, + expectWarnings(RestGetIndexTemplateAction.TYPES_DEPRECATION_MESSAGE) + ).getIndexTemplates(), + hasSize(1) + ); + assertThat( + execute( + new GetIndexTemplatesRequest("template-*"), + client.indices()::getTemplate, + client.indices()::getTemplateAsync, + expectWarnings(RestGetIndexTemplateAction.TYPES_DEPRECATION_MESSAGE) + ).getIndexTemplates().get(0).name(), + equalTo("template-2") + ); - assertTrue(execute(new DeleteIndexTemplateRequest("template-*"), - client.indices()::deleteTemplate, client.indices()::deleteTemplateAsync).isAcknowledged()); - assertThat(expectThrows(OpenSearchException.class, () -> execute(new GetIndexTemplatesRequest("template-*"), - client.indices()::getTemplate, client.indices()::getTemplateAsync, - expectWarnings(RestGetIndexTemplateAction.TYPES_DEPRECATION_MESSAGE))).status(), equalTo(RestStatus.NOT_FOUND)); + assertTrue( + execute(new DeleteIndexTemplateRequest("template-*"), client.indices()::deleteTemplate, client.indices()::deleteTemplateAsync) + .isAcknowledged() + ); + assertThat( + expectThrows( + OpenSearchException.class, + () -> execute( + new GetIndexTemplatesRequest("template-*"), + client.indices()::getTemplate, + client.indices()::getTemplateAsync, + expectWarnings(RestGetIndexTemplateAction.TYPES_DEPRECATION_MESSAGE) + ) + ).status(), + equalTo(RestStatus.NOT_FOUND) + ); } - public void testCRUDIndexTemplate() throws Exception { RestHighLevelClient client = highLevelClient(); - PutIndexTemplateRequest putTemplate1 = new PutIndexTemplateRequest("template-1") - .patterns(Arrays.asList("pattern-1", "name-1")).alias(new Alias("alias-1")); - assertThat(execute(putTemplate1, client.indices()::putTemplate, client.indices()::putTemplateAsync).isAcknowledged(), - equalTo(true)); - PutIndexTemplateRequest putTemplate2 = new PutIndexTemplateRequest("template-2") - .patterns(Arrays.asList("pattern-2", "name-2")) + PutIndexTemplateRequest putTemplate1 = new PutIndexTemplateRequest("template-1").patterns(Arrays.asList("pattern-1", "name-1")) + .alias(new Alias("alias-1")); + assertThat( + execute(putTemplate1, client.indices()::putTemplate, client.indices()::putTemplateAsync).isAcknowledged(), + equalTo(true) + ); + PutIndexTemplateRequest putTemplate2 = new PutIndexTemplateRequest("template-2").patterns(Arrays.asList("pattern-2", "name-2")) .mapping("{\"properties\": { \"name\": { \"type\": \"text\" }}}", XContentType.JSON) .settings(Settings.builder().put("number_of_shards", "2").put("number_of_replicas", "0")); - assertThat(execute(putTemplate2, client.indices()::putTemplate, client.indices()::putTemplateAsync) - .isAcknowledged(), equalTo(true)); + assertThat( + execute(putTemplate2, client.indices()::putTemplate, client.indices()::putTemplateAsync).isAcknowledged(), + equalTo(true) + ); GetIndexTemplatesResponse getTemplate1 = execute( - new GetIndexTemplatesRequest("template-1"), - client.indices()::getIndexTemplate, client.indices()::getIndexTemplateAsync); + new GetIndexTemplatesRequest("template-1"), + client.indices()::getIndexTemplate, + client.indices()::getIndexTemplateAsync + ); assertThat(getTemplate1.getIndexTemplates(), hasSize(1)); IndexTemplateMetadata template1 = getTemplate1.getIndexTemplates().get(0); assertThat(template1.name(), equalTo("template-1")); assertThat(template1.patterns(), contains("pattern-1", "name-1")); assertTrue(template1.aliases().containsKey("alias-1")); - GetIndexTemplatesResponse getTemplate2 = execute(new GetIndexTemplatesRequest("template-2"), - client.indices()::getIndexTemplate, client.indices()::getIndexTemplateAsync); + GetIndexTemplatesResponse getTemplate2 = execute( + new GetIndexTemplatesRequest("template-2"), + client.indices()::getIndexTemplate, + client.indices()::getIndexTemplateAsync + ); assertThat(getTemplate2.getIndexTemplates(), hasSize(1)); IndexTemplateMetadata template2 = getTemplate2.getIndexTemplates().get(0); assertThat(template2.name(), equalTo("template-2")); @@ -1904,43 +2210,86 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { Map props = (Map) template2.mappings().sourceAsMap().get("properties"); assertTrue(props.containsKey("name")); - - - List names = randomBoolean() - ? Arrays.asList("*plate-1", "template-2") - : Arrays.asList("template-*"); + List names = randomBoolean() ? Arrays.asList("*plate-1", "template-2") : Arrays.asList("template-*"); GetIndexTemplatesRequest getBothRequest = new GetIndexTemplatesRequest(names); GetIndexTemplatesResponse getBoth = execute( - getBothRequest, client.indices()::getIndexTemplate, client.indices()::getIndexTemplateAsync); + getBothRequest, + client.indices()::getIndexTemplate, + client.indices()::getIndexTemplateAsync + ); assertThat(getBoth.getIndexTemplates(), hasSize(2)); - assertThat(getBoth.getIndexTemplates().stream().map(IndexTemplateMetadata::name).toArray(), - arrayContainingInAnyOrder("template-1", "template-2")); + assertThat( + getBoth.getIndexTemplates().stream().map(IndexTemplateMetadata::name).toArray(), + arrayContainingInAnyOrder("template-1", "template-2") + ); GetIndexTemplatesRequest getAllRequest = new GetIndexTemplatesRequest(); GetIndexTemplatesResponse getAll = execute( - getAllRequest, client.indices()::getIndexTemplate, client.indices()::getIndexTemplateAsync); + getAllRequest, + client.indices()::getIndexTemplate, + client.indices()::getIndexTemplateAsync + ); assertThat(getAll.getIndexTemplates().size(), greaterThanOrEqualTo(2)); - assertThat(getAll.getIndexTemplates().stream().map(IndexTemplateMetadata::name) - .collect(Collectors.toList()), - hasItems("template-1", "template-2")); + assertThat( + getAll.getIndexTemplates().stream().map(IndexTemplateMetadata::name).collect(Collectors.toList()), + hasItems("template-1", "template-2") + ); - assertTrue(execute(new DeleteIndexTemplateRequest("template-1"), - client.indices()::deleteTemplate, client.indices()::deleteTemplateAsync).isAcknowledged()); - assertThat(expectThrows(OpenSearchException.class, () -> execute(new GetIndexTemplatesRequest("template-1"), - client.indices()::getIndexTemplate, client.indices()::getIndexTemplateAsync)).status(), equalTo(RestStatus.NOT_FOUND)); - assertThat(expectThrows(OpenSearchException.class, () -> execute(new DeleteIndexTemplateRequest("template-1"), - client.indices()::deleteTemplate, client.indices()::deleteTemplateAsync)).status(), equalTo(RestStatus.NOT_FOUND)); + assertTrue( + execute(new DeleteIndexTemplateRequest("template-1"), client.indices()::deleteTemplate, client.indices()::deleteTemplateAsync) + .isAcknowledged() + ); + assertThat( + expectThrows( + OpenSearchException.class, + () -> execute( + new GetIndexTemplatesRequest("template-1"), + client.indices()::getIndexTemplate, + client.indices()::getIndexTemplateAsync + ) + ).status(), + equalTo(RestStatus.NOT_FOUND) + ); + assertThat( + expectThrows( + OpenSearchException.class, + () -> execute( + new DeleteIndexTemplateRequest("template-1"), + client.indices()::deleteTemplate, + client.indices()::deleteTemplateAsync + ) + ).status(), + equalTo(RestStatus.NOT_FOUND) + ); - assertThat(execute(new GetIndexTemplatesRequest("template-*"), - client.indices()::getIndexTemplate, client.indices()::getIndexTemplateAsync).getIndexTemplates(), hasSize(1)); - assertThat(execute(new GetIndexTemplatesRequest("template-*"), - client.indices()::getIndexTemplate, client.indices()::getIndexTemplateAsync).getIndexTemplates() - .get(0).name(), equalTo("template-2")); + assertThat( + execute(new GetIndexTemplatesRequest("template-*"), client.indices()::getIndexTemplate, client.indices()::getIndexTemplateAsync) + .getIndexTemplates(), + hasSize(1) + ); + assertThat( + execute(new GetIndexTemplatesRequest("template-*"), client.indices()::getIndexTemplate, client.indices()::getIndexTemplateAsync) + .getIndexTemplates() + .get(0) + .name(), + equalTo("template-2") + ); - assertTrue(execute(new DeleteIndexTemplateRequest("template-*"), - client.indices()::deleteTemplate, client.indices()::deleteTemplateAsync).isAcknowledged()); - assertThat(expectThrows(OpenSearchException.class, () -> execute(new GetIndexTemplatesRequest("template-*"), - client.indices()::getIndexTemplate, client.indices()::getIndexTemplateAsync)).status(), equalTo(RestStatus.NOT_FOUND)); + assertTrue( + execute(new DeleteIndexTemplateRequest("template-*"), client.indices()::deleteTemplate, client.indices()::deleteTemplateAsync) + .isAcknowledged() + ); + assertThat( + expectThrows( + OpenSearchException.class, + () -> execute( + new GetIndexTemplatesRequest("template-*"), + client.indices()::getIndexTemplate, + client.indices()::getIndexTemplateAsync + ) + ).status(), + equalTo(RestStatus.NOT_FOUND) + ); } public void testIndexTemplatesExist() throws Exception { @@ -1949,9 +2298,9 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { { for (String suffix : Arrays.asList("1", "2")) { - final PutIndexTemplateRequest putRequest = new PutIndexTemplateRequest("template-" + suffix) - .patterns(Arrays.asList("pattern-" + suffix, "name-" + suffix)) - .alias(new Alias("alias-" + suffix)); + final PutIndexTemplateRequest putRequest = new PutIndexTemplateRequest("template-" + suffix).patterns( + Arrays.asList("pattern-" + suffix, "name-" + suffix) + ).alias(new Alias("alias-" + suffix)); assertTrue(execute(putRequest, client.indices()::putTemplate, client.indices()::putTemplateAsync).isAcknowledged()); final IndexTemplatesExistRequest existsRequest = new IndexTemplatesExistRequest("template-" + suffix); @@ -1960,9 +2309,7 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { } { - final List templateNames = randomBoolean() - ? Arrays.asList("*plate-1", "template-2") - : Arrays.asList("template-*"); + final List templateNames = randomBoolean() ? Arrays.asList("*plate-1", "template-2") : Arrays.asList("template-*"); final IndexTemplatesExistRequest bothRequest = new IndexTemplatesExistRequest(templateNames); assertTrue(execute(bothRequest, client.indices()::existsTemplate, client.indices()::existsTemplateAsync)); @@ -1998,8 +2345,11 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { IndicesAliasesRequest aliasesAddRemoveRequest = new IndicesAliasesRequest(); aliasesAddRemoveRequest.addAliasAction(new AliasActions(AliasActions.Type.ADD).indices(index).alias(alias)); aliasesAddRemoveRequest.addAliasAction(new AliasActions(AliasActions.Type.ADD).indices(index).alias(alias + "2")); - AcknowledgedResponse aliasResponse = execute(aliasesAddRemoveRequest, highLevelClient().indices()::updateAliases, - highLevelClient().indices()::updateAliasesAsync); + AcknowledgedResponse aliasResponse = execute( + aliasesAddRemoveRequest, + highLevelClient().indices()::updateAliases, + highLevelClient().indices()::updateAliasesAsync + ); assertTrue(aliasResponse.isAcknowledged()); assertThat(aliasExists(alias), equalTo(true)); assertThat(aliasExists(alias2), equalTo(true)); @@ -2007,9 +2357,11 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { assertThat(aliasExists(index, alias2), equalTo(true)); DeleteAliasRequest request = new DeleteAliasRequest(index, alias); - org.opensearch.client.core.AcknowledgedResponse aliasDeleteResponse = execute(request, + org.opensearch.client.core.AcknowledgedResponse aliasDeleteResponse = execute( + request, highLevelClient().indices()::deleteAlias, - highLevelClient().indices()::deleteAliasAsync); + highLevelClient().indices()::deleteAliasAsync + ); assertThat(aliasExists(alias), equalTo(false)); assertThat(aliasExists(alias2), equalTo(true)); @@ -2023,21 +2375,30 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { CompressedXContent mappings = new CompressedXContent("{\"properties\":{\"@timestamp\":{\"type\":\"date\"}}}"); Template template = new Template(null, mappings, null); - ComposableIndexTemplate indexTemplate = new ComposableIndexTemplate(Collections.singletonList(dataStreamName), template, - Collections.emptyList(), 1L, 1L, new HashMap<>(), new ComposableIndexTemplate.DataStreamTemplate()); - PutComposableIndexTemplateRequest putComposableIndexTemplateRequest = - new PutComposableIndexTemplateRequest().name("ds-template").create(true).indexTemplate(indexTemplate); - AcknowledgedResponse response = execute(putComposableIndexTemplateRequest, - highLevelClient().indices()::putIndexTemplate, highLevelClient().indices()::putIndexTemplateAsync); + ComposableIndexTemplate indexTemplate = new ComposableIndexTemplate( + Collections.singletonList(dataStreamName), + template, + Collections.emptyList(), + 1L, + 1L, + new HashMap<>(), + new ComposableIndexTemplate.DataStreamTemplate() + ); + PutComposableIndexTemplateRequest putComposableIndexTemplateRequest = new PutComposableIndexTemplateRequest().name("ds-template") + .create(true) + .indexTemplate(indexTemplate); + AcknowledgedResponse response = execute( + putComposableIndexTemplateRequest, + highLevelClient().indices()::putIndexTemplate, + highLevelClient().indices()::putIndexTemplateAsync + ); assertThat(response.isAcknowledged(), equalTo(true)); CreateDataStreamRequest createDataStreamRequest = new CreateDataStreamRequest(dataStreamName); IndicesClient indices = highLevelClient().indices(); response = execute(createDataStreamRequest, indices::createDataStream, indices::createDataStreamAsync); assertThat(response.isAcknowledged(), equalTo(true)); - ensureHealth(dataStreamName, (request -> { - request.addParameter("wait_for_status", "yellow"); - })); + ensureHealth(dataStreamName, (request -> { request.addParameter("wait_for_status", "yellow"); })); GetDataStreamRequest getDataStreamRequest = new GetDataStreamRequest(dataStreamName); GetDataStreamResponse getDataStreamResponse = execute(getDataStreamRequest, indices::getDataStream, indices::getDataStreamAsync); @@ -2060,8 +2421,11 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { assertThat(dataStream.getIndices(), hasSize(1)); DataStreamsStatsRequest dataStreamsStatsRequest = new DataStreamsStatsRequest(); - DataStreamsStatsResponse dataStreamsStatsResponse = execute(dataStreamsStatsRequest, indices::dataStreamsStats, - indices::dataStreamsStatsAsync); + DataStreamsStatsResponse dataStreamsStatsResponse = execute( + dataStreamsStatsRequest, + indices::dataStreamsStats, + indices::dataStreamsStatsAsync + ); int dataStreamsCount = dataStreamsStatsResponse.getDataStreamCount(); assertThat(dataStreamsCount, equalTo(1)); int backingIndices = dataStreamsStatsResponse.getBackingIndices(); @@ -2090,8 +2454,10 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { getDataStreamRequest = new GetDataStreamRequest(dataStreamName); GetDataStreamRequest finalGetDataStreamRequest = getDataStreamRequest; - OpenSearchStatusException e = expectThrows(OpenSearchStatusException.class, () -> execute(finalGetDataStreamRequest, - indices::getDataStream, indices::getDataStreamAsync)); + OpenSearchStatusException e = expectThrows( + OpenSearchStatusException.class, + () -> execute(finalGetDataStreamRequest, indices::getDataStream, indices::getDataStreamAsync) + ); assertThat(e.status(), equalTo(RestStatus.NOT_FOUND)); } @@ -2102,42 +2468,70 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { AliasMetadata alias = AliasMetadata.builder("alias").writeIndex(true).build(); Template template = new Template(settings, mappings, Collections.singletonMap("alias", alias)); List pattern = Collections.singletonList("pattern"); - ComposableIndexTemplate indexTemplate = - new ComposableIndexTemplate(pattern, template, Collections.emptyList(), 1L, 1L, new HashMap<>(), null); - PutComposableIndexTemplateRequest putComposableIndexTemplateRequest = - new PutComposableIndexTemplateRequest().name(templateName).create(true).indexTemplate(indexTemplate); + ComposableIndexTemplate indexTemplate = new ComposableIndexTemplate( + pattern, + template, + Collections.emptyList(), + 1L, + 1L, + new HashMap<>(), + null + ); + PutComposableIndexTemplateRequest putComposableIndexTemplateRequest = new PutComposableIndexTemplateRequest().name(templateName) + .create(true) + .indexTemplate(indexTemplate); - AcknowledgedResponse response = execute(putComposableIndexTemplateRequest, - highLevelClient().indices()::putIndexTemplate, highLevelClient().indices()::putIndexTemplateAsync); + AcknowledgedResponse response = execute( + putComposableIndexTemplateRequest, + highLevelClient().indices()::putIndexTemplate, + highLevelClient().indices()::putIndexTemplateAsync + ); assertThat(response.isAcknowledged(), equalTo(true)); ComposableIndexTemplateExistRequest composableIndexTemplateExistRequest = new ComposableIndexTemplateExistRequest(templateName); - boolean exist = execute(composableIndexTemplateExistRequest, - highLevelClient().indices()::existsIndexTemplate, highLevelClient().indices()::existsIndexTemplateAsync); + boolean exist = execute( + composableIndexTemplateExistRequest, + highLevelClient().indices()::existsIndexTemplate, + highLevelClient().indices()::existsIndexTemplateAsync + ); assertTrue(exist); GetComposableIndexTemplateRequest getComposableIndexTemplateRequest = new GetComposableIndexTemplateRequest(templateName); - GetComposableIndexTemplatesResponse getResponse = execute(getComposableIndexTemplateRequest, - highLevelClient().indices()::getIndexTemplate, highLevelClient().indices()::getIndexTemplateAsync); + GetComposableIndexTemplatesResponse getResponse = execute( + getComposableIndexTemplateRequest, + highLevelClient().indices()::getIndexTemplate, + highLevelClient().indices()::getIndexTemplateAsync + ); assertThat(getResponse.getIndexTemplates().size(), equalTo(1)); assertThat(getResponse.getIndexTemplates().containsKey(templateName), equalTo(true)); assertThat(getResponse.getIndexTemplates().get(templateName), equalTo(indexTemplate)); DeleteComposableIndexTemplateRequest deleteComposableIndexTemplateRequest = new DeleteComposableIndexTemplateRequest(templateName); - response = execute(deleteComposableIndexTemplateRequest, highLevelClient().indices()::deleteIndexTemplate, - highLevelClient().indices()::deleteIndexTemplateAsync); + response = execute( + deleteComposableIndexTemplateRequest, + highLevelClient().indices()::deleteIndexTemplate, + highLevelClient().indices()::deleteIndexTemplateAsync + ); assertThat(response.isAcknowledged(), equalTo(true)); - OpenSearchStatusException statusException = expectThrows(OpenSearchStatusException.class, - () -> execute(getComposableIndexTemplateRequest, - highLevelClient().indices()::getIndexTemplate, highLevelClient().indices()::getIndexTemplateAsync)); + OpenSearchStatusException statusException = expectThrows( + OpenSearchStatusException.class, + () -> execute( + getComposableIndexTemplateRequest, + highLevelClient().indices()::getIndexTemplate, + highLevelClient().indices()::getIndexTemplateAsync + ) + ); assertThat(statusException.status(), equalTo(RestStatus.NOT_FOUND)); - exist = execute(composableIndexTemplateExistRequest, - highLevelClient().indices()::existsIndexTemplate, highLevelClient().indices()::existsIndexTemplateAsync); + exist = execute( + composableIndexTemplateExistRequest, + highLevelClient().indices()::existsIndexTemplate, + highLevelClient().indices()::existsIndexTemplateAsync + ); assertFalse(exist); } @@ -2149,34 +2543,61 @@ public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase { AliasMetadata alias = AliasMetadata.builder("alias").writeIndex(true).build(); Template template = new Template(settings, mappings, org.opensearch.common.collect.Map.of("alias", alias)); List pattern = org.opensearch.common.collect.List.of("pattern"); - ComposableIndexTemplate indexTemplate = - new ComposableIndexTemplate(pattern, template, Collections.emptyList(), 1L, 1L, new HashMap<>(), null); - PutComposableIndexTemplateRequest putComposableIndexTemplateRequest = - new PutComposableIndexTemplateRequest().name(templateName).create(true).indexTemplate(indexTemplate); + ComposableIndexTemplate indexTemplate = new ComposableIndexTemplate( + pattern, + template, + Collections.emptyList(), + 1L, + 1L, + new HashMap<>(), + null + ); + PutComposableIndexTemplateRequest putComposableIndexTemplateRequest = new PutComposableIndexTemplateRequest().name(templateName) + .create(true) + .indexTemplate(indexTemplate); - AcknowledgedResponse response = execute(putComposableIndexTemplateRequest, - highLevelClient().indices()::putIndexTemplate, highLevelClient().indices()::putIndexTemplateAsync); + AcknowledgedResponse response = execute( + putComposableIndexTemplateRequest, + highLevelClient().indices()::putIndexTemplate, + highLevelClient().indices()::putIndexTemplateAsync + ); assertThat(response.isAcknowledged(), equalTo(true)); SimulateIndexTemplateRequest simulateIndexTemplateRequest = new SimulateIndexTemplateRequest("pattern"); AliasMetadata simulationAlias = AliasMetadata.builder("simulation-alias").writeIndex(true).build(); - ComposableIndexTemplate simulationTemplate = new ComposableIndexTemplate(pattern, new Template(null, null, - org.opensearch.common.collect.Map.of("simulation-alias", simulationAlias)), Collections.emptyList(), 2L, 1L, - new HashMap<>(), null); - PutComposableIndexTemplateRequest newIndexTemplateReq = - new PutComposableIndexTemplateRequest().name("used-for-simulation").create(true).indexTemplate(indexTemplate); + ComposableIndexTemplate simulationTemplate = new ComposableIndexTemplate( + pattern, + new Template(null, null, org.opensearch.common.collect.Map.of("simulation-alias", simulationAlias)), + Collections.emptyList(), + 2L, + 1L, + new HashMap<>(), + null + ); + PutComposableIndexTemplateRequest newIndexTemplateReq = new PutComposableIndexTemplateRequest().name("used-for-simulation") + .create(true) + .indexTemplate(indexTemplate); newIndexTemplateReq.indexTemplate(simulationTemplate); simulateIndexTemplateRequest.indexTemplateV2Request(newIndexTemplateReq); - SimulateIndexTemplateResponse simulateResponse = execute(simulateIndexTemplateRequest, - highLevelClient().indices()::simulateIndexTemplate, highLevelClient().indices()::simulateIndexTemplateAsync); + SimulateIndexTemplateResponse simulateResponse = execute( + simulateIndexTemplateRequest, + highLevelClient().indices()::simulateIndexTemplate, + highLevelClient().indices()::simulateIndexTemplateAsync + ); Map aliases = simulateResponse.resolvedTemplate().aliases(); assertThat(aliases, is(notNullValue())); - assertThat("the template we provided for the simulation has a higher priority than the one in the system", - aliases.get("simulation-alias"), is(notNullValue())); + assertThat( + "the template we provided for the simulation has a higher priority than the one in the system", + aliases.get("simulation-alias"), + is(notNullValue()) + ); assertThat(aliases.get("simulation-alias").getAlias(), is("simulation-alias")); - assertThat("existing template overlaps the higher priority template we provided for the simulation", - simulateResponse.overlappingTemplates().get("my-template").get(0), is("pattern")); + assertThat( + "existing template overlaps the higher priority template we provided for the simulation", + simulateResponse.overlappingTemplates().get("my-template").get(0), + is("pattern") + ); } } diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/IndicesRequestConvertersTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/IndicesRequestConvertersTests.java index 12d03cf730b..28728a95ae9 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/IndicesRequestConvertersTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/IndicesRequestConvertersTests.java @@ -38,7 +38,6 @@ import org.apache.http.client.methods.HttpHead; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.lucene.util.LuceneTestCase; -import org.opensearch.client.Request; import org.opensearch.action.ActionRequestValidationException; import org.opensearch.action.admin.indices.alias.Alias; import org.opensearch.action.admin.indices.alias.IndicesAliasesRequest; @@ -105,8 +104,7 @@ import static org.hamcrest.Matchers.nullValue; public class IndicesRequestConvertersTests extends OpenSearchTestCase { public void testAnalyzeRequest() throws Exception { - AnalyzeRequest indexAnalyzeRequest - = AnalyzeRequest.withIndexAnalyzer("test_index", "test_analyzer", "Here is some text"); + AnalyzeRequest indexAnalyzeRequest = AnalyzeRequest.withIndexAnalyzer("test_index", "test_analyzer", "Here is some text"); Request request = IndicesRequestConverters.analyze(indexAnalyzeRequest); assertThat(request.getEndpoint(), equalTo("/test_index/_analyze")); @@ -136,24 +134,31 @@ public class IndicesRequestConvertersTests extends OpenSearchTestCase { } public void testIndicesExistEmptyIndices() { - LuceneTestCase.expectThrows(IllegalArgumentException.class, () - -> IndicesRequestConverters.indicesExist(new GetIndexRequest())); - LuceneTestCase.expectThrows(IllegalArgumentException.class, () - -> IndicesRequestConverters.indicesExist(new GetIndexRequest((String[]) null))); + LuceneTestCase.expectThrows(IllegalArgumentException.class, () -> IndicesRequestConverters.indicesExist(new GetIndexRequest())); + LuceneTestCase.expectThrows( + IllegalArgumentException.class, + () -> IndicesRequestConverters.indicesExist(new GetIndexRequest((String[]) null)) + ); } public void testIndicesExistEmptyIndicesWithTypes() { - LuceneTestCase.expectThrows(IllegalArgumentException.class, - () -> IndicesRequestConverters.indicesExist(new org.opensearch.action.admin.indices.get.GetIndexRequest())); - LuceneTestCase.expectThrows(IllegalArgumentException.class, () -> IndicesRequestConverters - .indicesExist(new org.opensearch.action.admin.indices.get.GetIndexRequest().indices((String[]) null))); + LuceneTestCase.expectThrows( + IllegalArgumentException.class, + () -> IndicesRequestConverters.indicesExist(new org.opensearch.action.admin.indices.get.GetIndexRequest()) + ); + LuceneTestCase.expectThrows( + IllegalArgumentException.class, + () -> IndicesRequestConverters.indicesExist( + new org.opensearch.action.admin.indices.get.GetIndexRequest().indices((String[]) null) + ) + ); } public void testIndicesExistWithTypes() { String[] indices = RequestConvertersTests.randomIndicesNames(1, 10); org.opensearch.action.admin.indices.get.GetIndexRequest getIndexRequest = - new org.opensearch.action.admin.indices.get.GetIndexRequest().indices(indices); + new org.opensearch.action.admin.indices.get.GetIndexRequest().indices(indices); Map expectedParams = new HashMap<>(); RequestConvertersTests.setRandomIndicesOptions(getIndexRequest::indicesOptions, getIndexRequest::indicesOptions, expectedParams); @@ -186,8 +191,8 @@ public class IndicesRequestConvertersTests extends OpenSearchTestCase { } public void testCreateIndexWithTypes() throws IOException { - org.opensearch.action.admin.indices.create.CreateIndexRequest createIndexRequest = - org.opensearch.index.RandomCreateIndexGenerator.randomCreateIndexRequest(); + org.opensearch.action.admin.indices.create.CreateIndexRequest createIndexRequest = org.opensearch.index.RandomCreateIndexGenerator + .randomCreateIndexRequest(); Map expectedParams = new HashMap<>(); RequestConvertersTests.setRandomTimeout(createIndexRequest::timeout, AcknowledgedRequest.DEFAULT_ACK_TIMEOUT, expectedParams); @@ -229,8 +234,11 @@ public class IndicesRequestConvertersTests extends OpenSearchTestCase { Map expectedParams = new HashMap<>(); RequestConvertersTests.setRandomTimeout(putMappingRequest, AcknowledgedRequest.DEFAULT_ACK_TIMEOUT, expectedParams); RequestConvertersTests.setRandomMasterTimeout(putMappingRequest, expectedParams); - RequestConvertersTests.setRandomIndicesOptions(putMappingRequest::indicesOptions, - putMappingRequest::indicesOptions, expectedParams); + RequestConvertersTests.setRandomIndicesOptions( + putMappingRequest::indicesOptions, + putMappingRequest::indicesOptions, + expectedParams + ); Request request = IndicesRequestConverters.putMapping(putMappingRequest); @@ -290,8 +298,11 @@ public class IndicesRequestConvertersTests extends OpenSearchTestCase { } Map expectedParams = new HashMap<>(); - RequestConvertersTests.setRandomIndicesOptions(getMappingRequest::indicesOptions, - getMappingRequest::indicesOptions, expectedParams); + RequestConvertersTests.setRandomIndicesOptions( + getMappingRequest::indicesOptions, + getMappingRequest::indicesOptions, + expectedParams + ); RequestConvertersTests.setRandomMasterTimeout(getMappingRequest, expectedParams); RequestConvertersTests.setRandomLocal(getMappingRequest::local, expectedParams); @@ -330,8 +341,11 @@ public class IndicesRequestConvertersTests extends OpenSearchTestCase { Map expectedParams = new HashMap<>(); - RequestConvertersTests.setRandomIndicesOptions(getMappingRequest::indicesOptions, - getMappingRequest::indicesOptions, expectedParams); + RequestConvertersTests.setRandomIndicesOptions( + getMappingRequest::indicesOptions, + getMappingRequest::indicesOptions, + expectedParams + ); RequestConvertersTests.setRandomMasterTimeout(getMappingRequest, expectedParams); RequestConvertersTests.setRandomLocal(getMappingRequest::local, expectedParams); expectedParams.put(INCLUDE_TYPE_NAME_PARAMETER, "true"); @@ -375,8 +389,11 @@ public class IndicesRequestConvertersTests extends OpenSearchTestCase { } Map expectedParams = new HashMap<>(); - RequestConvertersTests.setRandomIndicesOptions(getFieldMappingsRequest::indicesOptions, getFieldMappingsRequest::indicesOptions, - expectedParams); + RequestConvertersTests.setRandomIndicesOptions( + getFieldMappingsRequest::indicesOptions, + getFieldMappingsRequest::indicesOptions, + expectedParams + ); Request request = IndicesRequestConverters.getFieldMapping(getFieldMappingsRequest); StringJoiner endpoint = new StringJoiner("/", "/", ""); @@ -427,8 +444,11 @@ public class IndicesRequestConvertersTests extends OpenSearchTestCase { Map expectedParams = new HashMap<>(); - RequestConvertersTests.setRandomIndicesOptions(getFieldMappingsRequest::indicesOptions, getFieldMappingsRequest::indicesOptions, - expectedParams); + RequestConvertersTests.setRandomIndicesOptions( + getFieldMappingsRequest::indicesOptions, + getFieldMappingsRequest::indicesOptions, + expectedParams + ); RequestConvertersTests.setRandomLocal(getFieldMappingsRequest::local, expectedParams); expectedParams.put(INCLUDE_TYPE_NAME_PARAMETER, "true"); @@ -487,8 +507,11 @@ public class IndicesRequestConvertersTests extends OpenSearchTestCase { RequestConvertersTests.setRandomTimeout(deleteIndexRequest::timeout, AcknowledgedRequest.DEFAULT_ACK_TIMEOUT, expectedParams); RequestConvertersTests.setRandomMasterTimeout(deleteIndexRequest, expectedParams); - RequestConvertersTests.setRandomIndicesOptions(deleteIndexRequest::indicesOptions, deleteIndexRequest::indicesOptions, - expectedParams); + RequestConvertersTests.setRandomIndicesOptions( + deleteIndexRequest::indicesOptions, + deleteIndexRequest::indicesOptions, + expectedParams + ); Request request = IndicesRequestConverters.deleteIndex(deleteIndexRequest); Assert.assertEquals("/" + String.join(",", indices), request.getEndpoint()); @@ -504,8 +527,11 @@ public class IndicesRequestConvertersTests extends OpenSearchTestCase { Map expectedParams = new HashMap<>(); RequestConvertersTests.setRandomMasterTimeout(getSettingsRequest, expectedParams); - RequestConvertersTests.setRandomIndicesOptions(getSettingsRequest::indicesOptions, getSettingsRequest::indicesOptions, - expectedParams); + RequestConvertersTests.setRandomIndicesOptions( + getSettingsRequest::indicesOptions, + getSettingsRequest::indicesOptions, + expectedParams + ); RequestConvertersTests.setRandomLocal(getSettingsRequest::local, expectedParams); @@ -582,7 +608,7 @@ public class IndicesRequestConvertersTests extends OpenSearchTestCase { String[] indicesUnderTest = OpenSearchTestCase.randomBoolean() ? null : RequestConvertersTests.randomIndicesNames(0, 5); org.opensearch.action.admin.indices.get.GetIndexRequest getIndexRequest = - new org.opensearch.action.admin.indices.get.GetIndexRequest().indices(indicesUnderTest); + new org.opensearch.action.admin.indices.get.GetIndexRequest().indices(indicesUnderTest); Map expectedParams = new HashMap<>(); RequestConvertersTests.setRandomMasterTimeout(getIndexRequest, expectedParams); @@ -649,11 +675,17 @@ public class IndicesRequestConvertersTests extends OpenSearchTestCase { CloseIndexRequest closeIndexRequest = new CloseIndexRequest(indices); Map expectedParams = new HashMap<>(); - RequestConvertersTests.setRandomTimeout(timeout -> closeIndexRequest.setTimeout(TimeValue.parseTimeValue(timeout, "test")), - AcknowledgedRequest.DEFAULT_ACK_TIMEOUT, expectedParams); + RequestConvertersTests.setRandomTimeout( + timeout -> closeIndexRequest.setTimeout(TimeValue.parseTimeValue(timeout, "test")), + AcknowledgedRequest.DEFAULT_ACK_TIMEOUT, + expectedParams + ); RequestConvertersTests.setRandomMasterTimeout(closeIndexRequest, expectedParams); - RequestConvertersTests.setRandomIndicesOptions(closeIndexRequest::indicesOptions, closeIndexRequest::indicesOptions, - expectedParams); + RequestConvertersTests.setRandomIndicesOptions( + closeIndexRequest::indicesOptions, + closeIndexRequest::indicesOptions, + expectedParams + ); Request request = IndicesRequestConverters.closeIndex(closeIndexRequest); StringJoiner endpoint = new StringJoiner("/", "/", "").add(String.join(",", indices)).add("_close"); @@ -728,13 +760,16 @@ public class IndicesRequestConvertersTests extends OpenSearchTestCase { syncedFlushRequest.indices(indices); } Map expectedParams = new HashMap<>(); - RequestConvertersTests.setRandomIndicesOptions(syncedFlushRequest::indicesOptions, syncedFlushRequest::indicesOptions, - expectedParams); + RequestConvertersTests.setRandomIndicesOptions( + syncedFlushRequest::indicesOptions, + syncedFlushRequest::indicesOptions, + expectedParams + ); Request request = IndicesRequestConverters.flushSynced(syncedFlushRequest); StringJoiner endpoint = new StringJoiner("/", "/", ""); if (indices != null && indices.length > 0) { - endpoint.add(String.join(",", indices)); - } + endpoint.add(String.join(",", indices)); + } endpoint.add("_flush/synced"); Assert.assertThat(request.getEndpoint(), equalTo(endpoint.toString())); Assert.assertThat(request.getParameters(), equalTo(expectedParams)); @@ -753,8 +788,11 @@ public class IndicesRequestConvertersTests extends OpenSearchTestCase { } Map expectedParams = new HashMap<>(); - RequestConvertersTests.setRandomIndicesOptions(forceMergeRequest::indicesOptions, forceMergeRequest::indicesOptions, - expectedParams); + RequestConvertersTests.setRandomIndicesOptions( + forceMergeRequest::indicesOptions, + forceMergeRequest::indicesOptions, + expectedParams + ); if (OpenSearchTestCase.randomBoolean()) { forceMergeRequest.maxNumSegments(OpenSearchTestCase.randomInt()); } @@ -790,8 +828,11 @@ public class IndicesRequestConvertersTests extends OpenSearchTestCase { clearIndicesCacheRequest.indices(indices); } Map expectedParams = new HashMap<>(); - RequestConvertersTests.setRandomIndicesOptions(clearIndicesCacheRequest::indicesOptions, clearIndicesCacheRequest::indicesOptions, - expectedParams); + RequestConvertersTests.setRandomIndicesOptions( + clearIndicesCacheRequest::indicesOptions, + clearIndicesCacheRequest::indicesOptions, + expectedParams + ); if (OpenSearchTestCase.randomBoolean()) { clearIndicesCacheRequest.queryCache(OpenSearchTestCase.randomBoolean()); } @@ -836,8 +877,11 @@ public class IndicesRequestConvertersTests extends OpenSearchTestCase { getAliasesRequest.aliases(aliases); Map expectedParams = new HashMap<>(); RequestConvertersTests.setRandomLocal(getAliasesRequest::local, expectedParams); - RequestConvertersTests.setRandomIndicesOptions(getAliasesRequest::indicesOptions, getAliasesRequest::indicesOptions, - expectedParams); + RequestConvertersTests.setRandomIndicesOptions( + getAliasesRequest::indicesOptions, + getAliasesRequest::indicesOptions, + expectedParams + ); Request request = IndicesRequestConverters.existsAlias(getAliasesRequest); StringJoiner expectedEndpoint = new StringJoiner("/", "/", ""); @@ -857,15 +901,19 @@ public class IndicesRequestConvertersTests extends OpenSearchTestCase { public void testExistsAliasNoAliasNoIndex() { { GetAliasesRequest getAliasesRequest = new GetAliasesRequest(); - IllegalArgumentException iae = LuceneTestCase.expectThrows(IllegalArgumentException.class, - () -> IndicesRequestConverters.existsAlias(getAliasesRequest)); + IllegalArgumentException iae = LuceneTestCase.expectThrows( + IllegalArgumentException.class, + () -> IndicesRequestConverters.existsAlias(getAliasesRequest) + ); Assert.assertEquals("existsAlias requires at least an alias or an index", iae.getMessage()); } { GetAliasesRequest getAliasesRequest = new GetAliasesRequest((String[]) null); getAliasesRequest.indices((String[]) null); - IllegalArgumentException iae = LuceneTestCase.expectThrows(IllegalArgumentException.class, - () -> IndicesRequestConverters.existsAlias(getAliasesRequest)); + IllegalArgumentException iae = LuceneTestCase.expectThrows( + IllegalArgumentException.class, + () -> IndicesRequestConverters.existsAlias(getAliasesRequest) + ); Assert.assertEquals("existsAlias requires at least an alias or an index", iae.getMessage()); } } @@ -882,14 +930,16 @@ public class IndicesRequestConvertersTests extends OpenSearchTestCase { resizeTest(ResizeType.SHRINK, IndicesRequestConverters::shrink); } - private void resizeTest(ResizeType resizeType, CheckedFunction function) - throws IOException { + private void resizeTest(ResizeType resizeType, CheckedFunction function) throws IOException { String[] indices = RequestConvertersTests.randomIndicesNames(2, 2); ResizeRequest resizeRequest = new ResizeRequest(indices[0], indices[1]); Map expectedParams = new HashMap<>(); RequestConvertersTests.setRandomMasterTimeout(resizeRequest, expectedParams); - RequestConvertersTests.setRandomTimeout(s -> resizeRequest.setTimeout(TimeValue.parseTimeValue(s, "timeout")), - resizeRequest.timeout(), expectedParams); + RequestConvertersTests.setRandomTimeout( + s -> resizeRequest.setTimeout(TimeValue.parseTimeValue(s, "timeout")), + resizeRequest.timeout(), + expectedParams + ); if (OpenSearchTestCase.randomBoolean()) { if (OpenSearchTestCase.randomBoolean()) { @@ -909,16 +959,22 @@ public class IndicesRequestConvertersTests extends OpenSearchTestCase { Request request = function.apply(resizeRequest); Assert.assertEquals(HttpPut.METHOD_NAME, request.getMethod()); - String expectedEndpoint = "/" + resizeRequest.getSourceIndex() + "/_" + resizeType.name().toLowerCase(Locale.ROOT) + "/" - + resizeRequest.getTargetIndex(); + String expectedEndpoint = "/" + + resizeRequest.getSourceIndex() + + "/_" + + resizeType.name().toLowerCase(Locale.ROOT) + + "/" + + resizeRequest.getTargetIndex(); Assert.assertEquals(expectedEndpoint, request.getEndpoint()); Assert.assertEquals(expectedParams, request.getParameters()); RequestConvertersTests.assertToXContentBody(resizeRequest, request.getEntity()); } public void testRollover() throws IOException { - RolloverRequest rolloverRequest = new RolloverRequest(OpenSearchTestCase.randomAlphaOfLengthBetween(3, 10), - OpenSearchTestCase.randomBoolean() ? null : OpenSearchTestCase.randomAlphaOfLengthBetween(3, 10)); + RolloverRequest rolloverRequest = new RolloverRequest( + OpenSearchTestCase.randomAlphaOfLengthBetween(3, 10), + OpenSearchTestCase.randomBoolean() ? null : OpenSearchTestCase.randomAlphaOfLengthBetween(3, 10) + ); Map expectedParams = new HashMap<>(); RequestConvertersTests.setRandomTimeout(rolloverRequest, AcknowledgedRequest.DEFAULT_ACK_TIMEOUT, expectedParams); RequestConvertersTests.setRandomMasterTimeout(rolloverRequest, expectedParams); @@ -938,8 +994,7 @@ public class IndicesRequestConvertersTests extends OpenSearchTestCase { randomAliases(rolloverRequest.getCreateIndexRequest()); } if (OpenSearchTestCase.randomBoolean()) { - rolloverRequest.getCreateIndexRequest().settings( - org.opensearch.index.RandomCreateIndexGenerator.randomIndexSettings()); + rolloverRequest.getCreateIndexRequest().settings(org.opensearch.index.RandomCreateIndexGenerator.randomIndexSettings()); } RequestConvertersTests.setRandomWaitForActiveShards(rolloverRequest.getCreateIndexRequest()::waitForActiveShards, expectedParams); @@ -947,8 +1002,10 @@ public class IndicesRequestConvertersTests extends OpenSearchTestCase { if (rolloverRequest.getNewIndexName() == null) { Assert.assertEquals("/" + rolloverRequest.getAlias() + "/_rollover", request.getEndpoint()); } else { - Assert.assertEquals("/" + rolloverRequest.getAlias() + "/_rollover/" + rolloverRequest.getNewIndexName(), - request.getEndpoint()); + Assert.assertEquals( + "/" + rolloverRequest.getAlias() + "/_rollover/" + rolloverRequest.getNewIndexName(), + request.getEndpoint() + ); } Assert.assertEquals(HttpPost.METHOD_NAME, request.getMethod()); RequestConvertersTests.assertToXContentBody(rolloverRequest, request.getEntity()); @@ -957,8 +1014,10 @@ public class IndicesRequestConvertersTests extends OpenSearchTestCase { public void testRolloverWithTypes() throws IOException { org.opensearch.action.admin.indices.rollover.RolloverRequest rolloverRequest = - new org.opensearch.action.admin.indices.rollover.RolloverRequest(OpenSearchTestCase.randomAlphaOfLengthBetween(3, 10), - OpenSearchTestCase.randomBoolean() ? null : OpenSearchTestCase.randomAlphaOfLengthBetween(3, 10)); + new org.opensearch.action.admin.indices.rollover.RolloverRequest( + OpenSearchTestCase.randomAlphaOfLengthBetween(3, 10), + OpenSearchTestCase.randomBoolean() ? null : OpenSearchTestCase.randomAlphaOfLengthBetween(3, 10) + ); Map expectedParams = new HashMap<>(); RequestConvertersTests.setRandomTimeout(rolloverRequest::timeout, rolloverRequest.timeout(), expectedParams); RequestConvertersTests.setRandomMasterTimeout(rolloverRequest, expectedParams); @@ -974,15 +1033,13 @@ public class IndicesRequestConvertersTests extends OpenSearchTestCase { } if (OpenSearchTestCase.randomBoolean()) { String type = OpenSearchTestCase.randomAlphaOfLengthBetween(3, 10); - rolloverRequest.getCreateIndexRequest().mapping(type, - org.opensearch.index.RandomCreateIndexGenerator.randomMapping(type)); + rolloverRequest.getCreateIndexRequest().mapping(type, org.opensearch.index.RandomCreateIndexGenerator.randomMapping(type)); } if (OpenSearchTestCase.randomBoolean()) { org.opensearch.index.RandomCreateIndexGenerator.randomAliases(rolloverRequest.getCreateIndexRequest()); } if (OpenSearchTestCase.randomBoolean()) { - rolloverRequest.getCreateIndexRequest().settings( - org.opensearch.index.RandomCreateIndexGenerator.randomIndexSettings()); + rolloverRequest.getCreateIndexRequest().settings(org.opensearch.index.RandomCreateIndexGenerator.randomIndexSettings()); } RequestConvertersTests.setRandomWaitForActiveShards(rolloverRequest.getCreateIndexRequest()::waitForActiveShards, expectedParams); @@ -990,8 +1047,10 @@ public class IndicesRequestConvertersTests extends OpenSearchTestCase { if (rolloverRequest.getNewIndexName() == null) { Assert.assertEquals("/" + rolloverRequest.getRolloverTarget() + "/_rollover", request.getEndpoint()); } else { - Assert.assertEquals("/" + rolloverRequest.getRolloverTarget() + "/_rollover/" + rolloverRequest.getNewIndexName(), - request.getEndpoint()); + Assert.assertEquals( + "/" + rolloverRequest.getRolloverTarget() + "/_rollover/" + rolloverRequest.getNewIndexName(), + request.getEndpoint() + ); } Assert.assertEquals(HttpPost.METHOD_NAME, request.getMethod()); RequestConvertersTests.assertToXContentBody(rolloverRequest, request.getEntity()); @@ -1003,8 +1062,11 @@ public class IndicesRequestConvertersTests extends OpenSearchTestCase { Map expectedParams = new HashMap<>(); RequestConvertersTests.setRandomLocal(getAliasesRequest::local, expectedParams); - RequestConvertersTests.setRandomIndicesOptions(getAliasesRequest::indicesOptions, getAliasesRequest::indicesOptions, - expectedParams); + RequestConvertersTests.setRandomIndicesOptions( + getAliasesRequest::indicesOptions, + getAliasesRequest::indicesOptions, + expectedParams + ); String[] indices = OpenSearchTestCase.randomBoolean() ? null : RequestConvertersTests.randomIndicesNames(0, 2); String[] aliases = OpenSearchTestCase.randomBoolean() ? null : RequestConvertersTests.randomIndicesNames(0, 2); @@ -1035,8 +1097,11 @@ public class IndicesRequestConvertersTests extends OpenSearchTestCase { Map expectedParams = new HashMap<>(); RequestConvertersTests.setRandomMasterTimeout(updateSettingsRequest, expectedParams); RequestConvertersTests.setRandomTimeout(updateSettingsRequest::timeout, AcknowledgedRequest.DEFAULT_ACK_TIMEOUT, expectedParams); - RequestConvertersTests.setRandomIndicesOptions(updateSettingsRequest::indicesOptions, updateSettingsRequest::indicesOptions, - expectedParams); + RequestConvertersTests.setRandomIndicesOptions( + updateSettingsRequest::indicesOptions, + updateSettingsRequest::indicesOptions, + expectedParams + ); if (OpenSearchTestCase.randomBoolean()) { updateSettingsRequest.setPreserveExisting(OpenSearchTestCase.randomBoolean()); if (updateSettingsRequest.isPreserveExisting()) { @@ -1064,9 +1129,9 @@ public class IndicesRequestConvertersTests extends OpenSearchTestCase { names.put("foo^bar", "foo%5Ebar"); org.opensearch.action.admin.indices.template.put.PutIndexTemplateRequest putTemplateRequest = - new org.opensearch.action.admin.indices.template.put.PutIndexTemplateRequest() - .name(OpenSearchTestCase.randomFrom(names.keySet())) - .patterns(Arrays.asList(OpenSearchTestCase.generateRandomStringArray(20, 100, false, false))); + new org.opensearch.action.admin.indices.template.put.PutIndexTemplateRequest().name( + OpenSearchTestCase.randomFrom(names.keySet()) + ).patterns(Arrays.asList(OpenSearchTestCase.generateRandomStringArray(20, 100, false, false))); if (OpenSearchTestCase.randomBoolean()) { putTemplateRequest.order(OpenSearchTestCase.randomInt()); } @@ -1075,12 +1140,16 @@ public class IndicesRequestConvertersTests extends OpenSearchTestCase { } if (OpenSearchTestCase.randomBoolean()) { putTemplateRequest.settings( - Settings.builder().put("setting-" + OpenSearchTestCase.randomInt(), OpenSearchTestCase.randomTimeValue())); + Settings.builder().put("setting-" + OpenSearchTestCase.randomInt(), OpenSearchTestCase.randomTimeValue()) + ); } Map expectedParams = new HashMap<>(); if (OpenSearchTestCase.randomBoolean()) { - putTemplateRequest.mapping("doc-" + OpenSearchTestCase.randomInt(), - "field-" + OpenSearchTestCase.randomInt(), "type=" + OpenSearchTestCase.randomFrom("text", "keyword")); + putTemplateRequest.mapping( + "doc-" + OpenSearchTestCase.randomInt(), + "field-" + OpenSearchTestCase.randomInt(), + "type=" + OpenSearchTestCase.randomFrom("text", "keyword") + ); } expectedParams.put(INCLUDE_TYPE_NAME_PARAMETER, "true"); if (OpenSearchTestCase.randomBoolean()) { @@ -1110,9 +1179,9 @@ public class IndicesRequestConvertersTests extends OpenSearchTestCase { names.put("-#template", "-%23template"); names.put("foo^bar", "foo%5Ebar"); - PutIndexTemplateRequest putTemplateRequest = - new PutIndexTemplateRequest(OpenSearchTestCase.randomFrom(names.keySet())) - .patterns(Arrays.asList(OpenSearchTestCase.generateRandomStringArray(20, 100, false, false))); + PutIndexTemplateRequest putTemplateRequest = new PutIndexTemplateRequest(OpenSearchTestCase.randomFrom(names.keySet())).patterns( + Arrays.asList(OpenSearchTestCase.generateRandomStringArray(20, 100, false, false)) + ); if (OpenSearchTestCase.randomBoolean()) { putTemplateRequest.order(OpenSearchTestCase.randomInt()); } @@ -1121,12 +1190,19 @@ public class IndicesRequestConvertersTests extends OpenSearchTestCase { } if (OpenSearchTestCase.randomBoolean()) { putTemplateRequest.settings( - Settings.builder().put("setting-" + OpenSearchTestCase.randomInt(), OpenSearchTestCase.randomTimeValue())); + Settings.builder().put("setting-" + OpenSearchTestCase.randomInt(), OpenSearchTestCase.randomTimeValue()) + ); } Map expectedParams = new HashMap<>(); if (OpenSearchTestCase.randomBoolean()) { - putTemplateRequest.mapping("{ \"properties\": { \"field-" + OpenSearchTestCase.randomInt() + - "\" : { \"type\" : \"" + OpenSearchTestCase.randomFrom("text", "keyword") + "\" }}}", XContentType.JSON); + putTemplateRequest.mapping( + "{ \"properties\": { \"field-" + + OpenSearchTestCase.randomInt() + + "\" : { \"type\" : \"" + + OpenSearchTestCase.randomFrom("text", "keyword") + + "\" }}}", + XContentType.JSON + ); } if (OpenSearchTestCase.randomBoolean()) { putTemplateRequest.alias(new Alias("alias-" + OpenSearchTestCase.randomInt())); @@ -1147,6 +1223,7 @@ public class IndicesRequestConvertersTests extends OpenSearchTestCase { Assert.assertThat(request.getParameters(), equalTo(expectedParams)); RequestConvertersTests.assertToXContentBody(putTemplateRequest, request.getEntity()); } + public void testValidateQuery() throws Exception { String[] indices = OpenSearchTestCase.randomBoolean() ? null : RequestConvertersTests.randomIndicesNames(0, 5); String[] types = OpenSearchTestCase.randomBoolean() ? OpenSearchTestCase.generateRandomStringArray(5, 5, false, false) : null; @@ -1159,8 +1236,11 @@ public class IndicesRequestConvertersTests extends OpenSearchTestCase { } validateQueryRequest.types(types); Map expectedParams = new HashMap<>(); - RequestConvertersTests.setRandomIndicesOptions(validateQueryRequest::indicesOptions, validateQueryRequest::indicesOptions, - expectedParams); + RequestConvertersTests.setRandomIndicesOptions( + validateQueryRequest::indicesOptions, + validateQueryRequest::indicesOptions, + expectedParams + ); validateQueryRequest.explain(OpenSearchTestCase.randomBoolean()); validateQueryRequest.rewrite(OpenSearchTestCase.randomBoolean()); validateQueryRequest.allShards(OpenSearchTestCase.randomBoolean()); @@ -1197,8 +1277,10 @@ public class IndicesRequestConvertersTests extends OpenSearchTestCase { Request request = IndicesRequestConverters.getTemplatesWithDocumentTypes(getTemplatesRequest); expectedParams.put(INCLUDE_TYPE_NAME_PARAMETER, "true"); - Assert.assertThat(request.getEndpoint(), - equalTo("/_template/" + names.stream().map(encodes::get).collect(Collectors.joining(",")))); + Assert.assertThat( + request.getEndpoint(), + equalTo("/_template/" + names.stream().map(encodes::get).collect(Collectors.joining(","))) + ); Assert.assertThat(request.getParameters(), equalTo(expectedParams)); Assert.assertThat(request.getEntity(), nullValue()); @@ -1209,11 +1291,15 @@ public class IndicesRequestConvertersTests extends OpenSearchTestCase { } public void testTemplatesExistRequest() { - final int numberOfNames = OpenSearchTestCase.usually() - ? 1 - : OpenSearchTestCase.randomIntBetween(2, 20); - final List names = Arrays.asList(OpenSearchTestCase.randomArray(numberOfNames, numberOfNames, String[]::new, - () -> OpenSearchTestCase.randomAlphaOfLengthBetween(1, 100))); + final int numberOfNames = OpenSearchTestCase.usually() ? 1 : OpenSearchTestCase.randomIntBetween(2, 20); + final List names = Arrays.asList( + OpenSearchTestCase.randomArray( + numberOfNames, + numberOfNames, + String[]::new, + () -> OpenSearchTestCase.randomAlphaOfLengthBetween(1, 100) + ) + ); final Map expectedParams = new HashMap<>(); final IndexTemplatesExistRequest indexTemplatesExistRequest = new IndexTemplatesExistRequest(names); RequestConvertersTests.setRandomMasterTimeout(indexTemplatesExistRequest::setMasterNodeTimeout, expectedParams); diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/IngestClientIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/IngestClientIT.java index 1ce7c8cc831..78a3202f358 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/IngestClientIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/IngestClientIT.java @@ -58,13 +58,13 @@ public class IngestClientIT extends OpenSearchRestHighLevelClientTestCase { public void testPutPipeline() throws IOException { String id = "some_pipeline_id"; XContentBuilder pipelineBuilder = buildRandomXContentPipeline(); - PutPipelineRequest request = new PutPipelineRequest( - id, - BytesReference.bytes(pipelineBuilder), - pipelineBuilder.contentType()); + PutPipelineRequest request = new PutPipelineRequest(id, BytesReference.bytes(pipelineBuilder), pipelineBuilder.contentType()); - AcknowledgedResponse putPipelineResponse = - execute(request, highLevelClient().ingest()::putPipeline, highLevelClient().ingest()::putPipelineAsync); + AcknowledgedResponse putPipelineResponse = execute( + request, + highLevelClient().ingest()::putPipeline, + highLevelClient().ingest()::putPipelineAsync + ); assertTrue(putPipelineResponse.isAcknowledged()); } @@ -72,22 +72,24 @@ public class IngestClientIT extends OpenSearchRestHighLevelClientTestCase { String id = "some_pipeline_id"; XContentBuilder pipelineBuilder = buildRandomXContentPipeline(); { - PutPipelineRequest request = new PutPipelineRequest( - id, - BytesReference.bytes(pipelineBuilder), - pipelineBuilder.contentType() - ); + PutPipelineRequest request = new PutPipelineRequest(id, BytesReference.bytes(pipelineBuilder), pipelineBuilder.contentType()); createPipeline(request); } GetPipelineRequest request = new GetPipelineRequest(id); - GetPipelineResponse response = - execute(request, highLevelClient().ingest()::getPipeline, highLevelClient().ingest()::getPipelineAsync); + GetPipelineResponse response = execute( + request, + highLevelClient().ingest()::getPipeline, + highLevelClient().ingest()::getPipelineAsync + ); assertTrue(response.isFound()); assertEquals(response.pipelines().get(0).getId(), id); - PipelineConfiguration expectedConfig = - new PipelineConfiguration(id, BytesReference.bytes(pipelineBuilder), pipelineBuilder.contentType()); + PipelineConfiguration expectedConfig = new PipelineConfiguration( + id, + BytesReference.bytes(pipelineBuilder), + pipelineBuilder.contentType() + ); assertEquals(expectedConfig.getConfigAsMap(), response.pipelines().get(0).getConfigAsMap()); } @@ -96,8 +98,11 @@ public class IngestClientIT extends OpenSearchRestHighLevelClientTestCase { GetPipelineRequest request = new GetPipelineRequest(id); - GetPipelineResponse response = - execute(request, highLevelClient().ingest()::getPipeline, highLevelClient().ingest()::getPipelineAsync); + GetPipelineResponse response = execute( + request, + highLevelClient().ingest()::getPipeline, + highLevelClient().ingest()::getPipelineAsync + ); assertFalse(response.isFound()); } @@ -109,8 +114,11 @@ public class IngestClientIT extends OpenSearchRestHighLevelClientTestCase { DeletePipelineRequest request = new DeletePipelineRequest(id); - AcknowledgedResponse response = - execute(request, highLevelClient().ingest()::deletePipeline, highLevelClient().ingest()::deletePipelineAsync); + AcknowledgedResponse response = execute( + request, + highLevelClient().ingest()::deletePipeline, + highLevelClient().ingest()::deletePipelineAsync + ); assertTrue(response.isAcknowledged()); } @@ -130,8 +138,7 @@ public class IngestClientIT extends OpenSearchRestHighLevelClientTestCase { testSimulatePipeline(true, true); } - private void testSimulatePipeline(boolean isVerbose, - boolean isFailure) throws IOException { + private void testSimulatePipeline(boolean isVerbose, boolean isFailure) throws IOException { XContentType xContentType = randomFrom(XContentType.values()); XContentBuilder builder = XContentBuilder.builder(xContentType.xContent()); String rankValue = isFailure ? "non-int" : Integer.toString(1234); @@ -144,20 +151,23 @@ public class IngestClientIT extends OpenSearchRestHighLevelClientTestCase { builder.startObject() .field("_index", "index") .field("_id", "doc_" + 1) - .startObject("_source").field("foo", "rab_" + 1).field("rank", rankValue).endObject() + .startObject("_source") + .field("foo", "rab_" + 1) + .field("rank", rankValue) + .endObject() .endObject(); } builder.endArray(); } builder.endObject(); - SimulatePipelineRequest request = new SimulatePipelineRequest( - BytesReference.bytes(builder), - builder.contentType() - ); + SimulatePipelineRequest request = new SimulatePipelineRequest(BytesReference.bytes(builder), builder.contentType()); request.setVerbose(isVerbose); - SimulatePipelineResponse response = - execute(request, highLevelClient().ingest()::simulate, highLevelClient().ingest()::simulateAsync); + SimulatePipelineResponse response = execute( + request, + highLevelClient().ingest()::simulate, + highLevelClient().ingest()::simulateAsync + ); List results = response.getResults(); assertEquals(1, results.size()); if (isVerbose) { @@ -166,38 +176,27 @@ public class IngestClientIT extends OpenSearchRestHighLevelClientTestCase { assertEquals(2, verboseResult.getProcessorResults().size()); if (isFailure) { assertNotNull(verboseResult.getProcessorResults().get(1).getFailure()); - assertThat(verboseResult.getProcessorResults().get(1).getFailure().getMessage(), - containsString("unable to convert [non-int] to integer")); - } else { - assertEquals( - verboseResult.getProcessorResults().get(0).getIngestDocument() - .getFieldValue("foo", String.class), - "bar" + assertThat( + verboseResult.getProcessorResults().get(1).getFailure().getMessage(), + containsString("unable to convert [non-int] to integer") ); + } else { + assertEquals(verboseResult.getProcessorResults().get(0).getIngestDocument().getFieldValue("foo", String.class), "bar"); assertEquals( Integer.valueOf(1234), - verboseResult.getProcessorResults().get(1).getIngestDocument() - .getFieldValue("rank", Integer.class) + verboseResult.getProcessorResults().get(1).getIngestDocument().getFieldValue("rank", Integer.class) ); } } else { assertThat(results.get(0), instanceOf(SimulateDocumentBaseResult.class)); - SimulateDocumentBaseResult baseResult = (SimulateDocumentBaseResult)results.get(0); + SimulateDocumentBaseResult baseResult = (SimulateDocumentBaseResult) results.get(0); if (isFailure) { assertNotNull(baseResult.getFailure()); - assertThat(baseResult.getFailure().getMessage(), - containsString("unable to convert [non-int] to integer")); + assertThat(baseResult.getFailure().getMessage(), containsString("unable to convert [non-int] to integer")); } else { assertNotNull(baseResult.getIngestDocument()); - assertEquals( - baseResult.getIngestDocument().getFieldValue("foo", String.class), - "bar" - ); - assertEquals( - Integer.valueOf(1234), - baseResult.getIngestDocument() - .getFieldValue("rank", Integer.class) - ); + assertEquals(baseResult.getIngestDocument().getFieldValue("foo", String.class), "bar"); + assertEquals(Integer.valueOf(1234), baseResult.getIngestDocument().getFieldValue("rank", Integer.class)); } } } diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/IngestRequestConvertersTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/IngestRequestConvertersTests.java index 7367691eada..0d95b3e7fdd 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/IngestRequestConvertersTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/IngestRequestConvertersTests.java @@ -141,8 +141,7 @@ public class IngestRequestConvertersTests extends OpenSearchTestCase { Request expectedRequest = IngestRequestConverters.simulatePipeline(request); StringJoiner endpoint = new StringJoiner("/", "/", ""); endpoint.add("_ingest/pipeline"); - if (pipelineId != null && !pipelineId.isEmpty()) - endpoint.add(pipelineId); + if (pipelineId != null && !pipelineId.isEmpty()) endpoint.add(pipelineId); endpoint.add("_simulate"); Assert.assertEquals(endpoint.toString(), expectedRequest.getEndpoint()); Assert.assertEquals(HttpPost.METHOD_NAME, expectedRequest.getMethod()); diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/MockRestHighLevelTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/MockRestHighLevelTests.java index 05e599435f4..70693fc560d 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/MockRestHighLevelTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/MockRestHighLevelTests.java @@ -76,10 +76,11 @@ public class MockRestHighLevelTests extends OpenSearchTestCase { } public void testWarningFailure() { - WarningFailureException exception = expectThrows(WarningFailureException.class, - () -> client.info(RequestOptions.DEFAULT)); - assertThat(exception.getMessage(), equalTo("method [GET], host [http://localhost:9200], URI [/_blah], " + - "status line [HTTP/1.1 200 OK]")); + WarningFailureException exception = expectThrows(WarningFailureException.class, () -> client.info(RequestOptions.DEFAULT)); + assertThat( + exception.getMessage(), + equalTo("method [GET], host [http://localhost:9200], URI [/_blah], " + "status line [HTTP/1.1 200 OK]") + ); assertNull(exception.getCause()); assertThat(exception.getResponse().getWarnings(), equalTo(WARNINGS)); } diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/NodesResponseHeaderTestUtils.java b/client/rest-high-level/src/test/java/org/opensearch/client/NodesResponseHeaderTestUtils.java index 20d1bb8c426..9591cff16f1 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/NodesResponseHeaderTestUtils.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/NodesResponseHeaderTestUtils.java @@ -34,7 +34,6 @@ package org.opensearch.client; import org.opensearch.OpenSearchException; import org.opensearch.common.xcontent.ToXContent; import org.opensearch.common.xcontent.XContentBuilder; -import org.opensearch.client.NodesResponseHeader; import java.io.IOException; diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/OpenSearchRestHighLevelClientTestCase.java b/client/rest-high-level/src/test/java/org/opensearch/client/OpenSearchRestHighLevelClientTestCase.java index 890b97dbbe4..d64feb1e172 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/OpenSearchRestHighLevelClientTestCase.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/OpenSearchRestHighLevelClientTestCase.java @@ -112,16 +112,20 @@ public abstract class OpenSearchRestHighLevelClientTestCase extends OpenSearchRe /** * Executes the provided request using either the sync method or its async variant, both provided as functions */ - protected static Resp execute(Req request, SyncMethod syncMethod, - AsyncMethod asyncMethod) throws IOException { + protected static Resp execute(Req request, SyncMethod syncMethod, AsyncMethod asyncMethod) + throws IOException { return execute(request, syncMethod, asyncMethod, RequestOptions.DEFAULT); } /** * Executes the provided request using either the sync method or its async variant, both provided as functions */ - protected static Resp execute(Req request, SyncMethod syncMethod, - AsyncMethod asyncMethod, RequestOptions options) throws IOException { + protected static Resp execute( + Req request, + SyncMethod syncMethod, + AsyncMethod asyncMethod, + RequestOptions options + ) throws IOException { if (async == false) { return syncMethod.execute(request, options); } else { @@ -136,8 +140,11 @@ public abstract class OpenSearchRestHighLevelClientTestCase extends OpenSearchRe * variant, both provided as functions. This variant is used when the call does * not have a request object (only headers and the request path). */ - protected static Resp execute(SyncMethodNoRequest syncMethodNoRequest, AsyncMethodNoRequest asyncMethodNoRequest, - RequestOptions requestOptions) throws IOException { + protected static Resp execute( + SyncMethodNoRequest syncMethodNoRequest, + AsyncMethodNoRequest asyncMethodNoRequest, + RequestOptions requestOptions + ) throws IOException { if (async == false) { return syncMethodNoRequest.execute(requestOptions); } else { @@ -181,16 +188,12 @@ public abstract class OpenSearchRestHighLevelClientTestCase extends OpenSearchRe { pipelineBuilder.startObject().startObject("set"); { - pipelineBuilder - .field("field", "foo") - .field("value", "bar"); + pipelineBuilder.field("field", "foo").field("value", "bar"); } pipelineBuilder.endObject().endObject(); pipelineBuilder.startObject().startObject("convert"); { - pipelineBuilder - .field("field", "rank") - .field("type", "integer"); + pipelineBuilder.field("field", "rank").field("type", "integer"); } pipelineBuilder.endObject().endObject(); } @@ -207,16 +210,15 @@ public abstract class OpenSearchRestHighLevelClientTestCase extends OpenSearchRe } protected static void createFieldAddingPipleine(String id, String fieldName, String value) throws IOException { - XContentBuilder pipeline = jsonBuilder() + XContentBuilder pipeline = jsonBuilder().startObject() + .startArray("processors") .startObject() - .startArray("processors") - .startObject() - .startObject("set") - .field("field", fieldName) - .field("value", value) - .endObject() - .endObject() - .endArray() + .startObject("set") + .field("field", fieldName) + .field("value", value) + .endObject() + .endObject() + .endArray() .endObject(); createPipeline(new PutPipelineRequest(id, BytesReference.bytes(pipeline), XContentType.JSON)); @@ -228,39 +230,43 @@ public abstract class OpenSearchRestHighLevelClientTestCase extends OpenSearchRe } protected static void createPipeline(PutPipelineRequest putPipelineRequest) throws IOException { - assertTrue(execute( - putPipelineRequest, highLevelClient().ingest()::putPipeline, highLevelClient().ingest()::putPipelineAsync).isAcknowledged()); + assertTrue( + execute(putPipelineRequest, highLevelClient().ingest()::putPipeline, highLevelClient().ingest()::putPipelineAsync) + .isAcknowledged() + ); } - protected static void clusterUpdateSettings(Settings persistentSettings, - Settings transientSettings) throws IOException { + protected static void clusterUpdateSettings(Settings persistentSettings, Settings transientSettings) throws IOException { ClusterUpdateSettingsRequest request = new ClusterUpdateSettingsRequest(); request.persistentSettings(persistentSettings); request.transientSettings(transientSettings); - assertTrue(execute( - request, highLevelClient().cluster()::putSettings, highLevelClient().cluster()::putSettingsAsync).isAcknowledged()); + assertTrue( + execute(request, highLevelClient().cluster()::putSettings, highLevelClient().cluster()::putSettingsAsync).isAcknowledged() + ); } protected void putConflictPipeline() throws IOException { - final XContentBuilder pipelineBuilder = jsonBuilder() + final XContentBuilder pipelineBuilder = jsonBuilder().startObject() + .startArray("processors") .startObject() - .startArray("processors") - .startObject() - .startObject("set") - .field("field", "_version") - .field("value", 1) - .endObject() - .endObject() - .startObject() - .startObject("set") - .field("field", "_id") - .field("value", "1") - .endObject() - .endObject() - .endArray() + .startObject("set") + .field("field", "_version") + .field("value", 1) + .endObject() + .endObject() + .startObject() + .startObject("set") + .field("field", "_id") + .field("value", "1") + .endObject() + .endObject() + .endArray() .endObject(); - final PutPipelineRequest putPipelineRequest = new PutPipelineRequest(CONFLICT_PIPELINE_ID, BytesReference.bytes(pipelineBuilder), - pipelineBuilder.contentType()); + final PutPipelineRequest putPipelineRequest = new PutPipelineRequest( + CONFLICT_PIPELINE_ID, + BytesReference.bytes(pipelineBuilder), + pipelineBuilder.contentType() + ); assertTrue(highLevelClient().ingest().putPipeline(putPipelineRequest, RequestOptions.DEFAULT).isAcknowledged()); } @@ -269,10 +275,7 @@ public abstract class OpenSearchRestHighLevelClientTestCase extends OpenSearchRe final String user = Objects.requireNonNull(System.getProperty("tests.rest.cluster.username")); final String pass = Objects.requireNonNull(System.getProperty("tests.rest.cluster.password")); final String token = "Basic " + Base64.getEncoder().encodeToString((user + ":" + pass).getBytes(StandardCharsets.UTF_8)); - return Settings.builder() - .put(super.restClientSettings()) - .put(ThreadContext.PREFIX + ".Authorization", token) - .build(); + return Settings.builder().put(super.restClientSettings()).put(ThreadContext.PREFIX + ".Authorization", token).build(); } protected Iterable searchAll(String... indices) throws IOException { @@ -287,19 +290,15 @@ public abstract class OpenSearchRestHighLevelClientTestCase extends OpenSearchRe } protected void refreshIndexes(String... indices) throws IOException { - String joinedIndices = Arrays.stream(indices) - .collect(Collectors.joining(",")); + String joinedIndices = Arrays.stream(indices).collect(Collectors.joining(",")); Response refreshResponse = client().performRequest(new Request("POST", "/" + joinedIndices + "/_refresh")); assertEquals(200, refreshResponse.getStatusLine().getStatusCode()); } protected void createIndexWithMultipleShards(String index) throws IOException { CreateIndexRequest indexRequest = new CreateIndexRequest(index); - int shards = randomIntBetween(8,10); - indexRequest.settings(Settings.builder() - .put("index.number_of_shards", shards) - .put("index.number_of_replicas", 0) - ); + int shards = randomIntBetween(8, 10); + indexRequest.settings(Settings.builder().put("index.number_of_shards", shards).put("index.number_of_replicas", 0)); highLevelClient().indices().create(indexRequest, RequestOptions.DEFAULT); } @@ -314,8 +313,8 @@ public abstract class OpenSearchRestHighLevelClientTestCase extends OpenSearchRe ClusterUpdateSettingsRequest updateSettingsRequest = new ClusterUpdateSettingsRequest(); updateSettingsRequest.transientSettings(singletonMap("cluster.remote." + remoteClusterName + ".seeds", transportAddress)); - ClusterUpdateSettingsResponse updateSettingsResponse = - restHighLevelClient.cluster().putSettings(updateSettingsRequest, RequestOptions.DEFAULT); + ClusterUpdateSettingsResponse updateSettingsResponse = restHighLevelClient.cluster() + .putSettings(updateSettingsRequest, RequestOptions.DEFAULT); assertThat(updateSettingsResponse.isAcknowledged(), is(true)); assertBusy(() -> { @@ -337,11 +336,11 @@ public abstract class OpenSearchRestHighLevelClientTestCase extends OpenSearchRe do { ListTasksResponse list = highLevelClient().tasks().list(request, RequestOptions.DEFAULT); list.rethrowFailures("Finding tasks to rethrottle"); - List taskGroups = - list.getTaskGroups().stream() - .filter(taskGroup -> taskGroup.getTaskInfo().getDescription().equals(description)).collect(Collectors.toList()); - assertThat("tasks are left over from the last execution of this test", - taskGroups, hasSize(lessThan(2))); + List taskGroups = list.getTaskGroups() + .stream() + .filter(taskGroup -> taskGroup.getTaskInfo().getDescription().equals(description)) + .collect(Collectors.toList()); + assertThat("tasks are left over from the last execution of this test", taskGroups, hasSize(lessThan(2))); if (0 == taskGroups.size()) { // The parent task hasn't started yet continue; @@ -350,8 +349,10 @@ public abstract class OpenSearchRestHighLevelClientTestCase extends OpenSearchRe assertThat(taskGroup.getChildTasks(), empty()); return taskGroup.getTaskInfo().getTaskId(); } while (System.nanoTime() - start < TimeUnit.SECONDS.toNanos(10)); - throw new AssertionError("Couldn't find tasks to rethrottle. Here are the running tasks " + - highLevelClient().tasks().list(request, RequestOptions.DEFAULT)); + throw new AssertionError( + "Couldn't find tasks to rethrottle. Here are the running tasks " + + highLevelClient().tasks().list(request, RequestOptions.DEFAULT) + ); } protected static CheckedRunnable checkTaskCompletionStatus(RestClient client, String taskId) { diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/RankEvalIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/RankEvalIT.java index a896361c6cc..07e5b162794 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/RankEvalIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/RankEvalIT.java @@ -129,7 +129,7 @@ public class RankEvalIT extends OpenSearchRestHighLevelClientTestCase { private static List createTestEvaluationSpec() { SearchSourceBuilder testQuery = new SearchSourceBuilder(); testQuery.query(new MatchAllQueryBuilder()); - List amsterdamRatedDocs = createRelevant("index" , "amsterdam1", "amsterdam2", "amsterdam3", "amsterdam4"); + List amsterdamRatedDocs = createRelevant("index", "amsterdam1", "amsterdam2", "amsterdam3", "amsterdam4"); amsterdamRatedDocs.addAll(createRelevant("index2", "amsterdam0")); RatedRequest amsterdamRequest = new RatedRequest("amsterdam_query", amsterdamRatedDocs, testQuery); RatedRequest berlinRequest = new RatedRequest("berlin_query", createRelevant("index", "berlin"), testQuery); @@ -144,9 +144,14 @@ public class RankEvalIT extends OpenSearchRestHighLevelClientTestCase { */ public void testMetrics() throws IOException { List specifications = createTestEvaluationSpec(); - List> metrics = Arrays.asList(PrecisionAtK::new, RecallAtK::new, - MeanReciprocalRank::new, DiscountedCumulativeGain::new, () -> new ExpectedReciprocalRank(1)); - double expectedScores[] = new double[] {0.4285714285714286, 1.0, 0.75, 1.6408962261063627, 0.4407738095238095}; + List> metrics = Arrays.asList( + PrecisionAtK::new, + RecallAtK::new, + MeanReciprocalRank::new, + DiscountedCumulativeGain::new, + () -> new ExpectedReciprocalRank(1) + ); + double expectedScores[] = new double[] { 0.4285714285714286, 1.0, 0.75, 1.6408962261063627, 0.4407738095238095 }; int i = 0; for (Supplier metricSupplier : metrics) { RankEvalSpec spec = new RankEvalSpec(specifications, metricSupplier.get()); 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 e5271ea79d4..5576b9d5ef2 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 @@ -32,7 +32,6 @@ package org.opensearch.client; -import org.opensearch.client.RequestOptions; import org.opensearch.action.ActionListener; import org.opensearch.action.admin.cluster.node.tasks.list.ListTasksResponse; import org.opensearch.action.bulk.BulkItemResponse; @@ -72,23 +71,15 @@ public class ReindexIT extends OpenSearchRestHighLevelClientTestCase { final String destinationIndex = "dest"; { // Prepare - Settings settings = Settings.builder() - .put("number_of_shards", 1) - .put("number_of_replicas", 0) - .build(); + Settings settings = Settings.builder().put("number_of_shards", 1).put("number_of_replicas", 0).build(); createIndex(sourceIndex, settings); createIndex(destinationIndex, settings); - BulkRequest bulkRequest = new BulkRequest() - .add(new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", "bar"), XContentType.JSON)) + BulkRequest bulkRequest = new BulkRequest().add( + new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", "bar"), XContentType.JSON) + ) .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo2", "bar2"), XContentType.JSON)) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); - assertEquals( - RestStatus.OK, - highLevelClient().bulk( - bulkRequest, - RequestOptions.DEFAULT - ).status() - ); + assertEquals(RestStatus.OK, highLevelClient().bulk(bulkRequest, RequestOptions.DEFAULT).status()); } { // reindex one document with id 1 from source to destination @@ -118,23 +109,15 @@ public class ReindexIT extends OpenSearchRestHighLevelClientTestCase { final String destinationIndex = "dest2"; { // Prepare - Settings settings = Settings.builder() - .put("number_of_shards", 1) - .put("number_of_replicas", 0) - .build(); + Settings settings = Settings.builder().put("number_of_shards", 1).put("number_of_replicas", 0).build(); createIndex(sourceIndex, settings); createIndex(destinationIndex, settings); - BulkRequest bulkRequest = new BulkRequest() - .add(new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", "bar"), XContentType.JSON)) + BulkRequest bulkRequest = new BulkRequest().add( + new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", "bar"), XContentType.JSON) + ) .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo2", "bar2"), XContentType.JSON)) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); - assertEquals( - RestStatus.OK, - highLevelClient().bulk( - bulkRequest, - RequestOptions.DEFAULT - ).status() - ); + assertEquals(RestStatus.OK, highLevelClient().bulk(bulkRequest, RequestOptions.DEFAULT).status()); } { // tag::submit-reindex-task @@ -157,14 +140,12 @@ public class ReindexIT extends OpenSearchRestHighLevelClientTestCase { final String sourceIndex = "testreindexconflict_source"; final String destIndex = "testreindexconflict_dest"; - final Settings settings = Settings.builder() - .put("number_of_shards", 1) - .put("number_of_replicas", 0) - .build(); + final Settings settings = Settings.builder().put("number_of_shards", 1).put("number_of_replicas", 0).build(); createIndex(sourceIndex, settings); createIndex(destIndex, settings); - final BulkRequest bulkRequest = new BulkRequest() - .add(new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", "bar"), XContentType.JSON)) + final BulkRequest bulkRequest = new BulkRequest().add( + new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", "bar"), XContentType.JSON) + ) .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo", "bar"), XContentType.JSON)) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); assertThat(highLevelClient().bulk(bulkRequest, RequestOptions.DEFAULT).status(), equalTo(RestStatus.OK)); @@ -199,21 +180,16 @@ public class ReindexIT extends OpenSearchRestHighLevelClientTestCase { final String sourceIndex = "source1"; { // Prepare - Settings settings = Settings.builder() - .put("number_of_shards", 1) - .put("number_of_replicas", 0) - .build(); + Settings settings = Settings.builder().put("number_of_shards", 1).put("number_of_replicas", 0).build(); createIndex(sourceIndex, settings); assertEquals( RestStatus.OK, highLevelClient().bulk( - new BulkRequest() - .add(new IndexRequest(sourceIndex).id("1") - .source(Collections.singletonMap("foo", 1), XContentType.JSON)) - .add(new IndexRequest(sourceIndex).id("2") - .source(Collections.singletonMap("foo", 2), XContentType.JSON)) - .add(new IndexRequest(sourceIndex).id("3") - .source(Collections.singletonMap("foo", 3), XContentType.JSON)) + new BulkRequest().add( + new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", 1), XContentType.JSON) + ) + .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo", 2), XContentType.JSON)) + .add(new IndexRequest(sourceIndex).id("3").source(Collections.singletonMap("foo", 3), XContentType.JSON)) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE), RequestOptions.DEFAULT ).status() @@ -225,8 +201,11 @@ public class ReindexIT extends OpenSearchRestHighLevelClientTestCase { deleteByQueryRequest.indices(sourceIndex); deleteByQueryRequest.setQuery(new IdsQueryBuilder().addIds("1")); deleteByQueryRequest.setRefresh(true); - BulkByScrollResponse bulkResponse = - execute(deleteByQueryRequest, highLevelClient()::deleteByQuery, highLevelClient()::deleteByQueryAsync); + BulkByScrollResponse bulkResponse = execute( + deleteByQueryRequest, + highLevelClient()::deleteByQuery, + highLevelClient()::deleteByQueryAsync + ); assertEquals(1, bulkResponse.getTotal()); assertEquals(1, bulkResponse.getDeleted()); assertEquals(0, bulkResponse.getNoops()); @@ -267,23 +246,33 @@ public class ReindexIT extends OpenSearchRestHighLevelClientTestCase { TaskId taskIdToRethrottle = findTaskToRethrottle(DeleteByQueryAction.NAME, deleteByQueryRequest.getDescription()); float requestsPerSecond = 1000f; - ListTasksResponse response = execute(new RethrottleRequest(taskIdToRethrottle, requestsPerSecond), - highLevelClient()::deleteByQueryRethrottle, highLevelClient()::deleteByQueryRethrottleAsync); + ListTasksResponse response = execute( + new RethrottleRequest(taskIdToRethrottle, requestsPerSecond), + highLevelClient()::deleteByQueryRethrottle, + highLevelClient()::deleteByQueryRethrottleAsync + ); assertThat(response.getTasks(), hasSize(1)); assertEquals(taskIdToRethrottle, response.getTasks().get(0).getTaskId()); assertThat(response.getTasks().get(0).getStatus(), instanceOf(RawTaskStatus.class)); - assertEquals(Float.toString(requestsPerSecond), - ((RawTaskStatus) response.getTasks().get(0).getStatus()).toMap().get("requests_per_second").toString()); + assertEquals( + Float.toString(requestsPerSecond), + ((RawTaskStatus) response.getTasks().get(0).getStatus()).toMap().get("requests_per_second").toString() + ); assertTrue(taskFinished.await(10, TimeUnit.SECONDS)); // any rethrottling after the delete-by-query is done performed with the same taskId should result in a failure - response = execute(new RethrottleRequest(taskIdToRethrottle, requestsPerSecond), - highLevelClient()::deleteByQueryRethrottle, highLevelClient()::deleteByQueryRethrottleAsync); + response = execute( + new RethrottleRequest(taskIdToRethrottle, requestsPerSecond), + highLevelClient()::deleteByQueryRethrottle, + highLevelClient()::deleteByQueryRethrottleAsync + ); assertTrue(response.getTasks().isEmpty()); assertFalse(response.getNodeFailures().isEmpty()); assertEquals(1, response.getNodeFailures().size()); - assertEquals("OpenSearch exception [type=resource_not_found_exception, reason=task [" + taskIdToRethrottle + "] is missing]", - response.getNodeFailures().get(0).getCause().getMessage()); + assertEquals( + "OpenSearch exception [type=resource_not_found_exception, reason=task [" + taskIdToRethrottle + "] is missing]", + response.getNodeFailures().get(0).getCause().getMessage() + ); } } @@ -291,21 +280,16 @@ public class ReindexIT extends OpenSearchRestHighLevelClientTestCase { final String sourceIndex = "source456"; { // Prepare - Settings settings = Settings.builder() - .put("number_of_shards", 1) - .put("number_of_replicas", 0) - .build(); + Settings settings = Settings.builder().put("number_of_shards", 1).put("number_of_replicas", 0).build(); createIndex(sourceIndex, settings); assertEquals( RestStatus.OK, highLevelClient().bulk( - new BulkRequest() - .add(new IndexRequest(sourceIndex).id("1") - .source(Collections.singletonMap("foo", 1), XContentType.JSON)) - .add(new IndexRequest(sourceIndex).id("2") - .source(Collections.singletonMap("foo", 2), XContentType.JSON)) - .add(new IndexRequest(sourceIndex).id("3") - .source(Collections.singletonMap("foo", 3), XContentType.JSON)) + new BulkRequest().add( + new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", 1), XContentType.JSON) + ) + .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo", 2), XContentType.JSON)) + .add(new IndexRequest(sourceIndex).id("3").source(Collections.singletonMap("foo", 3), XContentType.JSON)) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE), RequestOptions.DEFAULT ).status() diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/RequestConvertersTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/RequestConvertersTests.java index 00287d630c2..51b0ce00a14 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/RequestConvertersTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/RequestConvertersTests.java @@ -321,9 +321,7 @@ public class RequestConvertersTests extends OpenSearchTestCase { public void testMultiGetWithType() throws IOException { MultiGetRequest multiGetRequest = new MultiGetRequest(); - MultiGetRequest.Item item = new MultiGetRequest.Item(randomAlphaOfLength(4), - randomAlphaOfLength(4), - randomAlphaOfLength(4)); + MultiGetRequest.Item item = new MultiGetRequest.Item(randomAlphaOfLength(4), randomAlphaOfLength(4), randomAlphaOfLength(4)); multiGetRequest.add(item); Request request = RequestConverters.multiGet(multiGetRequest); @@ -456,7 +454,11 @@ public class RequestConvertersTests extends OpenSearchTestCase { Map expectedParams = new HashMap<>(); if (randomBoolean()) { XContentBuilder builder = JsonXContent.contentBuilder().prettyPrint(); - RemoteInfo remoteInfo = new RemoteInfo("http", "remote-host", 9200, null, + RemoteInfo remoteInfo = new RemoteInfo( + "http", + "remote-host", + 9200, + null, BytesReference.bytes(matchAllQuery().toXContent(builder, ToXContent.EMPTY_PARAMS)), "user", "pass", @@ -509,7 +511,7 @@ public class RequestConvertersTests extends OpenSearchTestCase { reindexRequest.setSourceQuery(new TermQueryBuilder("foo", "fooval")); } if (randomBoolean()) { - int slices = randomIntBetween(0,4); + int slices = randomIntBetween(0, 4); reindexRequest.setSlices(slices); if (slices == 0) { expectedParams.put("slices", AbstractBulkByScrollRequest.AUTO_SLICES_VALUE); @@ -685,7 +687,7 @@ public class RequestConvertersTests extends OpenSearchTestCase { Float requestsPerSecond; Map expectedParams = new HashMap<>(); if (frequently()) { - requestsPerSecond = (float) randomDoubleBetween(0.0, 100.0, true); + requestsPerSecond = (float) randomDoubleBetween(0.0, 100.0, true); rethrottleRequest = new RethrottleRequest(taskId, requestsPerSecond); expectedParams.put(RethrottleRequest.REQUEST_PER_SECOND_PARAMETER, Float.toString(requestsPerSecond)); } else { @@ -695,10 +697,12 @@ public class RequestConvertersTests extends OpenSearchTestCase { expectedParams.put("group_by", "none"); List>> variants = new ArrayList<>(); variants.add(new Tuple>("_reindex", () -> RequestConverters.rethrottleReindex(rethrottleRequest))); - variants.add(new Tuple>("_update_by_query", - () -> RequestConverters.rethrottleUpdateByQuery(rethrottleRequest))); - variants.add(new Tuple>("_delete_by_query", - () -> RequestConverters.rethrottleDeleteByQuery(rethrottleRequest))); + variants.add( + new Tuple>("_update_by_query", () -> RequestConverters.rethrottleUpdateByQuery(rethrottleRequest)) + ); + variants.add( + new Tuple>("_delete_by_query", () -> RequestConverters.rethrottleDeleteByQuery(rethrottleRequest)) + ); for (Tuple> variant : variants) { Request request = variant.v2().get(); @@ -924,7 +928,7 @@ public class RequestConvertersTests extends OpenSearchTestCase { } } - private static void assertIfSeqNoAndTerm(DocWriteRequestrequest, DocWriteRequest parsedRequest) { + private static void assertIfSeqNoAndTerm(DocWriteRequest request, DocWriteRequest parsedRequest) { assertEquals(request.ifSeqNo(), parsedRequest.ifSeqNo()); assertEquals(request.ifPrimaryTerm(), parsedRequest.ifPrimaryTerm()); } @@ -964,8 +968,10 @@ public class RequestConvertersTests extends OpenSearchTestCase { updateRequest.upsert(new IndexRequest().source(singletonMap("field", "upsert"), XContentType.YAML)); RequestConverters.update(updateRequest); }); - assertEquals("Update request cannot have different content types for doc [JSON] and upsert [YAML] documents", - exception.getMessage()); + assertEquals( + "Update request cannot have different content types for doc [JSON] and upsert [YAML] documents", + exception.getMessage() + ); } public void testBulk() throws IOException { @@ -1117,20 +1123,23 @@ public class RequestConvertersTests extends OpenSearchTestCase { bulkRequest.add(new IndexRequest("index").id("1").source(singletonMap("field", "value"), XContentType.JSON)); IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> RequestConverters.bulk(bulkRequest)); assertEquals( - "Mismatching content-type found for request with content-type [JSON], " + "previous requests have content-type [SMILE]", - exception.getMessage()); + "Mismatching content-type found for request with content-type [JSON], " + "previous requests have content-type [SMILE]", + exception.getMessage() + ); } { BulkRequest bulkRequest = new BulkRequest(); bulkRequest.add(new IndexRequest("index").id("0").source(singletonMap("field", "value"), XContentType.JSON)); bulkRequest.add(new IndexRequest("index").id("1").source(singletonMap("field", "value"), XContentType.JSON)); - bulkRequest.add(new UpdateRequest("index", "2") - .doc(new IndexRequest().source(singletonMap("field", "value"), XContentType.JSON)) - .upsert(new IndexRequest().source(singletonMap("field", "value"), XContentType.SMILE))); + bulkRequest.add( + new UpdateRequest("index", "2").doc(new IndexRequest().source(singletonMap("field", "value"), XContentType.JSON)) + .upsert(new IndexRequest().source(singletonMap("field", "value"), XContentType.SMILE)) + ); IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> RequestConverters.bulk(bulkRequest)); assertEquals( - "Mismatching content-type found for request with content-type [SMILE], " + "previous requests have content-type [JSON]", - exception.getMessage()); + "Mismatching content-type found for request with content-type [SMILE], " + "previous requests have content-type [JSON]", + exception.getMessage() + ); } { XContentType xContentType = randomFrom(XContentType.CBOR, XContentType.YAML); @@ -1142,24 +1151,23 @@ public class RequestConvertersTests extends OpenSearchTestCase { bulkRequest.add(new IndexRequest("index").id("4").source(singletonMap("field", "value"), XContentType.JSON)); bulkRequest.add(new IndexRequest("index").id("1").source(singletonMap("field", "value"), xContentType)); IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> RequestConverters.bulk(bulkRequest)); - assertEquals("Unsupported content-type found for request with content-type [" + xContentType - + "], only JSON and SMILE are supported", exception.getMessage()); + assertEquals( + "Unsupported content-type found for request with content-type [" + xContentType + "], only JSON and SMILE are supported", + exception.getMessage() + ); } } public void testGlobalPipelineOnBulkRequest() throws IOException { BulkRequest bulkRequest = new BulkRequest(); bulkRequest.pipeline("xyz"); - bulkRequest.add(new IndexRequest("test").id("11") - .source(XContentType.JSON, "field", "bulk1")); - bulkRequest.add(new IndexRequest("test").id("12") - .source(XContentType.JSON, "field", "bulk2")); - bulkRequest.add(new IndexRequest("test").id("13") - .source(XContentType.JSON, "field", "bulk3")); + bulkRequest.add(new IndexRequest("test").id("11").source(XContentType.JSON, "field", "bulk1")); + bulkRequest.add(new IndexRequest("test").id("12").source(XContentType.JSON, "field", "bulk2")); + bulkRequest.add(new IndexRequest("test").id("13").source(XContentType.JSON, "field", "bulk3")); Request request = RequestConverters.bulk(bulkRequest); - assertThat(request.getParameters(), Matchers.hasEntry("pipeline","xyz")); + assertThat(request.getParameters(), Matchers.hasEntry("pipeline", "xyz")); } public void testSearchNullSource() throws IOException { @@ -1241,17 +1249,23 @@ public class RequestConvertersTests extends OpenSearchTestCase { searchSourceBuilder.query(new TermQueryBuilder(randomAlphaOfLengthBetween(3, 10), randomAlphaOfLengthBetween(3, 10))); } if (randomBoolean()) { - searchSourceBuilder.aggregation(new TermsAggregationBuilder(randomAlphaOfLengthBetween(3, 10)) - .userValueTypeHint(ValueType.STRING) - .field(randomAlphaOfLengthBetween(3, 10))); + searchSourceBuilder.aggregation( + new TermsAggregationBuilder(randomAlphaOfLengthBetween(3, 10)).userValueTypeHint(ValueType.STRING) + .field(randomAlphaOfLengthBetween(3, 10)) + ); } if (randomBoolean()) { - searchSourceBuilder.suggest(new SuggestBuilder().addSuggestion(randomAlphaOfLengthBetween(3, 10), - new CompletionSuggestionBuilder(randomAlphaOfLengthBetween(3, 10)))); + searchSourceBuilder.suggest( + new SuggestBuilder().addSuggestion( + randomAlphaOfLengthBetween(3, 10), + new CompletionSuggestionBuilder(randomAlphaOfLengthBetween(3, 10)) + ) + ); } if (randomBoolean()) { - searchSourceBuilder.addRescorer(new QueryRescorerBuilder( - new TermQueryBuilder(randomAlphaOfLengthBetween(3, 10), randomAlphaOfLengthBetween(3, 10)))); + searchSourceBuilder.addRescorer( + new QueryRescorerBuilder(new TermQueryBuilder(randomAlphaOfLengthBetween(3, 10), randomAlphaOfLengthBetween(3, 10))) + ); } if (randomBoolean()) { searchSourceBuilder.collapse(new CollapseBuilder(randomAlphaOfLengthBetween(3, 10))); @@ -1261,15 +1275,14 @@ public class RequestConvertersTests extends OpenSearchTestCase { return searchSourceBuilder; } - public void testSearchNullIndicesAndTypes() { expectThrows(NullPointerException.class, () -> new SearchRequest((String[]) null)); expectThrows(NullPointerException.class, () -> new SearchRequest().indices((String[]) null)); expectThrows(NullPointerException.class, () -> new SearchRequest().types((String[]) null)); } - public void testCountNotNullSource() throws IOException { - //as we create SearchSourceBuilder in CountRequest constructor + public void testCountNotNullSource() throws IOException { + // as we create SearchSourceBuilder in CountRequest constructor CountRequest countRequest = new CountRequest(); Request request = RequestConverters.count(countRequest); assertEquals(HttpPost.METHOD_NAME, request.getMethod()); @@ -1321,8 +1334,7 @@ public class RequestConvertersTests extends OpenSearchTestCase { expectThrows(NullPointerException.class, () -> new CountRequest().types((String[]) null)); } - private static void setRandomCountParams(CountRequest countRequest, - Map expectedParams) { + private static void setRandomCountParams(CountRequest countRequest, Map expectedParams) { if (randomBoolean()) { countRequest.routing(randomAlphaOfLengthBetween(3, 10)); expectedParams.put("routing", countRequest.routing()); @@ -1359,10 +1371,19 @@ public class RequestConvertersTests extends OpenSearchTestCase { // specified from msearch api, so unset other options: IndicesOptions randomlyGenerated = searchRequest.indicesOptions(); IndicesOptions msearchDefault = new MultiSearchRequest().indicesOptions(); - searchRequest.indicesOptions(IndicesOptions.fromOptions(randomlyGenerated.ignoreUnavailable(), - randomlyGenerated.allowNoIndices(), randomlyGenerated.expandWildcardsOpen(), randomlyGenerated.expandWildcardsClosed(), - msearchDefault.expandWildcardsHidden(), msearchDefault.allowAliasesToMultipleIndices(), - msearchDefault.forbidClosedIndices(), msearchDefault.ignoreAliases(), msearchDefault.ignoreThrottled())); + searchRequest.indicesOptions( + IndicesOptions.fromOptions( + randomlyGenerated.ignoreUnavailable(), + randomlyGenerated.allowNoIndices(), + randomlyGenerated.expandWildcardsOpen(), + randomlyGenerated.expandWildcardsClosed(), + msearchDefault.expandWildcardsHidden(), + msearchDefault.allowAliasesToMultipleIndices(), + msearchDefault.forbidClosedIndices(), + msearchDefault.ignoreAliases(), + msearchDefault.ignoreThrottled() + ) + ); multiSearchRequest.add(searchRequest); } @@ -1386,9 +1407,20 @@ public class RequestConvertersTests extends OpenSearchTestCase { } requests.add(searchRequest); }; - MultiSearchRequest.readMultiLineFormat(new BytesArray(EntityUtils.toByteArray(request.getEntity())), - REQUEST_BODY_CONTENT_TYPE.xContent(), consumer, null, multiSearchRequest.indicesOptions(), null, null, null, null, - xContentRegistry(), true, deprecationLogger); + MultiSearchRequest.readMultiLineFormat( + new BytesArray(EntityUtils.toByteArray(request.getEntity())), + REQUEST_BODY_CONTENT_TYPE.xContent(), + consumer, + null, + multiSearchRequest.indicesOptions(), + null, + null, + null, + null, + xContentRegistry(), + true, + deprecationLogger + ); assertEquals(requests, multiSearchRequest.requests()); } @@ -1514,7 +1546,7 @@ public class RequestConvertersTests extends OpenSearchTestCase { Map expectedParams = new HashMap<>(); if (randomBoolean()) { - multiSearchTemplateRequest.maxConcurrentSearchRequests(randomIntBetween(1,10)); + multiSearchTemplateRequest.maxConcurrentSearchRequests(randomIntBetween(1, 10)); expectedParams.put("max_concurrent_searches", Integer.toString(multiSearchTemplateRequest.maxConcurrentSearchRequests())); } expectedParams.put(RestSearchAction.TYPED_KEYS_PARAM, "true"); @@ -1716,8 +1748,7 @@ public class RequestConvertersTests extends OpenSearchTestCase { String[] indices = randomIndicesNames(0, 5); String[] fields = generateRandomStringArray(5, 10, false, false); - FieldCapabilitiesRequest fieldCapabilitiesRequest = new FieldCapabilitiesRequest() - .indices(indices) + FieldCapabilitiesRequest fieldCapabilitiesRequest = new FieldCapabilitiesRequest().indices(indices) .fields(fields) .indexFilter(QueryBuilders.matchAllQuery()); @@ -1755,8 +1786,9 @@ public class RequestConvertersTests extends OpenSearchTestCase { public void testRankEval() throws Exception { RankEvalSpec spec = new RankEvalSpec( - Collections.singletonList(new RatedRequest("queryId", Collections.emptyList(), new SearchSourceBuilder())), - new PrecisionAtK()); + Collections.singletonList(new RatedRequest("queryId", Collections.emptyList(), new SearchSourceBuilder())), + new PrecisionAtK() + ); String[] indices = randomIndicesNames(0, 5); RankEvalRequest rankEvalRequest = new RankEvalRequest(spec, indices); Map expectedParams = new HashMap<>(); @@ -1788,10 +1820,7 @@ public class RequestConvertersTests extends OpenSearchTestCase { XContentType xContentType = randomFrom(XContentType.values()); try (XContentBuilder builder = XContentBuilder.builder(xContentType.xContent())) { builder.startObject(); - builder.startObject("script") - .field("lang", "painless") - .field("source", "Math.log(_score * 2) + params.multiplier") - .endObject(); + builder.startObject("script").field("lang", "painless").field("source", "Math.log(_score * 2) + params.multiplier").endObject(); builder.endObject(); putStoredScriptRequest.content(BytesReference.bytes(builder), xContentType); @@ -1816,8 +1845,7 @@ public class RequestConvertersTests extends OpenSearchTestCase { } public void testAnalyzeRequest() throws Exception { - AnalyzeRequest indexAnalyzeRequest - = AnalyzeRequest.withIndexAnalyzer("test_index", "test_analyzer", "Here is some text"); + AnalyzeRequest indexAnalyzeRequest = AnalyzeRequest.withIndexAnalyzer("test_index", "test_analyzer", "Here is some text"); Request request = RequestConverters.analyze(indexAnalyzeRequest); assertThat(request.getEndpoint(), equalTo("/test_index/_analyze")); @@ -1946,7 +1974,7 @@ public class RequestConvertersTests extends OpenSearchTestCase { } { EndpointBuilder endpointBuilder = new EndpointBuilder().addCommaSeparatedPathParts(new String[] { "index1", "index2" }) - .addPathPartAsIs("cache/clear"); + .addPathPartAsIs("cache/clear"); assertEquals("/index1,index2/cache/clear", endpointBuilder.build()); } { @@ -1988,10 +2016,14 @@ public class RequestConvertersTests extends OpenSearchTestCase { assertEquals("/index/type/id/_endpoint", RequestConverters.endpoint("index", "type", "id", "_endpoint")); assertEquals("/index1,index2", RequestConverters.endpoint(new String[] { "index1", "index2" })); assertEquals("/index1,index2/_endpoint", RequestConverters.endpoint(new String[] { "index1", "index2" }, "_endpoint")); - assertEquals("/index1,index2/type1,type2/_endpoint", - RequestConverters.endpoint(new String[] { "index1", "index2" }, new String[] { "type1", "type2" }, "_endpoint")); - assertEquals("/index1,index2/_endpoint/suffix1,suffix2", - RequestConverters.endpoint(new String[] { "index1", "index2" }, "_endpoint", new String[] { "suffix1", "suffix2" })); + assertEquals( + "/index1,index2/type1,type2/_endpoint", + RequestConverters.endpoint(new String[] { "index1", "index2" }, new String[] { "type1", "type2" }, "_endpoint") + ); + assertEquals( + "/index1,index2/_endpoint/suffix1,suffix2", + RequestConverters.endpoint(new String[] { "index1", "index2" }, "_endpoint", new String[] { "suffix1", "suffix2" }) + ); } public void testCreateContentType() { @@ -2007,24 +2039,39 @@ public class RequestConvertersTests extends OpenSearchTestCase { XContentType bulkContentType = randomBoolean() ? xContentType : null; - IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, - () -> enforceSameContentType(new IndexRequest().source(singletonMap("field", "value"), XContentType.CBOR), - bulkContentType)); - assertEquals("Unsupported content-type found for request with content-type [CBOR], only JSON and SMILE are supported", - exception.getMessage()); + IllegalArgumentException exception = expectThrows( + IllegalArgumentException.class, + () -> enforceSameContentType(new IndexRequest().source(singletonMap("field", "value"), XContentType.CBOR), bulkContentType) + ); + assertEquals( + "Unsupported content-type found for request with content-type [CBOR], only JSON and SMILE are supported", + exception.getMessage() + ); - exception = expectThrows(IllegalArgumentException.class, - () -> enforceSameContentType(new IndexRequest().source(singletonMap("field", "value"), XContentType.YAML), - bulkContentType)); - assertEquals("Unsupported content-type found for request with content-type [YAML], only JSON and SMILE are supported", - exception.getMessage()); + exception = expectThrows( + IllegalArgumentException.class, + () -> enforceSameContentType(new IndexRequest().source(singletonMap("field", "value"), XContentType.YAML), bulkContentType) + ); + assertEquals( + "Unsupported content-type found for request with content-type [YAML], only JSON and SMILE are supported", + exception.getMessage() + ); XContentType requestContentType = xContentType == XContentType.JSON ? XContentType.SMILE : XContentType.JSON; - exception = expectThrows(IllegalArgumentException.class, - () -> enforceSameContentType(new IndexRequest().source(singletonMap("field", "value"), requestContentType), xContentType)); - assertEquals("Mismatching content-type found for request with content-type [" + requestContentType + "], " - + "previous requests have content-type [" + xContentType + "]", exception.getMessage()); + exception = expectThrows( + IllegalArgumentException.class, + () -> enforceSameContentType(new IndexRequest().source(singletonMap("field", "value"), requestContentType), xContentType) + ); + assertEquals( + "Mismatching content-type found for request with content-type [" + + requestContentType + + "], " + + "previous requests have content-type [" + + xContentType + + "]", + exception.getMessage() + ); } /** @@ -2056,8 +2103,7 @@ public class RequestConvertersTests extends OpenSearchTestCase { } } - private static void setRandomSearchParams(SearchRequest searchRequest, - Map expectedParams) { + private static void setRandomSearchParams(SearchRequest searchRequest, Map expectedParams) { expectedParams.put(RestSearchAction.TYPED_KEYS_PARAM, "true"); if (randomBoolean()) { searchRequest.routing(randomAlphaOfLengthBetween(3, 10)); @@ -2103,12 +2149,25 @@ public class RequestConvertersTests extends OpenSearchTestCase { } } - public static void setRandomIndicesOptions(Consumer setter, Supplier getter, - Map expectedParams) { + public static void setRandomIndicesOptions( + Consumer setter, + Supplier getter, + Map expectedParams + ) { if (randomBoolean()) { - setter.accept(IndicesOptions.fromOptions(randomBoolean(), randomBoolean(), randomBoolean(), randomBoolean(), - true, false, false, randomBoolean())); + setter.accept( + IndicesOptions.fromOptions( + randomBoolean(), + randomBoolean(), + randomBoolean(), + randomBoolean(), + true, + false, + false, + randomBoolean() + ) + ); } expectedParams.put("ignore_unavailable", Boolean.toString(getter.get().ignoreUnavailable())); expectedParams.put("allow_no_indices", Boolean.toString(getter.get().allowNoIndices())); @@ -2126,8 +2185,16 @@ public class RequestConvertersTests extends OpenSearchTestCase { static IndicesOptions setRandomIndicesOptions(IndicesOptions indicesOptions, Map expectedParams) { if (randomBoolean()) { - indicesOptions = IndicesOptions.fromOptions(randomBoolean(), randomBoolean(), randomBoolean(), randomBoolean(), - true, false, false, randomBoolean()); + indicesOptions = IndicesOptions.fromOptions( + randomBoolean(), + randomBoolean(), + randomBoolean(), + randomBoolean(), + true, + false, + false, + randomBoolean() + ); } expectedParams.put("ignore_unavailable", Boolean.toString(indicesOptions.ignoreUnavailable())); expectedParams.put("allow_no_indices", Boolean.toString(indicesOptions.allowNoIndices())); @@ -2175,9 +2242,11 @@ public class RequestConvertersTests extends OpenSearchTestCase { } static void setRandomTimeout(TimedRequest request, TimeValue defaultTimeout, Map expectedParams) { - setRandomTimeout(s -> - request.setTimeout(TimeValue.parseTimeValue(s, request.getClass().getName() + ".timeout")), - defaultTimeout, expectedParams); + setRandomTimeout( + s -> request.setTimeout(TimeValue.parseTimeValue(s, request.getClass().getName() + ".timeout")), + defaultTimeout, + expectedParams + ); } static void setRandomTimeout(Consumer setter, TimeValue defaultTimeout, Map expectedParams) { @@ -2190,8 +2259,7 @@ public class RequestConvertersTests extends OpenSearchTestCase { } } - static void setRandomTimeoutTimeValue(Consumer setter, TimeValue defaultTimeout, - Map expectedParams) { + static void setRandomTimeoutTimeValue(Consumer setter, TimeValue defaultTimeout, Map expectedParams) { if (randomBoolean()) { TimeValue timeout = TimeValue.parseTimeValue(randomTimeValue(), "random_timeout"); setter.accept(timeout); @@ -2206,9 +2274,10 @@ public class RequestConvertersTests extends OpenSearchTestCase { } static void setRandomMasterTimeout(TimedRequest request, Map expectedParams) { - setRandomMasterTimeout(s -> - request.setMasterTimeout(TimeValue.parseTimeValue(s, request.getClass().getName() + ".masterNodeTimeout")), - expectedParams); + setRandomMasterTimeout( + s -> request.setMasterTimeout(TimeValue.parseTimeValue(s, request.getClass().getName() + ".masterNodeTimeout")), + expectedParams + ); } static void setRandomMasterTimeout(Consumer setter, Map expectedParams) { @@ -2235,8 +2304,11 @@ public class RequestConvertersTests extends OpenSearchTestCase { setRandomWaitForActiveShards(setter, ActiveShardCount.DEFAULT, expectedParams); } - static void setRandomWaitForActiveShards(Consumer setter, ActiveShardCount defaultActiveShardCount, - Map expectedParams) { + static void setRandomWaitForActiveShards( + Consumer setter, + ActiveShardCount defaultActiveShardCount, + Map expectedParams + ) { if (randomBoolean()) { int waitForActiveShardsInt = randomIntBetween(-1, 5); String waitForActiveShardsString; diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/RestHighLevelClientExtTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/RestHighLevelClientExtTests.java index 0a653b758b7..dbdf7eba3dc 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/RestHighLevelClientExtTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/RestHighLevelClientExtTests.java @@ -75,7 +75,7 @@ public class RestHighLevelClientExtTests extends OpenSearchTestCase { BaseCustomResponseSection customSection = restHighLevelClient.parseEntity(jsonEntity, BaseCustomResponseSection::fromXContent); assertThat(customSection, instanceOf(CustomResponseSection2.class)); CustomResponseSection2 customResponseSection2 = (CustomResponseSection2) customSection; - assertArrayEquals(new String[]{"item1", "item2"}, customResponseSection2.values); + assertArrayEquals(new String[] { "item1", "item2" }, customResponseSection2.values); } } @@ -87,10 +87,20 @@ public class RestHighLevelClientExtTests extends OpenSearchTestCase { private static List getNamedXContentsExt() { List entries = new ArrayList<>(); - entries.add(new NamedXContentRegistry.Entry(BaseCustomResponseSection.class, new ParseField("custom1"), - CustomResponseSection1::fromXContent)); - entries.add(new NamedXContentRegistry.Entry(BaseCustomResponseSection.class, new ParseField("custom2"), - CustomResponseSection2::fromXContent)); + entries.add( + new NamedXContentRegistry.Entry( + BaseCustomResponseSection.class, + new ParseField("custom1"), + CustomResponseSection1::fromXContent + ) + ); + entries.add( + new NamedXContentRegistry.Entry( + BaseCustomResponseSection.class, + new ParseField("custom2"), + CustomResponseSection2::fromXContent + ) + ); return entries; } } @@ -139,7 +149,7 @@ public class RestHighLevelClientExtTests extends OpenSearchTestCase { assertEquals("array", parser.currentName()); assertEquals(XContentParser.Token.START_ARRAY, parser.nextToken()); List values = new ArrayList<>(); - while(parser.nextToken().isValue()) { + while (parser.nextToken().isValue()) { values.add(parser.text()); } assertEquals(XContentParser.Token.END_ARRAY, parser.currentToken()); 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 f4d6019903f..5648409f151 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 @@ -132,11 +132,16 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { */ private static final Set APIS_WITHOUT_REQUEST_OBJECT = Sets.newHashSet( // core - "ping", "info", + "ping", + "info", // security - "security.get_ssl_certificates", "security.authenticate", "security.get_user_privileges", "security.get_builtin_privileges", + "security.get_ssl_certificates", + "security.authenticate", + "security.get_user_privileges", + "security.get_builtin_privileges", // license - "license.get_trial_status", "license.get_basic_status" + "license.get_trial_status", + "license.get_basic_status" ); @@ -178,9 +183,21 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { } public void testInfo() throws IOException { - MainResponse testInfo = new MainResponse("nodeName", new MainResponse.Version("number", "buildType", "buildHash", - "buildDate", true, "luceneVersion", "minimumWireCompatibilityVersion", "minimumIndexCompatibilityVersion"), - "clusterName", "clusterUuid"); + MainResponse testInfo = new MainResponse( + "nodeName", + new MainResponse.Version( + "number", + "buildType", + "buildHash", + "buildDate", + true, + "luceneVersion", + "minimumWireCompatibilityVersion", + "minimumIndexCompatibilityVersion" + ), + "clusterName", + "clusterUuid" + ); mockResponse((ToXContentFragment) (builder, params) -> { // taken from the server side MainResponse builder.field("name", testInfo.getNodeName()); @@ -203,12 +220,21 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { } public void testSearchScroll() throws IOException { - SearchResponse mockSearchResponse = new SearchResponse(new SearchResponseSections(SearchHits.empty(), InternalAggregations.EMPTY, - null, false, false, null, 1), randomAlphaOfLengthBetween(5, 10), 5, 5, 0, 100, ShardSearchFailure.EMPTY_ARRAY, - SearchResponse.Clusters.EMPTY); + SearchResponse mockSearchResponse = new SearchResponse( + new SearchResponseSections(SearchHits.empty(), InternalAggregations.EMPTY, null, false, false, null, 1), + randomAlphaOfLengthBetween(5, 10), + 5, + 5, + 0, + 100, + ShardSearchFailure.EMPTY_ARRAY, + SearchResponse.Clusters.EMPTY + ); mockResponse(mockSearchResponse); SearchResponse searchResponse = restHighLevelClient.scroll( - new SearchScrollRequest(randomAlphaOfLengthBetween(5, 10)), RequestOptions.DEFAULT); + new SearchScrollRequest(randomAlphaOfLengthBetween(5, 10)), + RequestOptions.DEFAULT + ); assertEquals(mockSearchResponse.getScrollId(), searchResponse.getScrollId()); assertEquals(0, searchResponse.getHits().getTotalHits().value); assertEquals(5, searchResponse.getTotalShards()); @@ -245,8 +271,10 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { }; { - ActionRequestValidationException actualException = expectThrows(ActionRequestValidationException.class, - () -> restHighLevelClient.performRequest(request, null, RequestOptions.DEFAULT, null, null)); + ActionRequestValidationException actualException = expectThrows( + ActionRequestValidationException.class, + () -> restHighLevelClient.performRequest(request, null, RequestOptions.DEFAULT, null, null) + ); assertSame(validationException, actualException); } { @@ -262,8 +290,10 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { assertEquals("Response body expected but not returned", ise.getMessage()); } { - IllegalStateException ise = expectThrows(IllegalStateException.class, - () -> restHighLevelClient.parseEntity(new NStringEntity("", (ContentType) null), null)); + IllegalStateException ise = expectThrows( + IllegalStateException.class, + () -> restHighLevelClient.parseEntity(new NStringEntity("", (ContentType) null), null) + ); assertEquals("OpenSearch didn't return the [Content-Type] header, unable to parse response body", ise.getMessage()); } { @@ -322,8 +352,12 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { { RestStatus restStatus = randomFrom(RestStatus.values()); HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus)); - httpResponse.setEntity(new NStringEntity("{\"error\":\"test error message\",\"status\":" + restStatus.getStatus() + "}", - ContentType.APPLICATION_JSON)); + httpResponse.setEntity( + new NStringEntity( + "{\"error\":\"test error message\",\"status\":" + restStatus.getStatus() + "}", + ContentType.APPLICATION_JSON + ) + ); Response response = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse); ResponseException responseException = new ResponseException(response); OpenSearchException openSearchException = restHighLevelClient.parseResponseException(responseException); @@ -365,15 +399,35 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse); when(restClient.performRequest(any(Request.class))).thenReturn(mockResponse); { - Integer result = restHighLevelClient.performRequest(mainRequest, requestConverter, RequestOptions.DEFAULT, - response -> response.getStatusLine().getStatusCode(), Collections.emptySet()); + Integer result = restHighLevelClient.performRequest( + mainRequest, + requestConverter, + RequestOptions.DEFAULT, + response -> response.getStatusLine().getStatusCode(), + Collections.emptySet() + ); assertEquals(restStatus.getStatus(), result.intValue()); } { - IOException ioe = expectThrows(IOException.class, () -> 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, " + - "response=http/1.1 " + restStatus.getStatus() + " " + restStatus.name() + "}", ioe.getMessage()); + IOException ioe = expectThrows( + IOException.class, + () -> 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, " + + "response=http/1.1 " + + restStatus.getStatus() + + " " + + restStatus.name() + + "}", + ioe.getMessage() + ); } } @@ -385,9 +439,16 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse); ResponseException responseException = new ResponseException(mockResponse); when(restClient.performRequest(any(Request.class))).thenThrow(responseException); - OpenSearchException openSearchException = expectThrows(OpenSearchException.class, - () -> restHighLevelClient.performRequest(mainRequest, requestConverter, RequestOptions.DEFAULT, - response -> response.getStatusLine().getStatusCode(), Collections.emptySet())); + OpenSearchException openSearchException = expectThrows( + OpenSearchException.class, + () -> restHighLevelClient.performRequest( + mainRequest, + requestConverter, + RequestOptions.DEFAULT, + response -> response.getStatusLine().getStatusCode(), + Collections.emptySet() + ) + ); assertEquals(responseException.getMessage(), openSearchException.getMessage()); assertEquals(restStatus, openSearchException.status()); assertSame(responseException, openSearchException.getCause()); @@ -398,14 +459,22 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { CheckedFunction requestConverter = request -> new Request(HttpGet.METHOD_NAME, "/"); RestStatus restStatus = randomFrom(RestStatus.values()); HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus)); - httpResponse.setEntity(new NStringEntity("{\"error\":\"test error message\",\"status\":" + restStatus.getStatus() + "}", - ContentType.APPLICATION_JSON)); + httpResponse.setEntity( + new NStringEntity("{\"error\":\"test error message\",\"status\":" + restStatus.getStatus() + "}", ContentType.APPLICATION_JSON) + ); Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse); ResponseException responseException = new ResponseException(mockResponse); when(restClient.performRequest(any(Request.class))).thenThrow(responseException); - OpenSearchException openSearchException = expectThrows(OpenSearchException.class, - () -> restHighLevelClient.performRequest(mainRequest, requestConverter, RequestOptions.DEFAULT, - response -> response.getStatusLine().getStatusCode(), Collections.emptySet())); + OpenSearchException openSearchException = expectThrows( + OpenSearchException.class, + () -> restHighLevelClient.performRequest( + mainRequest, + requestConverter, + RequestOptions.DEFAULT, + response -> response.getStatusLine().getStatusCode(), + Collections.emptySet() + ) + ); assertEquals("OpenSearch exception [type=exception, reason=test error message]", openSearchException.getMessage()); assertEquals(restStatus, openSearchException.status()); assertSame(responseException, openSearchException.getSuppressed()[0]); @@ -420,9 +489,16 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse); ResponseException responseException = new ResponseException(mockResponse); when(restClient.performRequest(any(Request.class))).thenThrow(responseException); - OpenSearchException openSearchException = expectThrows(OpenSearchException.class, - () -> restHighLevelClient.performRequest(mainRequest, requestConverter, RequestOptions.DEFAULT, - response -> response.getStatusLine().getStatusCode(), Collections.emptySet())); + OpenSearchException openSearchException = expectThrows( + OpenSearchException.class, + () -> restHighLevelClient.performRequest( + mainRequest, + requestConverter, + RequestOptions.DEFAULT, + response -> response.getStatusLine().getStatusCode(), + Collections.emptySet() + ) + ); assertEquals("Unable to parse response body", openSearchException.getMessage()); assertEquals(restStatus, openSearchException.status()); assertSame(responseException, openSearchException.getCause()); @@ -438,9 +514,16 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse); ResponseException responseException = new ResponseException(mockResponse); when(restClient.performRequest(any(Request.class))).thenThrow(responseException); - OpenSearchException openSearchException = expectThrows(OpenSearchException.class, - () -> restHighLevelClient.performRequest(mainRequest, requestConverter, RequestOptions.DEFAULT, - response -> response.getStatusLine().getStatusCode(), Collections.emptySet())); + OpenSearchException openSearchException = expectThrows( + OpenSearchException.class, + () -> restHighLevelClient.performRequest( + mainRequest, + requestConverter, + RequestOptions.DEFAULT, + response -> response.getStatusLine().getStatusCode(), + Collections.emptySet() + ) + ); assertEquals("Unable to parse response body", openSearchException.getMessage()); assertEquals(restStatus, openSearchException.status()); assertSame(responseException, openSearchException.getCause()); @@ -454,9 +537,17 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse); ResponseException responseException = new ResponseException(mockResponse); when(restClient.performRequest(any(Request.class))).thenThrow(responseException); - //although we got an exception, we turn it into a successful response because the status code was provided among ignores - assertEquals(Integer.valueOf(404), restHighLevelClient.performRequest(mainRequest, requestConverter, RequestOptions.DEFAULT, - response -> response.getStatusLine().getStatusCode(), Collections.singleton(404))); + // although we got an exception, we turn it into a successful response because the status code was provided among ignores + assertEquals( + Integer.valueOf(404), + restHighLevelClient.performRequest( + mainRequest, + requestConverter, + RequestOptions.DEFAULT, + response -> response.getStatusLine().getStatusCode(), + Collections.singleton(404) + ) + ); } public void testPerformRequestOnResponseExceptionWithIgnoresErrorNoBody() throws IOException { @@ -466,9 +557,16 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse); ResponseException responseException = new ResponseException(mockResponse); 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))); + OpenSearchException openSearchException = expectThrows( + OpenSearchException.class, + () -> restHighLevelClient.performRequest( + mainRequest, + requestConverter, + RequestOptions.DEFAULT, + response -> { throw new IllegalStateException(); }, + Collections.singleton(404) + ) + ); assertEquals(RestStatus.NOT_FOUND, openSearchException.status()); assertSame(responseException, openSearchException.getCause()); assertEquals(responseException.getMessage(), openSearchException.getMessage()); @@ -478,14 +576,20 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { MainRequest mainRequest = new MainRequest(); CheckedFunction requestConverter = request -> new Request(HttpGet.METHOD_NAME, "/"); HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(RestStatus.NOT_FOUND)); - httpResponse.setEntity(new NStringEntity("{\"error\":\"test error message\",\"status\":404}", - ContentType.APPLICATION_JSON)); + httpResponse.setEntity(new NStringEntity("{\"error\":\"test error message\",\"status\":404}", ContentType.APPLICATION_JSON)); Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse); ResponseException responseException = new ResponseException(mockResponse); 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))); + OpenSearchException openSearchException = expectThrows( + OpenSearchException.class, + () -> restHighLevelClient.performRequest( + mainRequest, + requestConverter, + RequestOptions.DEFAULT, + response -> { throw new IllegalStateException(); }, + Collections.singleton(404) + ) + ); assertEquals(RestStatus.NOT_FOUND, openSearchException.status()); assertSame(responseException, openSearchException.getSuppressed()[0]); assertEquals("OpenSearch exception [type=exception, reason=test error message]", openSearchException.getMessage()); @@ -495,7 +599,10 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { { TrackingActionListener trackingActionListener = new TrackingActionListener(); ResponseListener responseListener = restHighLevelClient.wrapResponseListener( - response -> response.getStatusLine().getStatusCode(), trackingActionListener, Collections.emptySet()); + response -> response.getStatusLine().getStatusCode(), + trackingActionListener, + Collections.emptySet() + ); RestStatus restStatus = randomFrom(RestStatus.values()); HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus)); responseListener.onSuccess(new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse)); @@ -505,14 +612,24 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { { TrackingActionListener trackingActionListener = new TrackingActionListener(); ResponseListener responseListener = restHighLevelClient.wrapResponseListener( - response -> {throw new IllegalStateException();}, trackingActionListener, Collections.emptySet()); + response -> { throw new IllegalStateException(); }, + trackingActionListener, + Collections.emptySet() + ); RestStatus restStatus = randomFrom(RestStatus.values()); HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus)); responseListener.onSuccess(new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse)); assertThat(trackingActionListener.exception.get(), instanceOf(IOException.class)); IOException ioe = (IOException) trackingActionListener.exception.get(); - assertEquals("Unable to parse response body for Response{requestLine=GET / http/1.1, host=http://localhost:9200, " + - "response=http/1.1 " + restStatus.getStatus() + " " + restStatus.name() + "}", ioe.getMessage()); + assertEquals( + "Unable to parse response body for Response{requestLine=GET / http/1.1, host=http://localhost:9200, " + + "response=http/1.1 " + + restStatus.getStatus() + + " " + + restStatus.name() + + "}", + ioe.getMessage() + ); assertThat(ioe.getCause(), instanceOf(IllegalStateException.class)); } } @@ -520,7 +637,10 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { public void testWrapResponseListenerOnException() { TrackingActionListener trackingActionListener = new TrackingActionListener(); ResponseListener responseListener = restHighLevelClient.wrapResponseListener( - response -> response.getStatusLine().getStatusCode(), trackingActionListener, Collections.emptySet()); + response -> response.getStatusLine().getStatusCode(), + trackingActionListener, + Collections.emptySet() + ); IllegalStateException exception = new IllegalStateException(); responseListener.onFailure(exception); assertSame(exception, trackingActionListener.exception.get()); @@ -529,7 +649,10 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { public void testWrapResponseListenerOnResponseExceptionWithoutEntity() throws IOException { TrackingActionListener trackingActionListener = new TrackingActionListener(); ResponseListener responseListener = restHighLevelClient.wrapResponseListener( - response -> response.getStatusLine().getStatusCode(), trackingActionListener, Collections.emptySet()); + response -> response.getStatusLine().getStatusCode(), + trackingActionListener, + Collections.emptySet() + ); RestStatus restStatus = randomFrom(RestStatus.values()); HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus)); Response response = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse); @@ -545,16 +668,20 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { public void testWrapResponseListenerOnResponseExceptionWithEntity() throws IOException { TrackingActionListener trackingActionListener = new TrackingActionListener(); ResponseListener responseListener = restHighLevelClient.wrapResponseListener( - response -> response.getStatusLine().getStatusCode(), trackingActionListener, Collections.emptySet()); + response -> response.getStatusLine().getStatusCode(), + trackingActionListener, + Collections.emptySet() + ); RestStatus restStatus = randomFrom(RestStatus.values()); HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus)); - httpResponse.setEntity(new NStringEntity("{\"error\":\"test error message\",\"status\":" + restStatus.getStatus() + "}", - ContentType.APPLICATION_JSON)); + httpResponse.setEntity( + new NStringEntity("{\"error\":\"test error message\",\"status\":" + restStatus.getStatus() + "}", ContentType.APPLICATION_JSON) + ); Response response = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse); ResponseException responseException = new ResponseException(response); responseListener.onFailure(responseException); assertThat(trackingActionListener.exception.get(), instanceOf(OpenSearchException.class)); - OpenSearchException openSearchException = (OpenSearchException)trackingActionListener.exception.get(); + OpenSearchException openSearchException = (OpenSearchException) trackingActionListener.exception.get(); assertEquals("OpenSearch exception [type=exception, reason=test error message]", openSearchException.getMessage()); assertEquals(restStatus, openSearchException.status()); assertSame(responseException, openSearchException.getSuppressed()[0]); @@ -564,7 +691,10 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { { TrackingActionListener trackingActionListener = new TrackingActionListener(); ResponseListener responseListener = restHighLevelClient.wrapResponseListener( - response -> response.getStatusLine().getStatusCode(), trackingActionListener, Collections.emptySet()); + response -> response.getStatusLine().getStatusCode(), + trackingActionListener, + Collections.emptySet() + ); RestStatus restStatus = randomFrom(RestStatus.values()); HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus)); httpResponse.setEntity(new NStringEntity("{\"error\":", ContentType.APPLICATION_JSON)); @@ -572,7 +702,7 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { ResponseException responseException = new ResponseException(response); responseListener.onFailure(responseException); assertThat(trackingActionListener.exception.get(), instanceOf(OpenSearchException.class)); - OpenSearchException openSearchException = (OpenSearchException)trackingActionListener.exception.get(); + OpenSearchException openSearchException = (OpenSearchException) trackingActionListener.exception.get(); assertEquals("Unable to parse response body", openSearchException.getMessage()); assertEquals(restStatus, openSearchException.status()); assertSame(responseException, openSearchException.getCause()); @@ -581,7 +711,10 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { { TrackingActionListener trackingActionListener = new TrackingActionListener(); ResponseListener responseListener = restHighLevelClient.wrapResponseListener( - response -> response.getStatusLine().getStatusCode(), trackingActionListener, Collections.emptySet()); + response -> response.getStatusLine().getStatusCode(), + trackingActionListener, + Collections.emptySet() + ); RestStatus restStatus = randomFrom(RestStatus.values()); HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus)); httpResponse.setEntity(new NStringEntity("{\"status\":" + restStatus.getStatus() + "}", ContentType.APPLICATION_JSON)); @@ -589,7 +722,7 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { ResponseException responseException = new ResponseException(response); responseListener.onFailure(responseException); assertThat(trackingActionListener.exception.get(), instanceOf(OpenSearchException.class)); - OpenSearchException openSearchException = (OpenSearchException)trackingActionListener.exception.get(); + OpenSearchException openSearchException = (OpenSearchException) trackingActionListener.exception.get(); assertEquals("Unable to parse response body", openSearchException.getMessage()); assertEquals(restStatus, openSearchException.status()); assertSame(responseException, openSearchException.getCause()); @@ -600,28 +733,34 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { public void testWrapResponseListenerOnResponseExceptionWithIgnores() throws IOException { TrackingActionListener trackingActionListener = new TrackingActionListener(); ResponseListener responseListener = restHighLevelClient.wrapResponseListener( - response -> response.getStatusLine().getStatusCode(), trackingActionListener, Collections.singleton(404)); + response -> response.getStatusLine().getStatusCode(), + trackingActionListener, + Collections.singleton(404) + ); HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(RestStatus.NOT_FOUND)); Response response = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse); ResponseException responseException = new ResponseException(response); responseListener.onFailure(responseException); - //although we got an exception, we turn it into a successful response because the status code was provided among ignores + // although we got an exception, we turn it into a successful response because the status code was provided among ignores assertNull(trackingActionListener.exception.get()); assertEquals(404, trackingActionListener.statusCode.get()); } public void testWrapResponseListenerOnResponseExceptionWithIgnoresErrorNoBody() throws IOException { TrackingActionListener trackingActionListener = new TrackingActionListener(); - //response parsing throws exception while handling ignores. same as when GetResponse#fromXContent throws error when trying - //to parse a 404 response which contains an error rather than a valid document not found response. + // response parsing throws exception while handling ignores. same as when GetResponse#fromXContent throws error when trying + // to parse a 404 response which contains an error rather than a valid document not found response. ResponseListener responseListener = restHighLevelClient.wrapResponseListener( - response -> { throw new IllegalStateException(); }, trackingActionListener, Collections.singleton(404)); + response -> { throw new IllegalStateException(); }, + trackingActionListener, + Collections.singleton(404) + ); HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(RestStatus.NOT_FOUND)); Response response = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse); ResponseException responseException = new ResponseException(response); responseListener.onFailure(responseException); assertThat(trackingActionListener.exception.get(), instanceOf(OpenSearchException.class)); - OpenSearchException openSearchException = (OpenSearchException)trackingActionListener.exception.get(); + OpenSearchException openSearchException = (OpenSearchException) trackingActionListener.exception.get(); assertEquals(RestStatus.NOT_FOUND, openSearchException.status()); assertSame(responseException, openSearchException.getCause()); assertEquals(responseException.getMessage(), openSearchException.getMessage()); @@ -629,18 +768,20 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { public void testWrapResponseListenerOnResponseExceptionWithIgnoresErrorValidBody() throws IOException { TrackingActionListener trackingActionListener = new TrackingActionListener(); - //response parsing throws exception while handling ignores. same as when GetResponse#fromXContent throws error when trying - //to parse a 404 response which contains an error rather than a valid document not found response. + // response parsing throws exception while handling ignores. same as when GetResponse#fromXContent throws error when trying + // to parse a 404 response which contains an error rather than a valid document not found response. ResponseListener responseListener = restHighLevelClient.wrapResponseListener( - response -> { throw new IllegalStateException(); }, trackingActionListener, Collections.singleton(404)); + response -> { throw new IllegalStateException(); }, + trackingActionListener, + Collections.singleton(404) + ); HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(RestStatus.NOT_FOUND)); - httpResponse.setEntity(new NStringEntity("{\"error\":\"test error message\",\"status\":404}", - ContentType.APPLICATION_JSON)); + httpResponse.setEntity(new NStringEntity("{\"error\":\"test error message\",\"status\":404}", ContentType.APPLICATION_JSON)); Response response = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse); ResponseException responseException = new ResponseException(response); responseListener.onFailure(responseException); assertThat(trackingActionListener.exception.get(), instanceOf(OpenSearchException.class)); - OpenSearchException openSearchException = (OpenSearchException)trackingActionListener.exception.get(); + OpenSearchException openSearchException = (OpenSearchException) trackingActionListener.exception.get(); assertEquals(RestStatus.NOT_FOUND, openSearchException.status()); assertSame(responseException, openSearchException.getSuppressed()[0]); assertEquals("OpenSearch exception [type=exception, reason=test error message]", openSearchException.getMessage()); @@ -695,8 +836,8 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { } public void testApiNamingConventions() throws Exception { - //this list should be empty once the high-level client is feature complete - String[] notYetSupportedApi = new String[]{ + // this list should be empty once the high-level client is feature complete + String[] notYetSupportedApi = new String[] { "create", "get_script_context", "get_script_languages", @@ -707,9 +848,8 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { "scripts_painless_execute", "indices.simulate_template", "indices.resolve_index", - "indices.add_block" - }; - //These API are not required for high-level client feature completeness + "indices.add_block" }; + // These API are not required for high-level client feature completeness String[] notRequiredApi = new String[] { "cluster.allocation_explain", "cluster.pending_tasks", @@ -732,12 +872,8 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { "nodes.hot_threads", "nodes.usage", "nodes.reload_secure_settings", - "search_shards", - }; - List booleanReturnMethods = Arrays.asList( - "security.enable_user", - "security.disable_user", - "security.change_password"); + "search_shards", }; + List booleanReturnMethods = Arrays.asList("security.enable_user", "security.disable_user", "security.change_password"); Set deprecatedMethods = new HashSet<>(); deprecatedMethods.add("indices.force_merge"); deprecatedMethods.add("multi_get"); @@ -754,14 +890,18 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { topLevelMethodsExclusions.add("close"); Map> methods = Arrays.stream(RestHighLevelClient.class.getMethods()) - .filter(method -> method.getDeclaringClass().equals(RestHighLevelClient.class) - && topLevelMethodsExclusions.contains(method.getName()) == false) - .map(method -> Tuple.tuple(toSnakeCase(method.getName()), method)) - .flatMap(tuple -> tuple.v2().getReturnType().getName().endsWith("Client") - ? getSubClientMethods(tuple.v1(), tuple.v2().getReturnType()) : Stream.of(tuple)) - .filter(tuple -> tuple.v2().getAnnotation(Deprecated.class) == null) - .collect(Collectors.groupingBy(Tuple::v1, - Collectors.mapping(Tuple::v2, Collectors.toSet()))); + .filter( + method -> method.getDeclaringClass().equals(RestHighLevelClient.class) + && topLevelMethodsExclusions.contains(method.getName()) == false + ) + .map(method -> Tuple.tuple(toSnakeCase(method.getName()), method)) + .flatMap( + tuple -> tuple.v2().getReturnType().getName().endsWith("Client") + ? getSubClientMethods(tuple.v1(), tuple.v2().getReturnType()) + : Stream.of(tuple) + ) + .filter(tuple -> tuple.v2().getAnnotation(Deprecated.class) == null) + .collect(Collectors.groupingBy(Tuple::v1, Collectors.mapping(Tuple::v2, Collectors.toSet()))); // TODO remove in 8.0 - we will undeprecate indices.get_template because the current getIndexTemplate // impl will replace the existing getTemplate method. @@ -776,11 +916,13 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { String apiName = entry.getKey(); for (Method method : entry.getValue()) { - assertTrue("method [" + apiName + "] is not final", - Modifier.isFinal(method.getClass().getModifiers()) || Modifier.isFinal(method.getModifiers())); + assertTrue( + "method [" + apiName + "] is not final", + Modifier.isFinal(method.getClass().getModifiers()) || Modifier.isFinal(method.getModifiers()) + ); assertTrue("method [" + method + "] should be public", Modifier.isPublic(method.getModifiers())); - //we convert all the method names to snake case, hence we need to look for the '_async' suffix rather than 'Async' + // we convert all the method names to snake case, hence we need to look for the '_async' suffix rather than 'Async' if (apiName.endsWith("_async")) { assertAsyncMethod(methods, method, apiName); } else if (isSubmitTaskMethod(apiName)) { @@ -790,12 +932,14 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { apiUnsupported.remove(apiName); if (apiSpec.contains(apiName) == false) { if (deprecatedMethods.contains(apiName)) { - assertTrue("method [" + method.getName() + "], api [" + apiName + "] should be deprecated", - method.isAnnotationPresent(Deprecated.class)); + assertTrue( + "method [" + method.getName() + "], api [" + apiName + "] should be deprecated", + method.isAnnotationPresent(Deprecated.class) + ); } else { if (// IndicesClientIT.getIndexTemplate should be renamed "getTemplate" in version 8.0 when we // can get rid of 7.0's deprecated "getTemplate" - apiName.equals("indices.get_index_template") == false ) { + apiName.equals("indices.get_index_template") == false) { apiNotFound.add(apiName); } } @@ -803,56 +947,86 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { } } } - assertThat("Some client method doesn't match a corresponding API defined in the REST spec: " + apiNotFound, - apiNotFound.size(), equalTo(0)); + assertThat( + "Some client method doesn't match a corresponding API defined in the REST spec: " + apiNotFound, + apiNotFound.size(), + equalTo(0) + ); - //we decided not to support cat API in the high-level REST client, they are supposed to be used from a low-level client + // we decided not to support cat API in the high-level REST client, they are supposed to be used from a low-level client apiUnsupported.removeIf(api -> api.startsWith("cat.")); - Stream.concat(Arrays.stream(notYetSupportedApi), Arrays.stream(notRequiredApi)).forEach( - api -> assertTrue(api + " API is either not defined in the spec or already supported by the high-level client", - apiUnsupported.remove(api))); + Stream.concat(Arrays.stream(notYetSupportedApi), Arrays.stream(notRequiredApi)) + .forEach( + api -> assertTrue( + api + " API is either not defined in the spec or already supported by the high-level client", + apiUnsupported.remove(api) + ) + ); assertThat("Some API are not supported but they should be: " + apiUnsupported, apiUnsupported.size(), equalTo(0)); } private static void assertSyncMethod(Method method, String apiName, List booleanReturnMethods) { - //A few methods return a boolean rather than a response object + // A few methods return a boolean rather than a response object if (apiName.equals("ping") || apiName.contains("exist") || booleanReturnMethods.contains(apiName)) { - assertThat("the return type for method [" + method + "] is incorrect", - method.getReturnType().getSimpleName(), equalTo("boolean")); + assertThat( + "the return type for method [" + method + "] is incorrect", + method.getReturnType().getSimpleName(), + equalTo("boolean") + ); } else { // It's acceptable for 404s to be represented as empty Optionals if (!method.getReturnType().isAssignableFrom(Optional.class)) { - assertThat("the return type for method [" + method + "] is incorrect", - method.getReturnType().getSimpleName(), endsWith("Response")); + assertThat( + "the return type for method [" + method + "] is incorrect", + method.getReturnType().getSimpleName(), + endsWith("Response") + ); } } assertEquals("incorrect number of exceptions for method [" + method + "]", 1, method.getExceptionTypes().length); - //a few methods don't accept a request object as argument + // a few methods don't accept a request object as argument if (APIS_WITHOUT_REQUEST_OBJECT.contains(apiName)) { assertEquals("incorrect number of arguments for method [" + method + "]", 1, method.getParameterTypes().length); - assertThat("the parameter to method [" + method + "] is the wrong type", - method.getParameterTypes()[0], equalTo(RequestOptions.class)); + assertThat( + "the parameter to method [" + method + "] is the wrong type", + method.getParameterTypes()[0], + equalTo(RequestOptions.class) + ); } else { assertEquals("incorrect number of arguments for method [" + method + "]", 2, method.getParameterTypes().length); // This is no longer true for all methods. Some methods can contain these 2 args backwards because of deprecation if (method.getParameterTypes()[0].equals(RequestOptions.class)) { - assertThat("the first parameter to method [" + method + "] is the wrong type", - method.getParameterTypes()[0], equalTo(RequestOptions.class)); - assertThat("the second parameter to method [" + method + "] is the wrong type", - method.getParameterTypes()[1].getSimpleName(), endsWith("Request")); + assertThat( + "the first parameter to method [" + method + "] is the wrong type", + method.getParameterTypes()[0], + equalTo(RequestOptions.class) + ); + assertThat( + "the second parameter to method [" + method + "] is the wrong type", + method.getParameterTypes()[1].getSimpleName(), + endsWith("Request") + ); } else { - assertThat("the first parameter to method [" + method + "] is the wrong type", - method.getParameterTypes()[0].getSimpleName(), endsWith("Request")); - assertThat("the second parameter to method [" + method + "] is the wrong type", - method.getParameterTypes()[1], equalTo(RequestOptions.class)); + assertThat( + "the first parameter to method [" + method + "] is the wrong type", + method.getParameterTypes()[0].getSimpleName(), + endsWith("Request") + ); + assertThat( + "the second parameter to method [" + method + "] is the wrong type", + method.getParameterTypes()[1], + equalTo(RequestOptions.class) + ); } } } private static void assertAsyncMethod(Map> methods, Method method, String apiName) { - assertTrue("async method [" + method.getName() + "] doesn't have corresponding sync method", - methods.containsKey(apiName.substring(0, apiName.length() - 6))); + assertTrue( + "async method [" + method.getName() + "] doesn't have corresponding sync method", + methods.containsKey(apiName.substring(0, apiName.length() - 6)) + ); assertThat("async method [" + method + "] should return Cancellable", method.getReturnType(), equalTo(Cancellable.class)); assertEquals("async method [" + method + "] should not throw any exceptions", 0, method.getExceptionTypes().length); if (APIS_WITHOUT_REQUEST_OBJECT.contains(apiName.replaceAll("_async$", ""))) { @@ -863,34 +1037,61 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { assertEquals("async method [" + method + "] has the wrong number of arguments", 3, method.getParameterTypes().length); // This is no longer true for all methods. Some methods can contain these 2 args backwards because of deprecation if (method.getParameterTypes()[0].equals(RequestOptions.class)) { - assertThat("the first parameter to async method [" + method + "] should be a request type", - method.getParameterTypes()[0], equalTo(RequestOptions.class)); - assertThat("the second parameter to async method [" + method + "] is the wrong type", - method.getParameterTypes()[1].getSimpleName(), endsWith("Request")); + assertThat( + "the first parameter to async method [" + method + "] should be a request type", + method.getParameterTypes()[0], + equalTo(RequestOptions.class) + ); + assertThat( + "the second parameter to async method [" + method + "] is the wrong type", + method.getParameterTypes()[1].getSimpleName(), + endsWith("Request") + ); } else { - assertThat("the first parameter to async method [" + method + "] should be a request type", - method.getParameterTypes()[0].getSimpleName(), endsWith("Request")); - assertThat("the second parameter to async method [" + method + "] is the wrong type", - method.getParameterTypes()[1], equalTo(RequestOptions.class)); + assertThat( + "the first parameter to async method [" + method + "] should be a request type", + method.getParameterTypes()[0].getSimpleName(), + endsWith("Request") + ); + assertThat( + "the second parameter to async method [" + method + "] is the wrong type", + method.getParameterTypes()[1], + equalTo(RequestOptions.class) + ); } - assertThat("the third parameter to async method [" + method + "] is the wrong type", - method.getParameterTypes()[2], equalTo(ActionListener.class)); + assertThat( + "the third parameter to async method [" + method + "] is the wrong type", + method.getParameterTypes()[2], + equalTo(ActionListener.class) + ); } } - private static void assertSubmitTaskMethod(Map> methods, Method method, String apiName, - ClientYamlSuiteRestSpec restSpec) { + private static void assertSubmitTaskMethod( + Map> methods, + Method method, + String apiName, + ClientYamlSuiteRestSpec restSpec + ) { String methodName = extractMethodName(apiName); - assertTrue("submit task method [" + method.getName() + "] doesn't have corresponding sync method", - methods.containsKey(methodName)); + assertTrue("submit task method [" + method.getName() + "] doesn't have corresponding sync method", methods.containsKey(methodName)); assertEquals("submit task method [" + method + "] has the wrong number of arguments", 2, method.getParameterTypes().length); - assertThat("the first parameter to submit task method [" + method + "] is the wrong type", - method.getParameterTypes()[0].getSimpleName(), endsWith("Request")); - assertThat("the second parameter to submit task method [" + method + "] is the wrong type", - method.getParameterTypes()[1], equalTo(RequestOptions.class)); + assertThat( + "the first parameter to submit task method [" + method + "] is the wrong type", + method.getParameterTypes()[0].getSimpleName(), + endsWith("Request") + ); + assertThat( + "the second parameter to submit task method [" + method + "] is the wrong type", + method.getParameterTypes()[1], + equalTo(RequestOptions.class) + ); - assertThat("submit task method [" + method + "] must have wait_for_completion parameter in rest spec", - restSpec.getApi(methodName).getParams(), Matchers.hasKey("wait_for_completion")); + assertThat( + "submit task method [" + method + "] must have wait_for_completion parameter in rest spec", + restSpec.getApi(methodName).getParams(), + Matchers.hasKey("wait_for_completion") + ); } private static String extractMethodName(String apiName) { @@ -902,10 +1103,14 @@ public class RestHighLevelClientTests extends OpenSearchTestCase { } private static Stream> getSubClientMethods(String namespace, Class clientClass) { - return Arrays.stream(clientClass.getMethods()).filter(method -> method.getDeclaringClass().equals(clientClass)) - .map(method -> Tuple.tuple(namespace + "." + toSnakeCase(method.getName()), method)) - .flatMap(tuple -> tuple.v2().getReturnType().getName().endsWith("Client") - ? getSubClientMethods(tuple.v1(), tuple.v2().getReturnType()) : Stream.of(tuple)); + return Arrays.stream(clientClass.getMethods()) + .filter(method -> method.getDeclaringClass().equals(clientClass)) + .map(method -> Tuple.tuple(namespace + "." + toSnakeCase(method.getName()), method)) + .flatMap( + tuple -> tuple.v2().getReturnType().getName().endsWith("Client") + ? getSubClientMethods(tuple.v1(), tuple.v2().getReturnType()) + : Stream.of(tuple) + ); } private static String toSnakeCase(String camelCase) { diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/SearchIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/SearchIT.java index f5f79ffa471..5a72e4452c5 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/SearchIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/SearchIT.java @@ -159,15 +159,16 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { { Request create = new Request("PUT", "/index2"); create.setJsonEntity( - "{" + - " \"mappings\": {" + - " \"properties\": {" + - " \"rating\": {" + - " \"type\": \"keyword\"" + - " }" + - " }" + - " }" + - "}"); + "{" + + " \"mappings\": {" + + " \"properties\": {" + + " \"rating\": {" + + " \"type\": \"keyword\"" + + " }" + + " }" + + " }" + + "}" + ); client().performRequest(create); Request doc3 = new Request(HttpPut.METHOD_NAME, "/index2/_doc/3"); doc3.setJsonEntity("{\"id\":3, \"field\":\"value1\", \"rating\": \"good\"}"); @@ -189,20 +190,21 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { { Request create = new Request(HttpPut.METHOD_NAME, "/index4"); create.setJsonEntity( - "{" + - " \"mappings\": {" + - " \"properties\": {" + - " \"field1\": {" + - " \"type\": \"keyword\"," + - " \"store\": true" + - " }," + - " \"field2\": {" + - " \"type\": \"keyword\"," + - " \"store\": true" + - " }" + - " }" + - " }" + - "}"); + "{" + + " \"mappings\": {" + + " \"properties\": {" + + " \"field1\": {" + + " \"type\": \"keyword\"," + + " \"store\": true" + + " }," + + " \"field2\": {" + + " \"type\": \"keyword\"," + + " \"store\": true" + + " }" + + " }" + + " }" + + "}" + ); client().performRequest(create); Request doc1 = new Request(HttpPut.METHOD_NAME, "/index4/_doc/1"); doc1.setJsonEntity("{\"id\":1, \"field1\":\"value1\", \"field2\":\"value2\"}"); @@ -210,17 +212,18 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { Request createFilteredAlias = new Request(HttpPost.METHOD_NAME, "/_aliases"); createFilteredAlias.setJsonEntity( - "{" + - " \"actions\" : [" + - " {" + - " \"add\" : {" + - " \"index\" : \"index4\"," + - " \"alias\" : \"alias4\"," + - " \"filter\" : { \"term\" : { \"field2\" : \"value1\" } }" + - " }" + - " }" + - " ]" + - "}"); + "{" + + " \"actions\" : [" + + " {" + + " \"add\" : {" + + " \"index\" : \"index4\"," + + " \"alias\" : \"alias4\"," + + " \"filter\" : { \"term\" : { \"field2\" : \"value1\" } }" + + " }" + + " }" + + " ]" + + "}" + ); client().performRequest(createFilteredAlias); } @@ -276,8 +279,7 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { public void testSearchWithTermsAgg() throws IOException { SearchRequest searchRequest = new SearchRequest(); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); - searchSourceBuilder.aggregation(new TermsAggregationBuilder("agg1").userValueTypeHint(ValueType.STRING) - .field("type.keyword")); + searchSourceBuilder.aggregation(new TermsAggregationBuilder("agg1").userValueTypeHint(ValueType.STRING).field("type.keyword")); searchSourceBuilder.size(0); searchRequest.source(searchSourceBuilder); SearchResponse searchResponse = execute(searchRequest, highLevelClient()::search, highLevelClient()::searchAsync); @@ -300,8 +302,9 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { public void testSearchWithRareTermsAgg() throws IOException { SearchRequest searchRequest = new SearchRequest(); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); - searchSourceBuilder.aggregation(new RareTermsAggregationBuilder("agg1").userValueTypeHint(ValueType.STRING) - .field("type.keyword").maxDocCount(2)); + searchSourceBuilder.aggregation( + new RareTermsAggregationBuilder("agg1").userValueTypeHint(ValueType.STRING).field("type.keyword").maxDocCount(2) + ); searchSourceBuilder.size(0); searchRequest.source(searchSourceBuilder); SearchResponse searchResponse = execute(searchRequest, highLevelClient()::search, highLevelClient()::searchAsync); @@ -320,8 +323,9 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { public void testSearchWithCompositeAgg() throws IOException { SearchRequest searchRequest = new SearchRequest(); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); - List> sources - = Collections.singletonList(new TermsValuesSourceBuilder("terms").field("type.keyword").missingBucket(true).order("asc")); + List> sources = Collections.singletonList( + new TermsValuesSourceBuilder("terms").field("type.keyword").missingBucket(true).order("asc") + ); searchSourceBuilder.aggregation(AggregationBuilders.composite("composite", sources)); searchSourceBuilder.size(0); searchRequest.source(searchSourceBuilder); @@ -353,15 +357,18 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { searchSourceBuilder.size(0); searchRequest.source(searchSourceBuilder); - OpenSearchStatusException exception = expectThrows(OpenSearchStatusException.class, - () -> execute(searchRequest, highLevelClient()::search, highLevelClient()::searchAsync)); + OpenSearchStatusException exception = expectThrows( + OpenSearchStatusException.class, + () -> execute(searchRequest, highLevelClient()::search, highLevelClient()::searchAsync) + ); assertEquals(RestStatus.BAD_REQUEST, exception.status()); } SearchRequest searchRequest = new SearchRequest("index"); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); - searchSourceBuilder.aggregation(new RangeAggregationBuilder("agg1").field("num") - .addRange("first", 0, 30).addRange("second", 31, 200)); + searchSourceBuilder.aggregation( + new RangeAggregationBuilder("agg1").field("num").addRange("first", 0, 30).addRange("second", 31, 200) + ); searchSourceBuilder.size(0); searchRequest.source(searchSourceBuilder); SearchResponse searchResponse = execute(searchRequest, highLevelClient()::search, highLevelClient()::searchAsync); @@ -390,8 +397,7 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { SearchRequest searchRequest = new SearchRequest("index"); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); TermsAggregationBuilder agg = new TermsAggregationBuilder("agg1").userValueTypeHint(ValueType.STRING).field("type.keyword"); - agg.subAggregation(new RangeAggregationBuilder("subagg").field("num") - .addRange("first", 0, 30).addRange("second", 31, 200)); + agg.subAggregation(new RangeAggregationBuilder("subagg").field("num").addRange("first", 0, 30).addRange("second", 31, 200)); searchSourceBuilder.aggregation(agg); searchSourceBuilder.size(0); searchRequest.source(searchSourceBuilder); @@ -444,9 +450,9 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { SearchRequest searchRequest = new SearchRequest("index"); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); TermsAggregationBuilder agg = new TermsAggregationBuilder("agg1").userValueTypeHint(ValueType.STRING).field("type.keyword"); - agg.subAggregation(new WeightedAvgAggregationBuilder("subagg") - .value(new MultiValuesSourceFieldConfig.Builder().setFieldName("num").build()) - .weight(new MultiValuesSourceFieldConfig.Builder().setFieldName("num2").build()) + agg.subAggregation( + new WeightedAvgAggregationBuilder("subagg").value(new MultiValuesSourceFieldConfig.Builder().setFieldName("num").build()) + .weight(new MultiValuesSourceFieldConfig.Builder().setFieldName("num2").build()) ); searchSourceBuilder.aggregation(agg); searchSourceBuilder.size(0); @@ -509,73 +515,78 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { final String indexName = "child_example"; Request createIndex = new Request(HttpPut.METHOD_NAME, "/" + indexName); createIndex.setJsonEntity( - "{\n" + - " \"mappings\": {\n" + - " \"properties\" : {\n" + - " \"qa_join_field\" : {\n" + - " \"type\" : \"join\",\n" + - " \"relations\" : { \"question\" : \"answer\" }\n" + - " }\n" + - " }\n" + - " }" + - "}"); + "{\n" + + " \"mappings\": {\n" + + " \"properties\" : {\n" + + " \"qa_join_field\" : {\n" + + " \"type\" : \"join\",\n" + + " \"relations\" : { \"question\" : \"answer\" }\n" + + " }\n" + + " }\n" + + " }" + + "}" + ); client().performRequest(createIndex); Request questionDoc = new Request(HttpPut.METHOD_NAME, "/" + indexName + "/_doc/1"); questionDoc.setJsonEntity( - "{\n" + - " \"body\": \"

I have Windows 2003 server and i bought a new Windows 2008 server...\",\n" + - " \"title\": \"Whats the best way to file transfer my site from server to a newer one?\",\n" + - " \"tags\": [\n" + - " \"windows-server-2003\",\n" + - " \"windows-server-2008\",\n" + - " \"file-transfer\"\n" + - " ],\n" + - " \"qa_join_field\" : \"question\"\n" + - "}"); + "{\n" + + " \"body\": \"

I have Windows 2003 server and i bought a new Windows 2008 server...\",\n" + + " \"title\": \"Whats the best way to file transfer my site from server to a newer one?\",\n" + + " \"tags\": [\n" + + " \"windows-server-2003\",\n" + + " \"windows-server-2008\",\n" + + " \"file-transfer\"\n" + + " ],\n" + + " \"qa_join_field\" : \"question\"\n" + + "}" + ); client().performRequest(questionDoc); Request answerDoc1 = new Request(HttpPut.METHOD_NAME, "/" + indexName + "/_doc/2"); answerDoc1.addParameter("routing", "1"); answerDoc1.setJsonEntity( - "{\n" + - " \"owner\": {\n" + - " \"location\": \"Norfolk, United Kingdom\",\n" + - " \"display_name\": \"Sam\",\n" + - " \"id\": 48\n" + - " },\n" + - " \"body\": \"

Unfortunately you're pretty much limited to FTP...\",\n" + - " \"qa_join_field\" : {\n" + - " \"name\" : \"answer\",\n" + - " \"parent\" : \"1\"\n" + - " },\n" + - " \"creation_date\": \"2009-05-04T13:45:37.030\"\n" + - "}"); + "{\n" + + " \"owner\": {\n" + + " \"location\": \"Norfolk, United Kingdom\",\n" + + " \"display_name\": \"Sam\",\n" + + " \"id\": 48\n" + + " },\n" + + " \"body\": \"

Unfortunately you're pretty much limited to FTP...\",\n" + + " \"qa_join_field\" : {\n" + + " \"name\" : \"answer\",\n" + + " \"parent\" : \"1\"\n" + + " },\n" + + " \"creation_date\": \"2009-05-04T13:45:37.030\"\n" + + "}" + ); client().performRequest(answerDoc1); Request answerDoc2 = new Request(HttpPut.METHOD_NAME, "/" + indexName + "/_doc/3"); answerDoc2.addParameter("routing", "1"); answerDoc2.setJsonEntity( - "{\n" + - " \"owner\": {\n" + - " \"location\": \"Norfolk, United Kingdom\",\n" + - " \"display_name\": \"Troll\",\n" + - " \"id\": 49\n" + - " },\n" + - " \"body\": \"

Use Linux...\",\n" + - " \"qa_join_field\" : {\n" + - " \"name\" : \"answer\",\n" + - " \"parent\" : \"1\"\n" + - " },\n" + - " \"creation_date\": \"2009-05-05T13:45:37.030\"\n" + - "}"); + "{\n" + + " \"owner\": {\n" + + " \"location\": \"Norfolk, United Kingdom\",\n" + + " \"display_name\": \"Troll\",\n" + + " \"id\": 49\n" + + " },\n" + + " \"body\": \"

Use Linux...\",\n" + + " \"qa_join_field\" : {\n" + + " \"name\" : \"answer\",\n" + + " \"parent\" : \"1\"\n" + + " },\n" + + " \"creation_date\": \"2009-05-05T13:45:37.030\"\n" + + "}" + ); client().performRequest(answerDoc2); client().performRequest(new Request(HttpPost.METHOD_NAME, "/_refresh")); - TermsAggregationBuilder leafTermAgg = new TermsAggregationBuilder("top-names") - .userValueTypeHint(ValueType.STRING) - .field("owner.display_name.keyword").size(10); + TermsAggregationBuilder leafTermAgg = new TermsAggregationBuilder("top-names").userValueTypeHint(ValueType.STRING) + .field("owner.display_name.keyword") + .size(10); ChildrenAggregationBuilder childrenAgg = new ChildrenAggregationBuilder("to-answers", "answer").subAggregation(leafTermAgg); TermsAggregationBuilder termsAgg = new TermsAggregationBuilder("top-tags").userValueTypeHint(ValueType.STRING) - .field("tags.keyword") - .size(10).subAggregation(childrenAgg); + .field("tags.keyword") + .size(10) + .subAggregation(childrenAgg); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.size(0).aggregation(termsAgg); SearchRequest searchRequest = new SearchRequest(indexName); @@ -594,8 +605,10 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { assertEquals(0, terms.getSumOfOtherDocCounts()); assertEquals(3, terms.getBuckets().size()); for (Terms.Bucket bucket : terms.getBuckets()) { - assertThat(bucket.getKeyAsString(), - either(equalTo("file-transfer")).or(equalTo("windows-server-2003")).or(equalTo("windows-server-2008"))); + assertThat( + bucket.getKeyAsString(), + either(equalTo("file-transfer")).or(equalTo("windows-server-2003")).or(equalTo("windows-server-2008")) + ); assertEquals(1, bucket.getDocCount()); assertEquals(1, bucket.getAggregations().asList().size()); Children children = bucket.getAggregations().get("to-answers"); @@ -616,8 +629,7 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { public void testSearchWithSuggest() throws IOException { SearchRequest searchRequest = new SearchRequest("index"); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); - searchSourceBuilder.suggest(new SuggestBuilder().addSuggestion("sugg1", new PhraseSuggestionBuilder("type")) - .setGlobalText("type")); + searchSourceBuilder.suggest(new SuggestBuilder().addSuggestion("sugg1", new PhraseSuggestionBuilder("type")).setGlobalText("type")); searchSourceBuilder.size(0); searchRequest.source(searchSourceBuilder); @@ -630,14 +642,15 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { assertEquals(0, searchResponse.getHits().getHits().length); assertEquals(1, searchResponse.getSuggest().size()); - Suggest.Suggestion> sugg = searchResponse - .getSuggest().iterator().next(); + Suggest.Suggestion> sugg = searchResponse.getSuggest() + .iterator() + .next(); assertEquals("sugg1", sugg.getName()); for (Suggest.Suggestion.Entry options : sugg) { assertEquals("type", options.getText().string()); assertEquals(0, options.getOffset()); assertEquals(4, options.getLength()); - assertEquals(2 ,options.getOptions().size()); + assertEquals(2, options.getOptions().size()); for (Suggest.Suggestion.Entry.Option option : options) { assertThat(option.getScore(), greaterThan(0f)); assertThat(option.getText().string(), either(equalTo("type1")).or(equalTo("type2"))); @@ -652,8 +665,9 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { client().performRequest(new Request("POST", "/test/_refresh")); { - SearchRequest searchRequest = new SearchRequest("test").source(SearchSourceBuilder.searchSource() - .scriptField("result", new Script("null"))); + SearchRequest searchRequest = new SearchRequest("test").source( + SearchSourceBuilder.searchSource().scriptField("result", new Script("null")) + ); SearchResponse searchResponse = execute(searchRequest, highLevelClient()::search, highLevelClient()::searchAsync); SearchHit searchHit = searchResponse.getHits().getAt(0); List values = searchHit.getFields().get("result").getValues(); @@ -662,8 +676,9 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { assertNull(values.get(0)); } { - SearchRequest searchRequest = new SearchRequest("test").source(SearchSourceBuilder.searchSource() - .scriptField("result", new Script("new HashMap()"))); + SearchRequest searchRequest = new SearchRequest("test").source( + SearchSourceBuilder.searchSource().scriptField("result", new Script("new HashMap()")) + ); SearchResponse searchResponse = execute(searchRequest, highLevelClient()::search, highLevelClient()::searchAsync); SearchHit searchHit = searchResponse.getHits().getAt(0); List values = searchHit.getFields().get("result").getValues(); @@ -674,8 +689,9 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { assertEquals(0, map.size()); } { - SearchRequest searchRequest = new SearchRequest("test").source(SearchSourceBuilder.searchSource() - .scriptField("result", new Script("new String[]{}"))); + SearchRequest searchRequest = new SearchRequest("test").source( + SearchSourceBuilder.searchSource().scriptField("result", new Script("new String[]{}")) + ); SearchResponse searchResponse = execute(searchRequest, highLevelClient()::search, highLevelClient()::searchAsync); SearchHit searchHit = searchResponse.getHits().getAt(0); List values = searchHit.getFields().get("result").getValues(); @@ -709,8 +725,11 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { assertThat(((Number) hit.getSortValues()[0]).longValue(), equalTo(counter++)); } - searchResponse = execute(new SearchScrollRequest(searchResponse.getScrollId()).scroll(TimeValue.timeValueMinutes(2)), - highLevelClient()::scroll, highLevelClient()::scrollAsync); + searchResponse = execute( + new SearchScrollRequest(searchResponse.getScrollId()).scroll(TimeValue.timeValueMinutes(2)), + highLevelClient()::scroll, + highLevelClient()::scrollAsync + ); assertThat(searchResponse.getHits().getTotalHits().value, equalTo(100L)); assertThat(searchResponse.getHits().getHits().length, equalTo(35)); @@ -718,8 +737,11 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { assertEquals(counter++, ((Number) hit.getSortValues()[0]).longValue()); } - searchResponse = execute(new SearchScrollRequest(searchResponse.getScrollId()).scroll(TimeValue.timeValueMinutes(2)), - highLevelClient()::scroll, highLevelClient()::scrollAsync); + searchResponse = execute( + new SearchScrollRequest(searchResponse.getScrollId()).scroll(TimeValue.timeValueMinutes(2)), + highLevelClient()::scroll, + highLevelClient()::scrollAsync + ); assertThat(searchResponse.getHits().getTotalHits().value, equalTo(100L)); assertThat(searchResponse.getHits().getHits().length, equalTo(30)); @@ -729,14 +751,19 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { } finally { ClearScrollRequest clearScrollRequest = new ClearScrollRequest(); clearScrollRequest.addScrollId(searchResponse.getScrollId()); - ClearScrollResponse clearScrollResponse = execute(clearScrollRequest, - highLevelClient()::clearScroll, highLevelClient()::clearScrollAsync); + ClearScrollResponse clearScrollResponse = execute( + clearScrollRequest, + highLevelClient()::clearScroll, + highLevelClient()::clearScrollAsync + ); assertThat(clearScrollResponse.getNumFreed(), greaterThan(0)); assertTrue(clearScrollResponse.isSucceeded()); SearchScrollRequest scrollRequest = new SearchScrollRequest(searchResponse.getScrollId()).scroll(TimeValue.timeValueMinutes(2)); - OpenSearchStatusException exception = expectThrows(OpenSearchStatusException.class, () -> execute(scrollRequest, - highLevelClient()::scroll, highLevelClient()::scrollAsync)); + OpenSearchStatusException exception = expectThrows( + OpenSearchStatusException.class, + () -> execute(scrollRequest, highLevelClient()::scroll, highLevelClient()::scrollAsync) + ); assertEquals(RestStatus.NOT_FOUND, exception.status()); assertThat(exception.getRootCause(), instanceOf(OpenSearchException.class)); OpenSearchException rootCause = (OpenSearchException) exception.getRootCause(); @@ -756,8 +783,7 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { searchRequest3.source().sort("id", SortOrder.ASC); multiSearchRequest.add(searchRequest3); - MultiSearchResponse multiSearchResponse = - execute(multiSearchRequest, highLevelClient()::msearch, highLevelClient()::msearchAsync); + MultiSearchResponse multiSearchResponse = execute(multiSearchRequest, highLevelClient()::msearch, highLevelClient()::msearchAsync); assertThat(multiSearchResponse.getTook().millis(), Matchers.greaterThanOrEqualTo(0L)); assertThat(multiSearchResponse.getResponses().length, Matchers.equalTo(3)); @@ -786,23 +812,28 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { public void testMultiSearch_withAgg() throws Exception { MultiSearchRequest multiSearchRequest = new MultiSearchRequest(); SearchRequest searchRequest1 = new SearchRequest("index1"); - searchRequest1.source().size(0).aggregation(new TermsAggregationBuilder("name").userValueTypeHint(ValueType.STRING) - .field("field.keyword") - .order(BucketOrder.key(true))); + searchRequest1.source() + .size(0) + .aggregation( + new TermsAggregationBuilder("name").userValueTypeHint(ValueType.STRING).field("field.keyword").order(BucketOrder.key(true)) + ); multiSearchRequest.add(searchRequest1); SearchRequest searchRequest2 = new SearchRequest("index2"); - searchRequest2.source().size(0).aggregation(new TermsAggregationBuilder("name").userValueTypeHint(ValueType.STRING) - .field("field.keyword") - .order(BucketOrder.key(true))); + searchRequest2.source() + .size(0) + .aggregation( + new TermsAggregationBuilder("name").userValueTypeHint(ValueType.STRING).field("field.keyword").order(BucketOrder.key(true)) + ); multiSearchRequest.add(searchRequest2); SearchRequest searchRequest3 = new SearchRequest("index3"); - searchRequest3.source().size(0).aggregation(new TermsAggregationBuilder("name").userValueTypeHint(ValueType.STRING) - .field("field.keyword") - .order(BucketOrder.key(true))); + searchRequest3.source() + .size(0) + .aggregation( + new TermsAggregationBuilder("name").userValueTypeHint(ValueType.STRING).field("field.keyword").order(BucketOrder.key(true)) + ); multiSearchRequest.add(searchRequest3); - MultiSearchResponse multiSearchResponse = - execute(multiSearchRequest, highLevelClient()::msearch, highLevelClient()::msearchAsync); + MultiSearchResponse multiSearchResponse = execute(multiSearchRequest, highLevelClient()::msearch, highLevelClient()::msearchAsync); assertThat(multiSearchResponse.getTook().millis(), Matchers.greaterThanOrEqualTo(0L)); assertThat(multiSearchResponse.getResponses().length, Matchers.equalTo(3)); @@ -849,8 +880,7 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { searchRequest3.source().query(new TermsQueryBuilder("field", "value2")); multiSearchRequest.add(searchRequest3); - MultiSearchResponse multiSearchResponse = - execute(multiSearchRequest, highLevelClient()::msearch, highLevelClient()::msearchAsync); + MultiSearchResponse multiSearchResponse = execute(multiSearchRequest, highLevelClient()::msearch, highLevelClient()::msearchAsync); assertThat(multiSearchResponse.getTook().millis(), Matchers.greaterThanOrEqualTo(0L)); assertThat(multiSearchResponse.getResponses().length, Matchers.equalTo(3)); @@ -883,24 +913,33 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { assertThat(multiSearchResponse.getResponses()[0].isFailure(), Matchers.is(false)); SearchIT.assertSearchHeader(multiSearchResponse.getResponses()[0].getResponse()); assertThat(multiSearchResponse.getResponses()[0].getResponse().getHits().getTotalHits().value, Matchers.equalTo(1L)); - assertThat(multiSearchResponse.getResponses()[0].getResponse().getHits().getAt(0).getHighlightFields() - .get("field").fragments()[0].string(), Matchers.equalTo("value2")); + assertThat( + multiSearchResponse.getResponses()[0].getResponse().getHits().getAt(0).getHighlightFields().get("field").fragments()[0] + .string(), + Matchers.equalTo("value2") + ); assertThat(multiSearchResponse.getResponses()[1].getFailure(), Matchers.nullValue()); assertThat(multiSearchResponse.getResponses()[1].isFailure(), Matchers.is(false)); SearchIT.assertSearchHeader(multiSearchResponse.getResponses()[1].getResponse()); assertThat(multiSearchResponse.getResponses()[1].getResponse().getHits().getTotalHits().value, Matchers.equalTo(1L)); assertThat(multiSearchResponse.getResponses()[1].getResponse().getHits().getAt(0).getId(), Matchers.equalTo("4")); - assertThat(multiSearchResponse.getResponses()[1].getResponse().getHits().getAt(0).getHighlightFields() - .get("field").fragments()[0].string(), Matchers.equalTo("value2")); + assertThat( + multiSearchResponse.getResponses()[1].getResponse().getHits().getAt(0).getHighlightFields().get("field").fragments()[0] + .string(), + Matchers.equalTo("value2") + ); assertThat(multiSearchResponse.getResponses()[2].getFailure(), Matchers.nullValue()); assertThat(multiSearchResponse.getResponses()[2].isFailure(), Matchers.is(false)); SearchIT.assertSearchHeader(multiSearchResponse.getResponses()[2].getResponse()); assertThat(multiSearchResponse.getResponses()[2].getResponse().getHits().getTotalHits().value, Matchers.equalTo(1L)); assertThat(multiSearchResponse.getResponses()[2].getResponse().getHits().getAt(0).getId(), Matchers.equalTo("6")); - assertThat(multiSearchResponse.getResponses()[2].getResponse().getHits().getAt(0).getHighlightFields() - .get("field").fragments()[0].string(), Matchers.equalTo("value2")); + assertThat( + multiSearchResponse.getResponses()[2].getResponse().getHits().getAt(0).getHighlightFields().get("field").fragments()[0] + .string(), + Matchers.equalTo("value2") + ); } public void testMultiSearch_failure() throws Exception { @@ -912,8 +951,7 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { searchRequest2.source().query(new ScriptQueryBuilder(new Script(ScriptType.INLINE, "invalid", "code", Collections.emptyMap()))); multiSearchRequest.add(searchRequest2); - MultiSearchResponse multiSearchResponse = - execute(multiSearchRequest, highLevelClient()::msearch, highLevelClient()::msearchAsync); + MultiSearchResponse multiSearchResponse = execute(multiSearchRequest, highLevelClient()::msearch, highLevelClient()::msearchAsync); assertThat(multiSearchResponse.getTook().millis(), Matchers.greaterThanOrEqualTo(0L)); assertThat(multiSearchResponse.getResponses().length, Matchers.equalTo(2)); @@ -940,9 +978,11 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { searchTemplateRequest.setExplain(true); searchTemplateRequest.setProfile(true); - SearchTemplateResponse searchTemplateResponse = execute(searchTemplateRequest, + SearchTemplateResponse searchTemplateResponse = execute( + searchTemplateRequest, highLevelClient()::searchTemplate, - highLevelClient()::searchTemplateAsync); + highLevelClient()::searchTemplateAsync + ); assertNull(searchTemplateResponse.getSource()); @@ -967,10 +1007,10 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { searchTemplateRequest.setScript("non-existent"); searchTemplateRequest.setScriptParams(Collections.emptyMap()); - OpenSearchStatusException exception = expectThrows(OpenSearchStatusException.class, - () -> execute(searchTemplateRequest, - highLevelClient()::searchTemplate, - highLevelClient()::searchTemplateAsync)); + OpenSearchStatusException exception = expectThrows( + OpenSearchStatusException.class, + () -> execute(searchTemplateRequest, highLevelClient()::searchTemplate, highLevelClient()::searchTemplateAsync) + ); assertEquals(RestStatus.NOT_FOUND, exception.status()); } @@ -988,20 +1028,23 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { // Setting simulate true causes the template to only be rendered. searchTemplateRequest.setSimulate(true); - SearchTemplateResponse searchTemplateResponse = execute(searchTemplateRequest, + SearchTemplateResponse searchTemplateResponse = execute( + searchTemplateRequest, highLevelClient()::searchTemplate, - highLevelClient()::searchTemplateAsync); + highLevelClient()::searchTemplateAsync + ); assertNull(searchTemplateResponse.getResponse()); BytesReference expectedSource = BytesReference.bytes( XContentFactory.jsonBuilder() .startObject() - .startObject("query") - .startObject("match") - .field("num", 10) - .endObject() - .endObject() - .endObject()); + .startObject("query") + .startObject("match") + .field("num", 10) + .endObject() + .endObject() + .endObject() + ); BytesReference actualSource = searchTemplateResponse.getSource(); assertNotNull(actualSource); @@ -1009,7 +1052,6 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { assertToXContentEquivalent(expectedSource, actualSource, XContentType.JSON); } - public void testMultiSearchTemplate() throws Exception { MultiSearchTemplateRequest multiSearchTemplateRequest = new MultiSearchTemplateRequest(); @@ -1024,7 +1066,6 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { goodRequest.setProfile(true); multiSearchTemplateRequest.add(goodRequest); - SearchTemplateRequest badRequest = new SearchTemplateRequest(); badRequest.setRequest(new SearchRequest("index")); badRequest.setScriptType(ScriptType.INLINE); @@ -1035,17 +1076,18 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { multiSearchTemplateRequest.add(badRequest); - MultiSearchTemplateResponse multiSearchTemplateResponse = - execute(multiSearchTemplateRequest, highLevelClient()::msearchTemplate, - highLevelClient()::msearchTemplateAsync); + MultiSearchTemplateResponse multiSearchTemplateResponse = execute( + multiSearchTemplateRequest, + highLevelClient()::msearchTemplate, + highLevelClient()::msearchTemplateAsync + ); Item[] responses = multiSearchTemplateResponse.getResponses(); assertEquals(2, responses.length); - assertNull(responses[0].getResponse().getSource()); - SearchResponse goodResponse =responses[0].getResponse().getResponse(); + SearchResponse goodResponse = responses[0].getResponse().getResponse(); assertNotNull(goodResponse); assertThat(responses[0].isFailure(), Matchers.is(false)); assertEquals(1, goodResponse.getHits().getTotalHits().value); @@ -1055,7 +1097,6 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { assertNotNull(hit.getExplanation()); assertFalse(goodResponse.getProfileResults().isEmpty()); - assertNull(responses[0].getResponse().getSource()); assertThat(responses[1].isFailure(), Matchers.is(true)); assertNotNull(responses[1].getFailureMessage()); @@ -1074,7 +1115,6 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { badRequest1.setScriptParams(scriptParams); multiSearchTemplateRequest.add(badRequest1); - SearchTemplateRequest badRequest2 = new SearchTemplateRequest(); badRequest2.setRequest(new SearchRequest("index")); badRequest2.setScriptType(ScriptType.INLINE); @@ -1086,9 +1126,10 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { multiSearchTemplateRequest.add(badRequest2); // The whole HTTP request should fail if no nested search requests are valid - OpenSearchStatusException exception = expectThrows(OpenSearchStatusException.class, - () -> execute(multiSearchTemplateRequest, highLevelClient()::msearchTemplate, - highLevelClient()::msearchTemplateAsync)); + OpenSearchStatusException exception = expectThrows( + OpenSearchStatusException.class, + () -> execute(multiSearchTemplateRequest, highLevelClient()::msearchTemplate, highLevelClient()::msearchTemplateAsync) + ); assertEquals(RestStatus.BAD_REQUEST, exception.status()); assertThat(exception.getMessage(), containsString("no requests added")); @@ -1141,9 +1182,9 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { } { ExplainRequest explainRequest = new ExplainRequest("index1", "1"); - explainRequest.query(QueryBuilders.boolQuery() - .must(QueryBuilders.termQuery("field", "value1")) - .must(QueryBuilders.termQuery("field", "value2"))); + explainRequest.query( + QueryBuilders.boolQuery().must(QueryBuilders.termQuery("field", "value1")).must(QueryBuilders.termQuery("field", "value2")) + ); ExplainResponse explainResponse = execute(explainRequest, highLevelClient()::explain, highLevelClient()::explainAsync); @@ -1162,12 +1203,16 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { { ExplainRequest explainRequest = new ExplainRequest("non_existent_index", "1"); explainRequest.query(QueryBuilders.matchQuery("field", "value")); - OpenSearchException exception = expectThrows(OpenSearchException.class, - () -> execute(explainRequest, highLevelClient()::explain, highLevelClient()::explainAsync)); + OpenSearchException exception = expectThrows( + OpenSearchException.class, + () -> execute(explainRequest, highLevelClient()::explain, highLevelClient()::explainAsync) + ); assertThat(exception.status(), equalTo(RestStatus.NOT_FOUND)); assertThat(exception.getIndex().getName(), equalTo("non_existent_index")); - assertThat(exception.getDetailedMessage(), - containsString("OpenSearch exception [type=index_not_found_exception, reason=no such index [non_existent_index]]")); + assertThat( + exception.getDetailedMessage(), + containsString("OpenSearch exception [type=index_not_found_exception, reason=no such index [non_existent_index]]") + ); } { ExplainRequest explainRequest = new ExplainRequest("index1", "999"); @@ -1189,7 +1234,7 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { { ExplainRequest explainRequest = new ExplainRequest("index4", "1"); explainRequest.query(QueryBuilders.matchAllQuery()); - explainRequest.storedFields(new String[]{"field1"}); + explainRequest.storedFields(new String[] { "field1" }); ExplainResponse explainResponse = execute(explainRequest, highLevelClient()::explain, highLevelClient()::explainAsync); @@ -1205,7 +1250,7 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { { ExplainRequest explainRequest = new ExplainRequest("index4", "1"); explainRequest.query(QueryBuilders.matchAllQuery()); - explainRequest.storedFields(new String[]{"field1", "field2"}); + explainRequest.storedFields(new String[] { "field1", "field2" }); ExplainResponse explainResponse = execute(explainRequest, highLevelClient()::explain, highLevelClient()::explainAsync); @@ -1225,7 +1270,7 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { { ExplainRequest explainRequest = new ExplainRequest("index4", "1"); explainRequest.query(QueryBuilders.matchAllQuery()); - explainRequest.fetchSourceContext(new FetchSourceContext(true, new String[]{"field1"}, null)); + explainRequest.fetchSourceContext(new FetchSourceContext(true, new String[] { "field1" }, null)); ExplainResponse explainResponse = execute(explainRequest, highLevelClient()::explain, highLevelClient()::explainAsync); @@ -1239,7 +1284,7 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { { ExplainRequest explainRequest = new ExplainRequest("index4", "1"); explainRequest.query(QueryBuilders.matchAllQuery()); - explainRequest.fetchSourceContext(new FetchSourceContext(true, null, new String[] {"field2"})); + explainRequest.fetchSourceContext(new FetchSourceContext(true, null, new String[] { "field2" })); ExplainResponse explainResponse = execute(explainRequest, highLevelClient()::explain, highLevelClient()::explainAsync); @@ -1264,12 +1309,9 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { } public void testFieldCaps() throws IOException { - FieldCapabilitiesRequest request = new FieldCapabilitiesRequest() - .indices("index1", "index2") - .fields("rating", "field"); + FieldCapabilitiesRequest request = new FieldCapabilitiesRequest().indices("index1", "index2").fields("rating", "field"); - FieldCapabilitiesResponse response = execute(request, - highLevelClient()::fieldCaps, highLevelClient()::fieldCapsAsync); + FieldCapabilitiesResponse response = execute(request, highLevelClient()::fieldCaps, highLevelClient()::fieldCapsAsync); assertThat(response.getIndices(), arrayContaining("index1", "index2")); @@ -1279,11 +1321,27 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { assertEquals(2, ratingResponse.size()); FieldCapabilities expectedKeywordCapabilities = new FieldCapabilities( - "rating", "keyword", true, true, new String[]{"index2"}, null, null, Collections.emptyMap()); + "rating", + "keyword", + true, + true, + new String[] { "index2" }, + null, + null, + Collections.emptyMap() + ); assertEquals(expectedKeywordCapabilities, ratingResponse.get("keyword")); FieldCapabilities expectedLongCapabilities = new FieldCapabilities( - "rating", "long", true, true, new String[]{"index1"}, null, null, Collections.emptyMap()); + "rating", + "long", + true, + true, + new String[] { "index1" }, + null, + null, + Collections.emptyMap() + ); assertEquals(expectedLongCapabilities, ratingResponse.get("long")); // Check the capabilities for the 'field' field. @@ -1292,27 +1350,32 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { assertEquals(1, fieldResponse.size()); FieldCapabilities expectedTextCapabilities = new FieldCapabilities( - "field", "text", true, false, null, null, null, Collections.emptyMap()); + "field", + "text", + true, + false, + null, + null, + null, + Collections.emptyMap() + ); assertEquals(expectedTextCapabilities, fieldResponse.get("text")); } public void testFieldCapsWithNonExistentFields() throws IOException { - FieldCapabilitiesRequest request = new FieldCapabilitiesRequest() - .indices("index2") - .fields("nonexistent"); + FieldCapabilitiesRequest request = new FieldCapabilitiesRequest().indices("index2").fields("nonexistent"); - FieldCapabilitiesResponse response = execute(request, - highLevelClient()::fieldCaps, highLevelClient()::fieldCapsAsync); + FieldCapabilitiesResponse response = execute(request, highLevelClient()::fieldCaps, highLevelClient()::fieldCapsAsync); assertTrue(response.get().isEmpty()); } public void testFieldCapsWithNonExistentIndices() { - FieldCapabilitiesRequest request = new FieldCapabilitiesRequest() - .indices("non-existent") - .fields("rating"); + FieldCapabilitiesRequest request = new FieldCapabilitiesRequest().indices("non-existent").fields("rating"); - OpenSearchException exception = expectThrows(OpenSearchException.class, - () -> execute(request, highLevelClient()::fieldCaps, highLevelClient()::fieldCapsAsync)); + OpenSearchException exception = expectThrows( + OpenSearchException.class, + () -> execute(request, highLevelClient()::fieldCaps, highLevelClient()::fieldCapsAsync) + ); assertEquals(RestStatus.NOT_FOUND, exception.status()); } @@ -1358,10 +1421,10 @@ public class SearchIT extends OpenSearchRestHighLevelClientTestCase { CountRequest countRequest; if (randomBoolean()) { SearchSourceBuilder sourceBuilder = new SearchSourceBuilder().query(new MatchQueryBuilder("field", "value1")); - countRequest = new CountRequest(new String[]{"index1", "index2", "index3"}, sourceBuilder); + countRequest = new CountRequest(new String[] { "index1", "index2", "index3" }, sourceBuilder); } else { QueryBuilder query = new MatchQueryBuilder("field", "value1"); - countRequest = new CountRequest(new String[]{"index1", "index2", "index3"}, query); + countRequest = new CountRequest(new String[] { "index1", "index2", "index3" }, query); } CountResponse countResponse = execute(countRequest, highLevelClient()::count, highLevelClient()::countAsync); assertCountHeader(countResponse); diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/SnapshotIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/SnapshotIT.java index 30658fa350b..1d93dae5b2c 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/SnapshotIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/SnapshotIT.java @@ -78,15 +78,13 @@ public class SnapshotIT extends OpenSearchRestHighLevelClientTestCase { PutRepositoryRequest request = new PutRepositoryRequest(repository); request.settings(settings, XContentType.JSON); request.type(type); - return execute(request, highLevelClient().snapshot()::createRepository, - highLevelClient().snapshot()::createRepositoryAsync); + return execute(request, highLevelClient().snapshot()::createRepository, highLevelClient().snapshot()::createRepositoryAsync); } private CreateSnapshotResponse createTestSnapshot(CreateSnapshotRequest createSnapshotRequest) throws IOException { // assumes the repository already exists - return execute(createSnapshotRequest, highLevelClient().snapshot()::create, - highLevelClient().snapshot()::createAsync); + return execute(createSnapshotRequest, highLevelClient().snapshot()::create, highLevelClient().snapshot()::createAsync); } public void testCreateRepository() throws IOException { @@ -100,9 +98,12 @@ public class SnapshotIT extends OpenSearchRestHighLevelClientTestCase { assertTrue(createTestRepository("other", FsRepository.TYPE, "{\"location\": \".\"}").isAcknowledged()); GetRepositoriesRequest request = new GetRepositoriesRequest(); - request.repositories(new String[]{testRepository}); - GetRepositoriesResponse response = execute(request, highLevelClient().snapshot()::getRepository, - highLevelClient().snapshot()::getRepositoryAsync); + request.repositories(new String[] { testRepository }); + GetRepositoriesResponse response = execute( + request, + highLevelClient().snapshot()::getRepository, + highLevelClient().snapshot()::getRepositoryAsync + ); assertThat(1, equalTo(response.repositories().size())); } @@ -110,20 +111,27 @@ public class SnapshotIT extends OpenSearchRestHighLevelClientTestCase { assertTrue(createTestRepository("other", FsRepository.TYPE, "{\"location\": \".\"}").isAcknowledged()); assertTrue(createTestRepository("test", FsRepository.TYPE, "{\"location\": \".\"}").isAcknowledged()); - GetRepositoriesResponse response = execute(new GetRepositoriesRequest(), highLevelClient().snapshot()::getRepository, - highLevelClient().snapshot()::getRepositoryAsync); + GetRepositoriesResponse response = execute( + new GetRepositoriesRequest(), + highLevelClient().snapshot()::getRepository, + highLevelClient().snapshot()::getRepositoryAsync + ); assertThat(2, equalTo(response.repositories().size())); } public void testSnapshotGetRepositoriesNonExistent() { String repository = "doesnotexist"; - GetRepositoriesRequest request = new GetRepositoriesRequest(new String[]{repository}); - OpenSearchException exception = expectThrows(OpenSearchException.class, () -> execute(request, - highLevelClient().snapshot()::getRepository, highLevelClient().snapshot()::getRepositoryAsync)); + GetRepositoriesRequest request = new GetRepositoriesRequest(new String[] { repository }); + OpenSearchException exception = expectThrows( + OpenSearchException.class, + () -> execute(request, highLevelClient().snapshot()::getRepository, highLevelClient().snapshot()::getRepositoryAsync) + ); assertThat(exception.status(), equalTo(RestStatus.NOT_FOUND)); - assertThat(exception.getMessage(), equalTo( - "OpenSearch exception [type=repository_missing_exception, reason=[" + repository + "] missing]")); + assertThat( + exception.getMessage(), + equalTo("OpenSearch exception [type=repository_missing_exception, reason=[" + repository + "] missing]") + ); } public void testSnapshotDeleteRepository() throws IOException { @@ -131,13 +139,19 @@ public class SnapshotIT extends OpenSearchRestHighLevelClientTestCase { assertTrue(createTestRepository(repository, FsRepository.TYPE, "{\"location\": \".\"}").isAcknowledged()); GetRepositoriesRequest request = new GetRepositoriesRequest(); - GetRepositoriesResponse response = execute(request, highLevelClient().snapshot()::getRepository, - highLevelClient().snapshot()::getRepositoryAsync); + GetRepositoriesResponse response = execute( + request, + highLevelClient().snapshot()::getRepository, + highLevelClient().snapshot()::getRepositoryAsync + ); assertThat(1, equalTo(response.repositories().size())); DeleteRepositoryRequest deleteRequest = new DeleteRepositoryRequest(repository); - AcknowledgedResponse deleteResponse = execute(deleteRequest, highLevelClient().snapshot()::deleteRepository, - highLevelClient().snapshot()::deleteRepositoryAsync); + AcknowledgedResponse deleteResponse = execute( + deleteRequest, + highLevelClient().snapshot()::deleteRepository, + highLevelClient().snapshot()::deleteRepositoryAsync + ); assertTrue(deleteResponse.isAcknowledged()); } @@ -147,8 +161,11 @@ public class SnapshotIT extends OpenSearchRestHighLevelClientTestCase { assertTrue(putRepositoryResponse.isAcknowledged()); VerifyRepositoryRequest request = new VerifyRepositoryRequest("test"); - VerifyRepositoryResponse response = execute(request, highLevelClient().snapshot()::verifyRepository, - highLevelClient().snapshot()::verifyRepositoryAsync); + VerifyRepositoryResponse response = execute( + request, + highLevelClient().snapshot()::verifyRepository, + highLevelClient().snapshot()::verifyRepositoryAsync + ); assertThat(response.getNodes().size(), equalTo(1)); } @@ -157,8 +174,11 @@ public class SnapshotIT extends OpenSearchRestHighLevelClientTestCase { assertTrue(putRepositoryResponse.isAcknowledged()); CleanupRepositoryRequest request = new CleanupRepositoryRequest("test"); - CleanupRepositoryResponse response = execute(request, highLevelClient().snapshot()::cleanupRepository, - highLevelClient().snapshot()::cleanupRepositoryAsync); + CleanupRepositoryResponse response = execute( + request, + highLevelClient().snapshot()::cleanupRepository, + highLevelClient().snapshot()::cleanupRepositoryAsync + ); assertThat(response.result().bytes(), equalTo(0L)); assertThat(response.result().blobs(), equalTo(0L)); } @@ -182,8 +202,9 @@ public class SnapshotIT extends OpenSearchRestHighLevelClientTestCase { if (waitForCompletion == false) { // If we don't wait for the snapshot to complete we have to cancel it to not leak the snapshot task AcknowledgedResponse deleteResponse = execute( - new DeleteSnapshotRequest(repository, snapshot), - highLevelClient().snapshot()::delete, highLevelClient().snapshot()::deleteAsync + new DeleteSnapshotRequest(repository, snapshot), + highLevelClient().snapshot()::delete, + highLevelClient().snapshot()::deleteAsync ); assertTrue(deleteResponse.isAcknowledged()); } @@ -213,17 +234,20 @@ public class SnapshotIT extends OpenSearchRestHighLevelClientTestCase { if (randomBoolean()) { request = new GetSnapshotsRequest(repository); } else if (randomBoolean()) { - request = new GetSnapshotsRequest(repository, new String[] {"_all"}); + request = new GetSnapshotsRequest(repository, new String[] { "_all" }); } else { - request = new GetSnapshotsRequest(repository, new String[] {snapshot1, snapshot2}); + request = new GetSnapshotsRequest(repository, new String[] { snapshot1, snapshot2 }); } GetSnapshotsResponse response = execute(request, highLevelClient().snapshot()::get, highLevelClient().snapshot()::getAsync); assertEquals(2, response.getSnapshots().size()); - assertThat(response.getSnapshots().stream().map((s) -> s.snapshotId().getName()).collect(Collectors.toList()), - contains("test_snapshot1", "test_snapshot2")); - Optional> returnedMetadata = response.getSnapshots().stream() + assertThat( + response.getSnapshots().stream().map((s) -> s.snapshotId().getName()).collect(Collectors.toList()), + contains("test_snapshot1", "test_snapshot2") + ); + Optional> returnedMetadata = response.getSnapshots() + .stream() .filter(s -> s.snapshotId().getName().equals("test_snapshot2")) .findFirst() .map(SnapshotInfo::userMetadata); @@ -253,9 +277,12 @@ public class SnapshotIT extends OpenSearchRestHighLevelClientTestCase { SnapshotsStatusRequest request = new SnapshotsStatusRequest(); request.repository(testRepository); - request.snapshots(new String[]{testSnapshot}); - SnapshotsStatusResponse response = execute(request, highLevelClient().snapshot()::status, - highLevelClient().snapshot()::statusAsync); + request.snapshots(new String[] { testSnapshot }); + SnapshotsStatusResponse response = execute( + request, + highLevelClient().snapshot()::status, + highLevelClient().snapshot()::statusAsync + ); assertThat(response.getSnapshots().size(), equalTo(1)); assertThat(response.getSnapshots().get(0).getSnapshot().getRepository(), equalTo(testRepository)); assertThat(response.getSnapshots().get(0).getSnapshot().getSnapshotId().getName(), equalTo(testSnapshot)); @@ -291,8 +318,11 @@ public class SnapshotIT extends OpenSearchRestHighLevelClientTestCase { request.renamePattern(testIndex); request.renameReplacement(restoredIndex); - RestoreSnapshotResponse response = execute(request, highLevelClient().snapshot()::restore, - highLevelClient().snapshot()::restoreAsync); + RestoreSnapshotResponse response = execute( + request, + highLevelClient().snapshot()::restore, + highLevelClient().snapshot()::restoreAsync + ); RestoreInfo restoreInfo = response.getRestoreInfo(); assertThat(restoreInfo.name(), equalTo(testSnapshot)); @@ -309,11 +339,14 @@ public class SnapshotIT extends OpenSearchRestHighLevelClientTestCase { AcknowledgedResponse putRepositoryResponse = createTestRepository(testRepository, FsRepository.TYPE, "{\"location\": \".\"}"); assertTrue(putRepositoryResponse.isAcknowledged()); - createIndex(testIndex, Settings.builder() - .put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, randomIntBetween(1,3)) - .put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0) - .put(IndexMetadata.SETTING_INDEX_HIDDEN, true) - .build()); + createIndex( + testIndex, + Settings.builder() + .put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, randomIntBetween(1, 3)) + .put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0) + .put(IndexMetadata.SETTING_INDEX_HIDDEN, true) + .build() + ); assertTrue("index [" + testIndex + "] should have been created", indexExists(testIndex)); CreateSnapshotRequest createSnapshotRequest = new CreateSnapshotRequest(testRepository, testSnapshot); @@ -333,8 +366,11 @@ public class SnapshotIT extends OpenSearchRestHighLevelClientTestCase { request.indices(randomFrom(testIndex, "test_*")); request.renamePattern(testIndex); - RestoreSnapshotResponse response = execute(request, highLevelClient().snapshot()::restore, - highLevelClient().snapshot()::restoreAsync); + RestoreSnapshotResponse response = execute( + request, + highLevelClient().snapshot()::restore, + highLevelClient().snapshot()::restoreAsync + ); RestoreInfo restoreInfo = response.getRestoreInfo(); assertThat(restoreInfo.name(), equalTo(testSnapshot)); @@ -369,7 +405,7 @@ public class SnapshotIT extends OpenSearchRestHighLevelClientTestCase { String repository = "test_repository"; String snapshot = "source_snapshot"; String targetSnapshot = "target_snapshot"; - final String testIndex = "test_idx"; + final String testIndex = "test_idx"; createIndex(testIndex, Settings.EMPTY); assertTrue("index [" + testIndex + "] should have been created", indexExists(testIndex)); @@ -383,7 +419,7 @@ public class SnapshotIT extends OpenSearchRestHighLevelClientTestCase { CreateSnapshotResponse createSnapshotResponse = createTestSnapshot(createSnapshotRequest); assertEquals(RestStatus.OK, createSnapshotResponse.status()); - CloneSnapshotRequest request = new CloneSnapshotRequest(repository, snapshot, targetSnapshot, new String[]{testIndex}); + CloneSnapshotRequest request = new CloneSnapshotRequest(repository, snapshot, targetSnapshot, new String[] { testIndex }); AcknowledgedResponse response = execute(request, highLevelClient().snapshot()::clone, highLevelClient().snapshot()::cloneAsync); assertTrue(response.isAcknowledged()); @@ -398,16 +434,20 @@ public class SnapshotIT extends OpenSearchRestHighLevelClientTestCase { long fields = randomLongBetween(0, 4); for (int i = 0; i < fields; i++) { if (randomBoolean()) { - metadata.put(randomValueOtherThanMany(metadata::containsKey, () -> randomAlphaOfLengthBetween(2,10)), - randomAlphaOfLengthBetween(5, 5)); + metadata.put( + randomValueOtherThanMany(metadata::containsKey, () -> randomAlphaOfLengthBetween(2, 10)), + randomAlphaOfLengthBetween(5, 5) + ); } else { Map nested = new HashMap<>(); long nestedFields = randomLongBetween(0, 4); for (int j = 0; j < nestedFields; j++) { - nested.put(randomValueOtherThanMany(nested::containsKey, () -> randomAlphaOfLengthBetween(2,10)), - randomAlphaOfLengthBetween(5, 5)); + nested.put( + randomValueOtherThanMany(nested::containsKey, () -> randomAlphaOfLengthBetween(2, 10)), + randomAlphaOfLengthBetween(5, 5) + ); } - metadata.put(randomValueOtherThanMany(metadata::containsKey, () -> randomAlphaOfLengthBetween(2,10)), nested); + metadata.put(randomValueOtherThanMany(metadata::containsKey, () -> randomAlphaOfLengthBetween(2, 10)), nested); } } return metadata; diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/SnapshotRequestConvertersTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/SnapshotRequestConvertersTests.java index 03a9671fdb7..f18679127bf 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/SnapshotRequestConvertersTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/SnapshotRequestConvertersTests.java @@ -74,7 +74,7 @@ public class SnapshotRequestConvertersTests extends OpenSearchTestCase { RequestConvertersTests.setRandomLocal(getRepositoriesRequest::local, expectedParams); if (randomBoolean()) { - String[] entries = new String[]{"a", "b", "c"}; + String[] entries = new String[] { "a", "b", "c" }; getRepositoriesRequest.repositories(entries); endpoint.append("/" + String.join(",", entries)); } @@ -99,7 +99,8 @@ public class SnapshotRequestConvertersTests extends OpenSearchTestCase { .put(FsRepository.LOCATION_SETTING.getKey(), repositoryLocation) .put(FsRepository.COMPRESS_SETTING.getKey(), randomBoolean()) .put(FsRepository.CHUNK_SIZE_SETTING.getKey(), randomIntBetween(100, 1000), ByteSizeUnit.BYTES) - .build()); + .build() + ); Request request = SnapshotRequestConverters.createRepository(putRepositoryRequest); assertThat(request.getEndpoint(), equalTo(endpoint)); diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/StoredScriptsIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/StoredScriptsIT.java index 12d613ae477..b3898fe0b95 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/StoredScriptsIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/StoredScriptsIT.java @@ -55,32 +55,31 @@ public class StoredScriptsIT extends OpenSearchRestHighLevelClientTestCase { private static final String id = "calculate-score"; public void testGetStoredScript() throws Exception { - final StoredScriptSource scriptSource = - new StoredScriptSource("painless", - "Math.log(_score * 2) + params.my_modifier", - Collections.singletonMap(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType())); + final StoredScriptSource scriptSource = new StoredScriptSource( + "painless", + "Math.log(_score * 2) + params.my_modifier", + Collections.singletonMap(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType()) + ); - PutStoredScriptRequest request = - new PutStoredScriptRequest(id, "score", new BytesArray("{}"), XContentType.JSON, scriptSource); + PutStoredScriptRequest request = new PutStoredScriptRequest(id, "score", new BytesArray("{}"), XContentType.JSON, scriptSource); assertAcked(execute(request, highLevelClient()::putScript, highLevelClient()::putScriptAsync)); GetStoredScriptRequest getRequest = new GetStoredScriptRequest("calculate-score"); getRequest.masterNodeTimeout("50s"); - GetStoredScriptResponse getResponse = execute(getRequest, highLevelClient()::getScript, - highLevelClient()::getScriptAsync); + GetStoredScriptResponse getResponse = execute(getRequest, highLevelClient()::getScript, highLevelClient()::getScriptAsync); assertThat(getResponse.getSource(), equalTo(scriptSource)); } public void testDeleteStoredScript() throws Exception { - final StoredScriptSource scriptSource = - new StoredScriptSource("painless", - "Math.log(_score * 2) + params.my_modifier", - Collections.singletonMap(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType())); + final StoredScriptSource scriptSource = new StoredScriptSource( + "painless", + "Math.log(_score * 2) + params.my_modifier", + Collections.singletonMap(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType()) + ); - PutStoredScriptRequest request = - new PutStoredScriptRequest(id, "score", new BytesArray("{}"), XContentType.JSON, scriptSource); + PutStoredScriptRequest request = new PutStoredScriptRequest(id, "score", new BytesArray("{}"), XContentType.JSON, scriptSource); assertAcked(execute(request, highLevelClient()::putScript, highLevelClient()::putScriptAsync)); DeleteStoredScriptRequest deleteRequest = new DeleteStoredScriptRequest(id); @@ -90,20 +89,21 @@ public class StoredScriptsIT extends OpenSearchRestHighLevelClientTestCase { GetStoredScriptRequest getRequest = new GetStoredScriptRequest(id); - final OpenSearchStatusException statusException = expectThrows(OpenSearchStatusException.class, - () -> execute(getRequest, highLevelClient()::getScript, - highLevelClient()::getScriptAsync)); + final OpenSearchStatusException statusException = expectThrows( + OpenSearchStatusException.class, + () -> execute(getRequest, highLevelClient()::getScript, highLevelClient()::getScriptAsync) + ); assertThat(statusException.status(), equalTo(RestStatus.NOT_FOUND)); } public void testPutScript() throws Exception { - final StoredScriptSource scriptSource = - new StoredScriptSource("painless", - "Math.log(_score * 2) + params.my_modifier", - Collections.singletonMap(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType())); + final StoredScriptSource scriptSource = new StoredScriptSource( + "painless", + "Math.log(_score * 2) + params.my_modifier", + Collections.singletonMap(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType()) + ); - PutStoredScriptRequest request = - new PutStoredScriptRequest(id, "score", new BytesArray("{}"), XContentType.JSON, scriptSource); + PutStoredScriptRequest request = new PutStoredScriptRequest(id, "score", new BytesArray("{}"), XContentType.JSON, scriptSource); assertAcked(execute(request, highLevelClient()::putScript, highLevelClient()::putScriptAsync)); Map script = getAsMap("/_scripts/" + id); diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/SyncedFlushResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/SyncedFlushResponseTests.java index 89b02f4fa08..e56e78d5d9c 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/SyncedFlushResponseTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/SyncedFlushResponseTests.java @@ -70,19 +70,18 @@ public class SyncedFlushResponseTests extends OpenSearchTestCase { assertNotNull(plan.result); plan.clientResult.toXContent(clientResponsebuilder, ToXContent.EMPTY_PARAMS); Map serverContentMap = convertFailureListToSet( - serverResponsebuilder - .generator() + serverResponsebuilder.generator() .contentType() .xContent() .createParser( xContentRegistry(), DeprecationHandler.THROW_UNSUPPORTED_OPERATION, BytesReference.bytes(serverResponsebuilder).streamInput() - ).map() + ) + .map() ); Map clientContentMap = convertFailureListToSet( - clientResponsebuilder - .generator() + clientResponsebuilder.generator() .contentType() .xContent() .createParser( @@ -102,20 +101,15 @@ public class SyncedFlushResponseTests extends OpenSearchTestCase { builder.startObject(); plan.result.toXContent(builder, ToXContent.EMPTY_PARAMS); builder.endObject(); - XContentParser parser = builder - .generator() + XContentParser parser = builder.generator() .contentType() .xContent() - .createParser( - xContentRegistry(), - DeprecationHandler.THROW_UNSUPPORTED_OPERATION, - BytesReference.bytes(builder).streamInput() - ); + .createParser(xContentRegistry(), DeprecationHandler.THROW_UNSUPPORTED_OPERATION, BytesReference.bytes(builder).streamInput()); SyncedFlushResponse originalResponse = plan.clientResult; SyncedFlushResponse parsedResponse = SyncedFlushResponse.fromXContent(parser); assertNotNull(parsedResponse); assertShardCounts(originalResponse.getShardCounts(), parsedResponse.getShardCounts()); - for (Map.Entry entry: originalResponse.getIndexResults().entrySet()) { + for (Map.Entry entry : originalResponse.getIndexResults().entrySet()) { String index = entry.getKey(); SyncedFlushResponse.IndexResult responseResult = entry.getValue(); SyncedFlushResponse.IndexResult parsedResult = parsedResponse.getIndexResults().get(index); @@ -123,7 +117,7 @@ public class SyncedFlushResponseTests extends OpenSearchTestCase { assertNotNull(parsedResult); assertShardCounts(responseResult.getShardCounts(), parsedResult.getShardCounts()); assertEquals(responseResult.failures().size(), parsedResult.failures().size()); - for (SyncedFlushResponse.ShardFailure responseShardFailure: responseResult.failures()) { + for (SyncedFlushResponse.ShardFailure responseShardFailure : responseResult.failures()) { assertTrue(containsFailure(parsedResult.failures(), responseShardFailure)); } } @@ -162,21 +156,18 @@ public class SyncedFlushResponseTests extends OpenSearchTestCase { failed += replicas + 1; failures++; shardsResults.add(new ShardsSyncedFlushResult(shardId, replicas + 1, "simulated total failure")); - shardFailures.add( - new SyncedFlushResponse.ShardFailure( - shardId.id(), - "simulated total failure", - new HashMap<>() - ) - ); + shardFailures.add(new SyncedFlushResponse.ShardFailure(shardId.id(), "simulated total failure", new HashMap<>())); } else { Map shardResponses = new HashMap<>(); for (int copy = 0; copy < replicas + 1; copy++) { - final ShardRouting shardRouting = - TestShardRouting.newShardRouting( - index, shard, "node_" + shardId + "_" + copy, null, - copy == 0, ShardRoutingState.STARTED - ); + final ShardRouting shardRouting = TestShardRouting.newShardRouting( + index, + shard, + "node_" + shardId + "_" + copy, + null, + copy == 0, + ShardRoutingState.STARTED + ); if (randomInt(5) < 2) { // shard copy failure failed++; @@ -184,24 +175,17 @@ public class SyncedFlushResponseTests extends OpenSearchTestCase { shardResponses.put(shardRouting, new SyncedFlushService.ShardSyncedFlushResponse("copy failure " + shardId)); // Building the shardRouting map here. XContentBuilder builder = XContentBuilder.builder(xContentType.xContent()); - Map routing = - shardRouting.toXContent(builder, ToXContent.EMPTY_PARAMS) - .generator() - .contentType() - .xContent() - .createParser( - xContentRegistry(), - DeprecationHandler.THROW_UNSUPPORTED_OPERATION, - BytesReference.bytes(builder).streamInput() - ) - .map(); - shardFailures.add( - new SyncedFlushResponse.ShardFailure( - shardId.id(), - "copy failure " + shardId, - routing + Map routing = shardRouting.toXContent(builder, ToXContent.EMPTY_PARAMS) + .generator() + .contentType() + .xContent() + .createParser( + xContentRegistry(), + DeprecationHandler.THROW_UNSUPPORTED_OPERATION, + BytesReference.bytes(builder).streamInput() ) - ); + .map(); + shardFailures.add(new SyncedFlushResponse.ShardFailure(shardId.id(), "copy failure " + shardId, routing)); } else { successful++; shardResponses.put(shardRouting, new SyncedFlushService.ShardSyncedFlushResponse((String) null)); @@ -211,15 +195,7 @@ public class SyncedFlushResponseTests extends OpenSearchTestCase { } } indicesResults.put(index, shardsResults); - indexResults.put( - index, - new SyncedFlushResponse.IndexResult( - shards * (replicas + 1), - successful, - failed, - shardFailures - ) - ); + indexResults.put(index, new SyncedFlushResponse.IndexResult(shards * (replicas + 1), successful, failed, shardFailures)); testPlan.countsPerIndex.put(index, new SyncedFlushResponse.ShardCounts(shards * (replicas + 1), successful, failed)); testPlan.expectedFailuresPerIndex.put(index, failures); totalFailed += failed; @@ -236,17 +212,16 @@ public class SyncedFlushResponseTests extends OpenSearchTestCase { } public boolean containsFailure(List failures, SyncedFlushResponse.ShardFailure origFailure) { - for (SyncedFlushResponse.ShardFailure failure: failures) { - if (failure.getShardId() == origFailure.getShardId() && - failure.getFailureReason().equals(origFailure.getFailureReason()) && - failure.getRouting().equals(origFailure.getRouting())) { + for (SyncedFlushResponse.ShardFailure failure : failures) { + if (failure.getShardId() == origFailure.getShardId() + && failure.getFailureReason().equals(origFailure.getFailureReason()) + && failure.getRouting().equals(origFailure.getRouting())) { return true; } } return false; } - public void assertShardCounts(SyncedFlushResponse.ShardCounts first, SyncedFlushResponse.ShardCounts second) { if (first == null) { assertNull(second); @@ -257,18 +232,18 @@ public class SyncedFlushResponseTests extends OpenSearchTestCase { public Map convertFailureListToSet(Map input) { Map retMap = new HashMap<>(); - for (Map.Entry entry: input.entrySet()) { + for (Map.Entry entry : input.entrySet()) { if (entry.getKey().equals(SyncedFlushResponse.SHARDS_FIELD)) { retMap.put(entry.getKey(), entry.getValue()); } else { // This was an index entry. @SuppressWarnings("unchecked") - Map indexResult = (Map)entry.getValue(); + Map indexResult = (Map) entry.getValue(); Map retResult = new HashMap<>(); - for (Map.Entry entry2: indexResult.entrySet()) { + for (Map.Entry entry2 : indexResult.entrySet()) { if (entry2.getKey().equals(SyncedFlushResponse.IndexResult.FAILURES_FIELD)) { @SuppressWarnings("unchecked") - List failures = (List)entry2.getValue(); + List failures = (List) entry2.getValue(); Set retSet = new HashSet<>(failures); retResult.put(entry.getKey(), retSet); } else { diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/TasksIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/TasksIT.java index 0831ee15a75..0db8ee4406c 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/TasksIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/TasksIT.java @@ -93,10 +93,11 @@ public class TasksIT extends OpenSearchRestHighLevelClientTestCase { Settings settings = Settings.builder().put("number_of_shards", 1).put("number_of_replicas", 0).build(); createIndex(sourceIndex, settings); createIndex(destinationIndex, settings); - BulkRequest bulkRequest = new BulkRequest() - .add(new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", "bar"), XContentType.JSON)) - .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo2", "bar2"), XContentType.JSON)) - .setRefreshPolicy(RefreshPolicy.IMMEDIATE); + BulkRequest bulkRequest = new BulkRequest().add( + new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", "bar"), XContentType.JSON) + ) + .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo2", "bar2"), XContentType.JSON)) + .setRefreshPolicy(RefreshPolicy.IMMEDIATE); assertEquals(RestStatus.OK, highLevelClient().bulk(bulkRequest, RequestOptions.DEFAULT).status()); final ReindexRequest reindexRequest = new ReindexRequest().setSourceIndices(sourceIndex).setDestIndex(destinationIndex); @@ -132,22 +133,18 @@ public class TasksIT extends OpenSearchRestHighLevelClientTestCase { public void testCancelTasks() throws IOException { ListTasksRequest listRequest = new ListTasksRequest(); - ListTasksResponse listResponse = execute( - listRequest, - highLevelClient().tasks()::list, - highLevelClient().tasks()::listAsync - ); + ListTasksResponse listResponse = execute(listRequest, highLevelClient().tasks()::list, highLevelClient().tasks()::listAsync); // in this case, probably no task will actually be cancelled. // this is ok, that case is covered in TasksIT.testTasksCancellation org.opensearch.tasks.TaskInfo firstTask = listResponse.getTasks().get(0); String node = listResponse.getPerNodeTasks().keySet().iterator().next(); - CancelTasksRequest cancelTasksRequest = new CancelTasksRequest.Builder().withTaskId( - new TaskId(node, firstTask.getId()) - ).build(); - CancelTasksResponse response = execute(cancelTasksRequest, + CancelTasksRequest cancelTasksRequest = new CancelTasksRequest.Builder().withTaskId(new TaskId(node, firstTask.getId())).build(); + CancelTasksResponse response = execute( + cancelTasksRequest, highLevelClient().tasks()::cancel, - highLevelClient().tasks()::cancelAsync); + highLevelClient().tasks()::cancelAsync + ); // Since the task may or may not have been cancelled, assert that we received a response only // The actual testing of task cancellation is covered by TasksIT.testTasksCancellation assertThat(response, notNullValue()); diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/TasksRequestConvertersTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/TasksRequestConvertersTests.java index 0b7403c5903..64fec3c8fb8 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/TasksRequestConvertersTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/TasksRequestConvertersTests.java @@ -50,10 +50,11 @@ public class TasksRequestConvertersTests extends OpenSearchTestCase { public void testCancelTasks() { Map expectedParams = new HashMap<>(); - org.opensearch.client.tasks.TaskId taskId = - new org.opensearch.client.tasks.TaskId(randomAlphaOfLength(5), randomNonNegativeLong()); - org.opensearch.client.tasks.TaskId parentTaskId = - new org.opensearch.client.tasks.TaskId(randomAlphaOfLength(5), randomNonNegativeLong()); + org.opensearch.client.tasks.TaskId taskId = new org.opensearch.client.tasks.TaskId(randomAlphaOfLength(5), randomNonNegativeLong()); + org.opensearch.client.tasks.TaskId parentTaskId = new org.opensearch.client.tasks.TaskId( + randomAlphaOfLength(5), + randomNonNegativeLong() + ); CancelTasksRequest.Builder builder = new CancelTasksRequest.Builder().withTaskId(taskId).withParentTaskId(parentTaskId); expectedParams.put("task_id", taskId.toString()); expectedParams.put("parent_task_id", parentTaskId.toString()); @@ -123,8 +124,10 @@ public class TasksRequestConvertersTests extends OpenSearchTestCase { { ListTasksRequest request = new ListTasksRequest(); request.setTaskId(new TaskId(randomAlphaOfLength(5), randomNonNegativeLong())); - IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () - -> TasksRequestConverters.listTasks(request)); + IllegalArgumentException exception = expectThrows( + IllegalArgumentException.class, + () -> TasksRequestConverters.listTasks(request) + ); assertEquals("TaskId cannot be used for list tasks request", exception.getMessage()); } } diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/TimedRequestTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/TimedRequestTests.java index 648140049d7..3026472bb8e 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/TimedRequestTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/TimedRequestTests.java @@ -38,15 +38,17 @@ import org.opensearch.test.OpenSearchTestCase; public class TimedRequestTests extends OpenSearchTestCase { public void testDefaults() { - TimedRequest timedRequest = new TimedRequest(){}; + TimedRequest timedRequest = new TimedRequest() { + }; assertEquals(timedRequest.timeout(), TimedRequest.DEFAULT_ACK_TIMEOUT); assertEquals(timedRequest.masterNodeTimeout(), TimedRequest.DEFAULT_MASTER_NODE_TIMEOUT); } public void testNonDefaults() { - TimedRequest timedRequest = new TimedRequest(){}; + TimedRequest timedRequest = new TimedRequest() { + }; TimeValue timeout = TimeValue.timeValueSeconds(randomIntBetween(0, 1000)); - TimeValue masterTimeout = TimeValue.timeValueSeconds(randomIntBetween(0,1000)); + TimeValue masterTimeout = TimeValue.timeValueSeconds(randomIntBetween(0, 1000)); timedRequest.setTimeout(timeout); timedRequest.setMasterTimeout(masterTimeout); assertEquals(timedRequest.timeout(), timeout); diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/UpdateByQueryIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/UpdateByQueryIT.java index 08c965a9d28..d73fa2bd0aa 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/UpdateByQueryIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/UpdateByQueryIT.java @@ -70,19 +70,15 @@ public class UpdateByQueryIT extends OpenSearchRestHighLevelClientTestCase { final String sourceIndex = "source1"; { // Prepare - Settings settings = Settings.builder() - .put("number_of_shards", 1) - .put("number_of_replicas", 0) - .build(); + Settings settings = Settings.builder().put("number_of_shards", 1).put("number_of_replicas", 0).build(); createIndex(sourceIndex, settings); assertEquals( RestStatus.OK, highLevelClient().bulk( - new BulkRequest() - .add(new IndexRequest(sourceIndex).id("1") - .source(Collections.singletonMap("foo", 1), XContentType.JSON)) - .add(new IndexRequest(sourceIndex).id("2") - .source(Collections.singletonMap("foo", 2), XContentType.JSON)) + new BulkRequest().add( + new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", 1), XContentType.JSON) + ) + .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo", 2), XContentType.JSON)) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE), RequestOptions.DEFAULT ).status() @@ -94,8 +90,11 @@ public class UpdateByQueryIT extends OpenSearchRestHighLevelClientTestCase { updateByQueryRequest.indices(sourceIndex); updateByQueryRequest.setQuery(new IdsQueryBuilder().addIds("1")); updateByQueryRequest.setRefresh(true); - BulkByScrollResponse bulkResponse = - execute(updateByQueryRequest, highLevelClient()::updateByQuery, highLevelClient()::updateByQueryAsync); + BulkByScrollResponse bulkResponse = execute( + updateByQueryRequest, + highLevelClient()::updateByQuery, + highLevelClient()::updateByQueryAsync + ); assertEquals(1, bulkResponse.getTotal()); assertEquals(1, bulkResponse.getUpdated()); assertEquals(0, bulkResponse.getNoops()); @@ -112,8 +111,11 @@ public class UpdateByQueryIT extends OpenSearchRestHighLevelClientTestCase { updateByQueryRequest.indices(sourceIndex); updateByQueryRequest.setScript(new Script("if (ctx._source.foo == 2) ctx._source.foo++;")); updateByQueryRequest.setRefresh(true); - BulkByScrollResponse bulkResponse = - execute(updateByQueryRequest, highLevelClient()::updateByQuery, highLevelClient()::updateByQueryAsync); + BulkByScrollResponse bulkResponse = execute( + updateByQueryRequest, + highLevelClient()::updateByQuery, + highLevelClient()::updateByQueryAsync + ); assertEquals(2, bulkResponse.getTotal()); assertEquals(2, bulkResponse.getUpdated()); assertEquals(0, bulkResponse.getDeleted()); @@ -126,8 +128,7 @@ public class UpdateByQueryIT extends OpenSearchRestHighLevelClientTestCase { assertEquals(0, bulkResponse.getSearchFailures().size()); assertEquals( 3, - (int) (highLevelClient().get(new GetRequest(sourceIndex, "2"), RequestOptions.DEFAULT) - .getSourceAsMap().get("foo")) + (int) (highLevelClient().get(new GetRequest(sourceIndex, "2"), RequestOptions.DEFAULT).getSourceAsMap().get("foo")) ); } { @@ -156,23 +157,33 @@ public class UpdateByQueryIT extends OpenSearchRestHighLevelClientTestCase { TaskId taskIdToRethrottle = findTaskToRethrottle(UpdateByQueryAction.NAME, updateByQueryRequest.getDescription()); float requestsPerSecond = 1000f; - ListTasksResponse response = execute(new RethrottleRequest(taskIdToRethrottle, requestsPerSecond), - highLevelClient()::updateByQueryRethrottle, highLevelClient()::updateByQueryRethrottleAsync); + ListTasksResponse response = execute( + new RethrottleRequest(taskIdToRethrottle, requestsPerSecond), + highLevelClient()::updateByQueryRethrottle, + highLevelClient()::updateByQueryRethrottleAsync + ); assertThat(response.getTasks(), hasSize(1)); assertEquals(taskIdToRethrottle, response.getTasks().get(0).getTaskId()); assertThat(response.getTasks().get(0).getStatus(), instanceOf(RawTaskStatus.class)); - assertEquals(Float.toString(requestsPerSecond), - ((RawTaskStatus) response.getTasks().get(0).getStatus()).toMap().get("requests_per_second").toString()); + assertEquals( + Float.toString(requestsPerSecond), + ((RawTaskStatus) response.getTasks().get(0).getStatus()).toMap().get("requests_per_second").toString() + ); assertTrue(taskFinished.await(10, TimeUnit.SECONDS)); // any rethrottling after the update-by-query is done performed with the same taskId should result in a failure - response = execute(new RethrottleRequest(taskIdToRethrottle, requestsPerSecond), - highLevelClient()::updateByQueryRethrottle, highLevelClient()::updateByQueryRethrottleAsync); + response = execute( + new RethrottleRequest(taskIdToRethrottle, requestsPerSecond), + highLevelClient()::updateByQueryRethrottle, + highLevelClient()::updateByQueryRethrottleAsync + ); assertTrue(response.getTasks().isEmpty()); assertFalse(response.getNodeFailures().isEmpty()); assertEquals(1, response.getNodeFailures().size()); - assertEquals("OpenSearch exception [type=resource_not_found_exception, reason=task [" + taskIdToRethrottle + "] is missing]", - response.getNodeFailures().get(0).getCause().getMessage()); + assertEquals( + "OpenSearch exception [type=resource_not_found_exception, reason=task [" + taskIdToRethrottle + "] is missing]", + response.getNodeFailures().get(0).getCause().getMessage() + ); } } @@ -180,21 +191,16 @@ public class UpdateByQueryIT extends OpenSearchRestHighLevelClientTestCase { final String sourceIndex = "testupdatebyquerytask"; { // Prepare - Settings settings = Settings.builder() - .put("number_of_shards", 1) - .put("number_of_replicas", 0) - .build(); + Settings settings = Settings.builder().put("number_of_shards", 1).put("number_of_replicas", 0).build(); createIndex(sourceIndex, settings); assertEquals( RestStatus.OK, highLevelClient().bulk( - new BulkRequest() - .add(new IndexRequest(sourceIndex).id("1") - .source(Collections.singletonMap("foo", 1), XContentType.JSON)) - .add(new IndexRequest(sourceIndex).id("2") - .source(Collections.singletonMap("foo", 2), XContentType.JSON)) - .add(new IndexRequest(sourceIndex).id("3") - .source(Collections.singletonMap("foo", 3), XContentType.JSON)) + new BulkRequest().add( + new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", 1), XContentType.JSON) + ) + .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo", 2), XContentType.JSON)) + .add(new IndexRequest(sourceIndex).id("3").source(Collections.singletonMap("foo", 3), XContentType.JSON)) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE), RequestOptions.DEFAULT ).status() @@ -221,13 +227,11 @@ public class UpdateByQueryIT extends OpenSearchRestHighLevelClientTestCase { public void testUpdateByQueryConflict() throws IOException { final String index = "testupdatebyqueryconflict"; - final Settings settings = Settings.builder() - .put("number_of_shards", 1) - .put("number_of_replicas", 0) - .build(); + final Settings settings = Settings.builder().put("number_of_shards", 1).put("number_of_replicas", 0).build(); createIndex(index, settings); - final BulkRequest bulkRequest = new BulkRequest() - .add(new IndexRequest(index).id("1").source(Collections.singletonMap("foo", "bar"), XContentType.JSON)) + final BulkRequest bulkRequest = new BulkRequest().add( + new IndexRequest(index).id("1").source(Collections.singletonMap("foo", "bar"), XContentType.JSON) + ) .add(new IndexRequest(index).id("2").source(Collections.singletonMap("foo", "bar"), XContentType.JSON)) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); assertThat(highLevelClient().bulk(bulkRequest, RequestOptions.DEFAULT).status(), equalTo(RestStatus.OK)); diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/cluster/RemoteInfoResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/cluster/RemoteInfoResponseTests.java index 8bc785ac5a0..a6ebec81976 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/cluster/RemoteInfoResponseTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/cluster/RemoteInfoResponseTests.java @@ -49,8 +49,9 @@ import static java.util.function.Function.identity; import static java.util.stream.Collectors.toMap; import static org.hamcrest.Matchers.equalTo; -public class RemoteInfoResponseTests extends AbstractResponseTestCase { +public class RemoteInfoResponseTests extends AbstractResponseTestCase< + org.opensearch.action.admin.cluster.remote.RemoteInfoResponse, + RemoteInfoResponse> { @Override protected org.opensearch.action.admin.cluster.remote.RemoteInfoResponse createServerTestInstance(XContentType xContentType) { @@ -68,33 +69,36 @@ public class RemoteInfoResponseTests extends AbstractResponseTestCase serverInfos = serverTestInstance.getInfos().stream() - .collect(toMap(RemoteConnectionInfo::getClusterAlias, identity())); + Map serverInfos = serverTestInstance.getInfos() + .stream() + .collect(toMap(RemoteConnectionInfo::getClusterAlias, identity())); for (org.opensearch.client.cluster.RemoteConnectionInfo clientRemoteInfo : clientInstance.getInfos()) { RemoteConnectionInfo serverRemoteInfo = serverInfos.get(clientRemoteInfo.getClusterAlias()); assertThat(clientRemoteInfo.getClusterAlias(), equalTo(serverRemoteInfo.getClusterAlias())); - assertThat(clientRemoteInfo.getInitialConnectionTimeoutString(), - equalTo(serverRemoteInfo.getInitialConnectionTimeout().toString())); + assertThat( + clientRemoteInfo.getInitialConnectionTimeoutString(), + equalTo(serverRemoteInfo.getInitialConnectionTimeout().toString()) + ); assertThat(clientRemoteInfo.isConnected(), equalTo(serverRemoteInfo.isConnected())); assertThat(clientRemoteInfo.isSkipUnavailable(), equalTo(serverRemoteInfo.isSkipUnavailable())); assertThat(clientRemoteInfo.getModeInfo().isConnected(), equalTo(serverRemoteInfo.getModeInfo().isConnected())); assertThat(clientRemoteInfo.getModeInfo().modeName(), equalTo(serverRemoteInfo.getModeInfo().modeName())); if (clientRemoteInfo.getModeInfo().modeName().equals(SniffModeInfo.NAME)) { - SniffModeInfo clientModeInfo = - (SniffModeInfo) clientRemoteInfo.getModeInfo(); - SniffConnectionStrategy.SniffModeInfo serverModeInfo = - (SniffConnectionStrategy.SniffModeInfo) serverRemoteInfo.getModeInfo(); + SniffModeInfo clientModeInfo = (SniffModeInfo) clientRemoteInfo.getModeInfo(); + SniffConnectionStrategy.SniffModeInfo serverModeInfo = (SniffConnectionStrategy.SniffModeInfo) serverRemoteInfo + .getModeInfo(); assertThat(clientModeInfo.getMaxConnectionsPerCluster(), equalTo(serverModeInfo.getMaxConnectionsPerCluster())); assertThat(clientModeInfo.getNumNodesConnected(), equalTo(serverModeInfo.getNumNodesConnected())); assertThat(clientModeInfo.getSeedNodes(), equalTo(serverModeInfo.getSeedNodes())); } else if (clientRemoteInfo.getModeInfo().modeName().equals(ProxyModeInfo.NAME)) { - ProxyModeInfo clientModeInfo = - (ProxyModeInfo) clientRemoteInfo.getModeInfo(); - ProxyConnectionStrategy.ProxyModeInfo serverModeInfo = - (ProxyConnectionStrategy.ProxyModeInfo) serverRemoteInfo.getModeInfo(); + ProxyModeInfo clientModeInfo = (ProxyModeInfo) clientRemoteInfo.getModeInfo(); + ProxyConnectionStrategy.ProxyModeInfo serverModeInfo = (ProxyConnectionStrategy.ProxyModeInfo) serverRemoteInfo + .getModeInfo(); assertThat(clientModeInfo.getAddress(), equalTo(serverModeInfo.getAddress())); assertThat(clientModeInfo.getServerName(), equalTo(serverModeInfo.getServerName())); assertThat(clientModeInfo.getMaxSocketConnections(), equalTo(serverModeInfo.getMaxSocketConnections())); diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/core/AcknowledgedResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/core/AcknowledgedResponseTests.java index 9f9f9f74d06..a517e37dc87 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/core/AcknowledgedResponseTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/core/AcknowledgedResponseTests.java @@ -39,7 +39,8 @@ import java.io.IOException; import static org.hamcrest.Matchers.is; -public class AcknowledgedResponseTests extends AbstractResponseTestCase { @Override @@ -53,8 +54,10 @@ public class AcknowledgedResponseTests extends AbstractResponseTestCase { +public class BroadcastResponseTests extends AbstractResponseTestCase< + org.opensearch.action.support.broadcast.BroadcastResponse, + BroadcastResponse> { private String index; private String id; @@ -69,7 +70,8 @@ public class BroadcastResponseTests extends AbstractResponseTestCase randomIntBetween(0, total - 1)), - new RetentionLeaseNotFoundException(id)); + new RetentionLeaseNotFoundException(id) + ); failures.add(failure); shardIds.add(failure.shardId()); } @@ -83,8 +85,10 @@ public class BroadcastResponseTests extends AbstractResponseTestCase mutators = new ArrayList<>(); - mutators.add(() -> mutation.indices(ArrayUtils.concat(countRequest.indices(), new String[]{randomAlphaOfLength(10)}))); - mutators.add(() -> mutation.indicesOptions(randomValueOtherThan(countRequest.indicesOptions(), - () -> IndicesOptions.fromOptions(randomBoolean(), randomBoolean(), randomBoolean(), randomBoolean())))); - mutators.add(() -> mutation.types(ArrayUtils.concat(countRequest.types(), new String[]{randomAlphaOfLength(10)}))); + mutators.add(() -> mutation.indices(ArrayUtils.concat(countRequest.indices(), new String[] { randomAlphaOfLength(10) }))); + mutators.add( + () -> mutation.indicesOptions( + randomValueOtherThan( + countRequest.indicesOptions(), + () -> IndicesOptions.fromOptions(randomBoolean(), randomBoolean(), randomBoolean(), randomBoolean()) + ) + ) + ); + mutators.add(() -> mutation.types(ArrayUtils.concat(countRequest.types(), new String[] { randomAlphaOfLength(10) }))); mutators.add(() -> mutation.preference(randomValueOtherThan(countRequest.preference(), () -> randomAlphaOfLengthBetween(3, 10)))); mutators.add(() -> mutation.routing(randomValueOtherThan(countRequest.routing(), () -> randomAlphaOfLengthBetween(3, 10)))); mutators.add(() -> mutation.terminateAfter(randomValueOtherThan(countRequest.terminateAfter(), () -> randomIntBetween(0, 10)))); mutators.add(() -> mutation.minScore(randomValueOtherThan(countRequest.minScore(), () -> (float) randomIntBetween(0, 10)))); - mutators.add(() -> mutation.query(randomValueOtherThan(countRequest.query(), - () -> new MatchQueryBuilder(randomAlphaOfLength(4), randomAlphaOfLength(4))))); + mutators.add( + () -> mutation.query( + randomValueOtherThan(countRequest.query(), () -> new MatchQueryBuilder(randomAlphaOfLength(4), randomAlphaOfLength(4))) + ) + ); randomFrom(mutators).run(); return mutation; } diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/core/CountResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/core/CountResponseTests.java index 82b4bf859e0..3b9b91bd93c 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/core/CountResponseTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/core/CountResponseTests.java @@ -53,15 +53,9 @@ public class CountResponseTests extends OpenSearchTestCase { // OpenSearchException. Best effort: try to check that the original message appears somewhere in the rendered xContent // For more see ShardSearchFailureTests. public void testFromXContent() throws IOException { - xContentTester( - this::createParser, - this::createTestInstance, - this::toXContent, - CountResponse::fromXContent) - .supportsUnknownFields(false) - .assertEqualsConsumer(this::assertEqualInstances) - .assertToXContentEquivalence(false) - .test(); + xContentTester(this::createParser, this::createTestInstance, this::toXContent, CountResponse::fromXContent).supportsUnknownFields( + false + ).assertEqualsConsumer(this::assertEqualInstances).assertToXContentEquivalence(false).test(); } private CountResponse createTestInstance() { @@ -75,8 +69,12 @@ public class CountResponseTests extends OpenSearchTestCase { for (int i = 0; i < failures.length; i++) { failures[i] = createShardFailureTestItem(); } - CountResponse.ShardStats shardStats = new CountResponse.ShardStats(successfulShards, totalShards, skippedShards, - randomBoolean() ? ShardSearchFailure.EMPTY_ARRAY : failures); + CountResponse.ShardStats shardStats = new CountResponse.ShardStats( + successfulShards, + totalShards, + skippedShards, + randomBoolean() ? ShardSearchFailure.EMPTY_ARRAY : failures + ); return new CountResponse(count, terminatedEarly, shardStats); } @@ -91,8 +89,15 @@ public class CountResponseTests extends OpenSearchTestCase { } private void toXContent(CountResponse.ShardStats stats, XContentBuilder builder, ToXContent.Params params) throws IOException { - RestActions.buildBroadcastShardsHeader(builder, params, stats.getTotalShards(), stats.getSuccessfulShards(), stats - .getSkippedShards(), stats.getShardFailures().length, stats.getShardFailures()); + RestActions.buildBroadcastShardsHeader( + builder, + params, + stats.getTotalShards(), + stats.getSuccessfulShards(), + stats.getSkippedShards(), + stats.getShardFailures().length, + stats.getShardFailures() + ); } @SuppressWarnings("Duplicates") @@ -103,8 +108,12 @@ public class CountResponseTests extends OpenSearchTestCase { if (randomBoolean()) { String nodeId = randomAlphaOfLengthBetween(5, 10); String indexName = randomAlphaOfLengthBetween(5, 10); - searchShardTarget = new SearchShardTarget(nodeId, - new ShardId(new Index(indexName, IndexMetadata.INDEX_UUID_NA_VALUE), randomInt()), null, null); + searchShardTarget = new SearchShardTarget( + nodeId, + new ShardId(new Index(indexName, IndexMetadata.INDEX_UUID_NA_VALUE), randomInt()), + null, + null + ); } return new ShardSearchFailure(ex, searchShardTarget); } @@ -129,11 +138,15 @@ public class CountResponseTests extends OpenSearchTestCase { assertEquals(originalFailure.shard(), parsedFailure.shard()); assertEquals(originalFailure.shardId(), parsedFailure.shardId()); String originalMsg = originalFailure.getCause().getMessage(); - assertEquals(parsedFailure.getCause().getMessage(), "OpenSearch exception [type=parsing_exception, reason=" + - originalMsg + "]"); + assertEquals( + parsedFailure.getCause().getMessage(), + "OpenSearch exception [type=parsing_exception, reason=" + originalMsg + "]" + ); String nestedMsg = originalFailure.getCause().getCause().getMessage(); - assertEquals(parsedFailure.getCause().getCause().getMessage(), - "OpenSearch exception [type=illegal_argument_exception, reason=" + nestedMsg + "]"); + assertEquals( + parsedFailure.getCause().getCause().getMessage(), + "OpenSearch exception [type=illegal_argument_exception, reason=" + nestedMsg + "]" + ); } } } diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/core/GetSourceResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/core/GetSourceResponseTests.java index 34171536314..6f26fed2d04 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/core/GetSourceResponseTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/core/GetSourceResponseTests.java @@ -47,8 +47,7 @@ import java.util.Collections; import static org.hamcrest.CoreMatchers.equalTo; -public final class GetSourceResponseTests extends - AbstractResponseTestCase { +public final class GetSourceResponseTests extends AbstractResponseTestCase { static class SourceOnlyResponse implements ToXContentObject { diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/core/MainResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/core/MainResponseTests.java index 03faae759ee..57f41255398 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/core/MainResponseTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/core/MainResponseTests.java @@ -55,10 +55,14 @@ public class MainResponseTests extends AbstractResponseTestCase - field.endsWith("term_vectors") || field.endsWith("terms") || field.endsWith("tokens")) + .randomFieldsExcludeFilter(field -> field.endsWith("term_vectors") || field.endsWith("terms") || field.endsWith("tokens")) .test(); } diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/core/ShardsAcknowledgedResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/core/ShardsAcknowledgedResponseTests.java index aa064427bb3..5e2c2757085 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/core/ShardsAcknowledgedResponseTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/core/ShardsAcknowledgedResponseTests.java @@ -41,12 +41,12 @@ import static org.opensearch.test.AbstractXContentTestCase.xContentTester; public class ShardsAcknowledgedResponseTests extends OpenSearchTestCase { public void testFromXContent() throws IOException { - xContentTester(this::createParser, + xContentTester( + this::createParser, this::createTestInstance, ShardsAcknowledgedResponseTests::toXContent, - ShardsAcknowledgedResponse::fromXContent) - .supportsUnknownFields(false) - .test(); + ShardsAcknowledgedResponse::fromXContent + ).supportsUnknownFields(false).test(); } private ShardsAcknowledgedResponse createTestInstance() { diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/core/TermVectorsResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/core/TermVectorsResponseTests.java index 0c38183a939..11a6aeb6dbe 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/core/TermVectorsResponseTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/core/TermVectorsResponseTests.java @@ -50,10 +50,9 @@ public class TermVectorsResponseTests extends OpenSearchTestCase { this::createParser, TermVectorsResponseTests::createTestInstance, TermVectorsResponseTests::toXContent, - TermVectorsResponse::fromXContent) - .supportsUnknownFields(true) - .randomFieldsExcludeFilter(field -> - field.endsWith("term_vectors") || field.endsWith("terms") || field.endsWith("tokens")) + TermVectorsResponse::fromXContent + ).supportsUnknownFields(true) + .randomFieldsExcludeFilter(field -> field.endsWith("term_vectors") || field.endsWith("terms") || field.endsWith("tokens")) .test(); } @@ -114,7 +113,7 @@ public class TermVectorsResponseTests extends OpenSearchTestCase { for (TermVectorsResponse.TermVector.Token token : tokens) { builder.startObject(); if (token.getPosition() != null) builder.field("position", token.getPosition()); - if (token.getStartOffset()!= null) builder.field("start_offset", token.getStartOffset()); + if (token.getStartOffset() != null) builder.field("start_offset", token.getStartOffset()); if (token.getEndOffset() != null) builder.field("end_offset", token.getEndOffset()); if (token.getPayload() != null) builder.field("payload", token.getPayload()); builder.endObject(); @@ -129,16 +128,15 @@ public class TermVectorsResponseTests extends OpenSearchTestCase { builder.endObject(); } - static TermVectorsResponse createTestInstance() { String index = randomAlphaOfLength(5); String type = randomAlphaOfLength(5); - String id = String.valueOf(randomIntBetween(1,100)); + String id = String.valueOf(randomIntBetween(1, 100)); long version = randomNonNegativeLong(); long tookInMillis = randomNonNegativeLong(); boolean found = randomBoolean(); List tvList = null; - if (found){ + if (found) { boolean hasFieldStatistics = randomBoolean(); boolean hasTermStatistics = randomBoolean(); boolean hasScores = randomBoolean(); @@ -151,18 +149,24 @@ public class TermVectorsResponseTests extends OpenSearchTestCase { for (int i = 0; i < fieldsCount; i++) { String fieldName = randomValueOtherThanMany(usedFieldNames::contains, () -> randomAlphaOfLength(7)); usedFieldNames.add(fieldName); - tvList.add(randomTermVector( - fieldName, hasFieldStatistics, hasTermStatistics, hasScores, hasOffsets, hasPositions, hasPayloads)); + tvList.add( + randomTermVector(fieldName, hasFieldStatistics, hasTermStatistics, hasScores, hasOffsets, hasPositions, hasPayloads) + ); } } TermVectorsResponse tvresponse = new TermVectorsResponse(index, type, id, version, found, tookInMillis, tvList); return tvresponse; } - - - private static TermVectorsResponse.TermVector randomTermVector(String fieldName, boolean hasFieldStatistics, boolean hasTermStatistics, - boolean hasScores, boolean hasOffsets, boolean hasPositions, boolean hasPayloads) { + private static TermVectorsResponse.TermVector randomTermVector( + String fieldName, + boolean hasFieldStatistics, + boolean hasTermStatistics, + boolean hasScores, + boolean hasOffsets, + boolean hasPositions, + boolean hasPayloads + ) { TermVectorsResponse.TermVector.FieldStatistics fs = null; if (hasFieldStatistics) { long sumDocFreq = randomNonNegativeLong(); @@ -184,10 +188,16 @@ public class TermVectorsResponseTests extends OpenSearchTestCase { return tv; } - private static TermVectorsResponse.TermVector.Term randomTerm(String termTxt, boolean hasTermStatistics, boolean hasScores, - boolean hasOffsets, boolean hasPositions, boolean hasPayloads) { + private static TermVectorsResponse.TermVector.Term randomTerm( + String termTxt, + boolean hasTermStatistics, + boolean hasScores, + boolean hasOffsets, + boolean hasPositions, + boolean hasPayloads + ) { - int termFreq = randomInt(10000); + int termFreq = randomInt(10000); Integer docFreq = null; Long totalTermFreq = null; Float score = null; @@ -197,7 +207,7 @@ public class TermVectorsResponseTests extends OpenSearchTestCase { totalTermFreq = randomNonNegativeLong(); } if (hasScores) score = randomFloat(); - if (hasOffsets || hasPositions || hasPayloads ){ + if (hasOffsets || hasPositions || hasPayloads) { int tokensCount = randomIntBetween(1, 5); tokens = new ArrayList<>(tokensCount); for (int i = 0; i < tokensCount; i++) { @@ -211,13 +221,23 @@ public class TermVectorsResponseTests extends OpenSearchTestCase { } if (hasPositions) position = randomInt(100); if (hasPayloads) payload = "payload" + randomAlphaOfLength(2); - TermVectorsResponse.TermVector.Token token = - new TermVectorsResponse.TermVector.Token(startOffset, endOffset, position, payload); + TermVectorsResponse.TermVector.Token token = new TermVectorsResponse.TermVector.Token( + startOffset, + endOffset, + position, + payload + ); tokens.add(token); } } - TermVectorsResponse.TermVector.Term term = - new TermVectorsResponse.TermVector.Term(termTxt, termFreq, docFreq, totalTermFreq, score, tokens); + TermVectorsResponse.TermVector.Term term = new TermVectorsResponse.TermVector.Term( + termTxt, + termFreq, + docFreq, + totalTermFreq, + score, + tokens + ); return term; } } diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/core/tasks/GetTaskResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/core/tasks/GetTaskResponseTests.java index 58f01554e54..a14e1169d09 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/core/tasks/GetTaskResponseTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/core/tasks/GetTaskResponseTests.java @@ -52,15 +52,12 @@ import static org.opensearch.test.AbstractXContentTestCase.xContentTester; public class GetTaskResponseTests extends OpenSearchTestCase { public void testFromXContent() throws IOException { - xContentTester( - this::createParser, - this::createTestInstance, - this::toXContent, - GetTaskResponse::fromXContent) - .supportsUnknownFields(true) + xContentTester(this::createParser, this::createTestInstance, this::toXContent, GetTaskResponse::fromXContent).supportsUnknownFields( + true + ) .assertEqualsConsumer(this::assertEqualInstances) .assertToXContentEquivalence(true) - .randomFieldsExcludeFilter(field ->field.endsWith("headers") || field.endsWith("status")) + .randomFieldsExcludeFilter(field -> field.endsWith("headers") || field.endsWith("status")) .test(); } @@ -94,9 +91,9 @@ public class GetTaskResponseTests extends OpenSearchTestCase { long runningTimeNanos = randomLong(); boolean cancellable = randomBoolean(); TaskId parentTaskId = randomBoolean() ? TaskId.EMPTY_TASK_ID : randomTaskId(); - Map headers = randomBoolean() ? - Collections.emptyMap() : - Collections.singletonMap(randomAlphaOfLength(5), randomAlphaOfLength(5)); + Map headers = randomBoolean() + ? Collections.emptyMap() + : Collections.singletonMap(randomAlphaOfLength(5), randomAlphaOfLength(5)); return new TaskInfo(taskId, type, action, description, status, startTime, runningTimeNanos, cancellable, parentTaskId, headers); } diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/CRUDDocumentationIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/CRUDDocumentationIT.java index c2a0e2231ae..67df99d9d7c 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/CRUDDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/CRUDDocumentationIT.java @@ -260,9 +260,7 @@ public class CRUDDocumentationIT extends OpenSearchRestHighLevelClientTestCase { // end::index-optype } { - IndexRequest request = new IndexRequest("posts") - .id("async") - .source("field", "value"); + IndexRequest request = new IndexRequest("posts").id("async").source("field", "value"); ActionListener listener; // tag::index-execute-listener listener = new ActionListener() { @@ -299,13 +297,17 @@ public class CRUDDocumentationIT extends OpenSearchRestHighLevelClientTestCase { assertSame(RestStatus.CREATED, indexResponse.status()); Request request = new Request("POST", "/_scripts/increment-field"); - request.setJsonEntity(Strings.toString(JsonXContent.contentBuilder() - .startObject() + request.setJsonEntity( + Strings.toString( + JsonXContent.contentBuilder() + .startObject() .startObject("script") - .field("lang", "painless") - .field("source", "ctx._source.field += params.count") + .field("lang", "painless") + .field("source", "ctx._source.field += params.count") .endObject() - .endObject())); + .endObject() + ) + ); Response response = client().performRequest(request); assertEquals(RestStatus.OK.getStatus(), response.getStatusLine().getStatusCode()); } @@ -639,8 +641,7 @@ public class CRUDDocumentationIT extends OpenSearchRestHighLevelClientTestCase { } { - IndexResponse indexResponse = client.index(new IndexRequest("posts").id("1").source("field", "value") - , RequestOptions.DEFAULT); + IndexResponse indexResponse = client.index(new IndexRequest("posts").id("1").source("field", "value"), RequestOptions.DEFAULT); assertSame(RestStatus.CREATED, indexResponse.status()); // tag::delete-conflict @@ -656,8 +657,10 @@ public class CRUDDocumentationIT extends OpenSearchRestHighLevelClientTestCase { // end::delete-conflict } { - IndexResponse indexResponse = client.index(new IndexRequest("posts").id("async").source("field", "value"), - RequestOptions.DEFAULT); + IndexResponse indexResponse = client.index( + new IndexRequest("posts").id("async").source("field", "value"), + RequestOptions.DEFAULT + ); assertSame(RestStatus.CREATED, indexResponse.status()); DeleteRequest request = new DeleteRequest("posts", "async"); @@ -807,18 +810,17 @@ public class CRUDDocumentationIT extends OpenSearchRestHighLevelClientTestCase { public void testReindex() throws Exception { RestHighLevelClient client = highLevelClient(); { - String mapping = - " \"properties\": {\n" + - " \"user\": {\n" + - " \"type\": \"text\"\n" + - " },\n" + - " \"field1\": {\n" + - " \"type\": \"integer\"\n" + - " },\n" + - " \"field2\": {\n" + - " \"type\": \"integer\"\n" + - " }\n" + - " }"; + String mapping = " \"properties\": {\n" + + " \"user\": {\n" + + " \"type\": \"text\"\n" + + " },\n" + + " \"field1\": {\n" + + " \"type\": \"integer\"\n" + + " },\n" + + " \"field2\": {\n" + + " \"type\": \"integer\"\n" + + " }\n" + + " }"; createIndex("source1", Settings.EMPTY, mapping); createIndex("source2", Settings.EMPTY, mapping); createPipeline("my_pipeline"); @@ -881,7 +883,6 @@ public class CRUDDocumentationIT extends OpenSearchRestHighLevelClientTestCase { request.setScroll(TimeValue.timeValueMinutes(10)); // <1> // end::reindex-request-scroll - // tag::reindex-execute BulkByScrollResponse bulkResponse = client.reindex(request, RequestOptions.DEFAULT); @@ -1009,18 +1010,17 @@ public class CRUDDocumentationIT extends OpenSearchRestHighLevelClientTestCase { public void testUpdateByQuery() throws Exception { RestHighLevelClient client = highLevelClient(); { - String mapping = - " \"properties\": {\n" + - " \"user\": {\n" + - " \"type\": \"text\"\n" + - " },\n" + - " \"field1\": {\n" + - " \"type\": \"integer\"\n" + - " },\n" + - " \"field2\": {\n" + - " \"type\": \"integer\"\n" + - " }\n" + - " }"; + String mapping = " \"properties\": {\n" + + " \"user\": {\n" + + " \"type\": \"text\"\n" + + " },\n" + + " \"field1\": {\n" + + " \"type\": \"integer\"\n" + + " },\n" + + " \"field2\": {\n" + + " \"type\": \"integer\"\n" + + " }\n" + + " }"; createIndex("source1", Settings.EMPTY, mapping); createIndex("source2", Settings.EMPTY, mapping); createPipeline("my_pipeline"); @@ -1132,18 +1132,17 @@ public class CRUDDocumentationIT extends OpenSearchRestHighLevelClientTestCase { public void testDeleteByQuery() throws Exception { RestHighLevelClient client = highLevelClient(); { - String mapping = - " \"properties\": {\n" + - " \"user\": {\n" + - " \"type\": \"text\"\n" + - " },\n" + - " \"field1\": {\n" + - " \"type\": \"integer\"\n" + - " },\n" + - " \"field2\": {\n" + - " \"type\": \"integer\"\n" + - " }\n" + - " }"; + String mapping = " \"properties\": {\n" + + " \"user\": {\n" + + " \"type\": \"text\"\n" + + " },\n" + + " \"field1\": {\n" + + " \"type\": \"integer\"\n" + + " },\n" + + " \"field2\": {\n" + + " \"type\": \"integer\"\n" + + " }\n" + + " }"; createIndex("source1", Settings.EMPTY, mapping); createIndex("source2", Settings.EMPTY, mapping); } @@ -1245,23 +1244,22 @@ public class CRUDDocumentationIT extends OpenSearchRestHighLevelClientTestCase { { Request createIndex = new Request("PUT", "/posts"); createIndex.setJsonEntity( - "{\n" + - " \"mappings\" : {\n" + - " \"properties\" : {\n" + - " \"message\" : {\n" + - " \"type\": \"text\",\n" + - " \"store\": true\n" + - " }\n" + - " }\n" + - " }\n" + - "}"); + "{\n" + + " \"mappings\" : {\n" + + " \"properties\" : {\n" + + " \"message\" : {\n" + + " \"type\": \"text\",\n" + + " \"store\": true\n" + + " }\n" + + " }\n" + + " }\n" + + "}" + ); Response response = client().performRequest(createIndex); assertEquals(200, response.getStatusLine().getStatusCode()); IndexRequest indexRequest = new IndexRequest("posts").id("1") - .source("user", "foobar", - "postDate", new Date(), - "message", "trying out OpenSearch"); + .source("user", "foobar", "postDate", new Date(), "message", "trying out OpenSearch"); IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT); assertEquals(DocWriteResponse.Result.CREATED, indexResponse.getResult()); } @@ -1418,23 +1416,22 @@ public class CRUDDocumentationIT extends OpenSearchRestHighLevelClientTestCase { { Request createIndex = new Request("PUT", "/posts"); createIndex.setJsonEntity( - "{\n" + - " \"mappings\" : {\n" + - " \"properties\" : {\n" + - " \"message\" : {\n" + - " \"type\": \"text\",\n" + - " \"store\": true\n" + - " }\n" + - " }\n" + - " }\n" + - "}"); + "{\n" + + " \"mappings\" : {\n" + + " \"properties\" : {\n" + + " \"message\" : {\n" + + " \"type\": \"text\",\n" + + " \"store\": true\n" + + " }\n" + + " }\n" + + " }\n" + + "}" + ); Response response = client().performRequest(createIndex); assertEquals(200, response.getStatusLine().getStatusCode()); IndexRequest indexRequest = new IndexRequest("posts").id("1") - .source("user", "foobar", - "postDate", new Date(), - "message", "trying out OpenSearch"); + .source("user", "foobar", "postDate", new Date(), "message", "trying out OpenSearch"); IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT); assertEquals(DocWriteResponse.Result.CREATED, indexResponse.getResult()); } @@ -1654,14 +1651,16 @@ public class CRUDDocumentationIT extends OpenSearchRestHighLevelClientTestCase { // Not entirely sure if _termvectors belongs to CRUD, and in the absence of a better place, will have it here public void testTermVectors() throws Exception { RestHighLevelClient client = highLevelClient(); - CreateIndexRequest authorsRequest = new CreateIndexRequest("authors") - .mapping(XContentFactory.jsonBuilder().startObject() + CreateIndexRequest authorsRequest = new CreateIndexRequest("authors").mapping( + XContentFactory.jsonBuilder() + .startObject() .startObject("properties") - .startObject("user") - .field("type", "keyword") - .endObject() + .startObject("user") + .field("type", "keyword") .endObject() - .endObject()); + .endObject() + .endObject() + ); CreateIndexResponse authorsResponse = client.indices().create(authorsRequest, RequestOptions.DEFAULT); assertTrue(authorsResponse.isAcknowledged()); client.index(new IndexRequest("index").id("1").source("user", "foobar"), RequestOptions.DEFAULT); @@ -1718,7 +1717,6 @@ public class CRUDDocumentationIT extends OpenSearchRestHighLevelClientTestCase { client.termvectors(request, RequestOptions.DEFAULT); // end::term-vectors-execute - // tag::term-vectors-response String index = response.getIndex(); // <1> String type = response.getType(); // <2> @@ -1781,18 +1779,19 @@ public class CRUDDocumentationIT extends OpenSearchRestHighLevelClientTestCase { } - // Not entirely sure if _mtermvectors belongs to CRUD, and in the absence of a better place, will have it here public void testMultiTermVectors() throws Exception { RestHighLevelClient client = highLevelClient(); - CreateIndexRequest authorsRequest = new CreateIndexRequest("authors") - .mapping(XContentFactory.jsonBuilder().startObject() + CreateIndexRequest authorsRequest = new CreateIndexRequest("authors").mapping( + XContentFactory.jsonBuilder() + .startObject() .startObject("properties") - .startObject("user") - .field("type", "keyword") - .endObject() + .startObject("user") + .field("type", "keyword") .endObject() - .endObject()); + .endObject() + .endObject() + ); CreateIndexResponse authorsResponse = client.indices().create(authorsRequest, RequestOptions.DEFAULT); assertTrue(authorsResponse.isAcknowledged()); client.index(new IndexRequest("index").id("1").source("user", "foobar"), RequestOptions.DEFAULT); @@ -1869,16 +1868,17 @@ public class CRUDDocumentationIT extends OpenSearchRestHighLevelClientTestCase { { Request createIndex = new Request("PUT", "/index"); createIndex.setJsonEntity( - "{\n" + - " \"mappings\" : {\n" + - " \"properties\" : {\n" + - " \"foo\" : {\n" + - " \"type\": \"text\",\n" + - " \"store\": true\n" + - " }\n" + - " }\n" + - " }\n" + - "}"); + "{\n" + + " \"mappings\" : {\n" + + " \"properties\" : {\n" + + " \"foo\" : {\n" + + " \"type\": \"text\",\n" + + " \"store\": true\n" + + " }\n" + + " }\n" + + " }\n" + + "}" + ); Response response = client().performRequest(createIndex); assertEquals(200, response.getStatusLine().getStatusCode()); } @@ -1887,10 +1887,10 @@ public class CRUDDocumentationIT extends OpenSearchRestHighLevelClientTestCase { source.put("foo", "val1"); source.put("bar", "val2"); source.put("baz", "val3"); - client.index(new IndexRequest("index") - .id("example_id") - .source(source) - .setRefreshPolicy(RefreshPolicy.IMMEDIATE), RequestOptions.DEFAULT); + client.index( + new IndexRequest("index").id("example_id").source(source).setRefreshPolicy(RefreshPolicy.IMMEDIATE), + RequestOptions.DEFAULT + ); { // tag::multi-get-request diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/ClusterClientDocumentationIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/ClusterClientDocumentationIT.java index 0ec5c77754e..7762813aa53 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/ClusterClientDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/ClusterClientDocumentationIT.java @@ -472,7 +472,6 @@ public class ClusterClientDocumentationIT extends OpenSearchRestHighLevelClientT RemoteInfoRequest request = new RemoteInfoRequest(); // end::remote-info-request - // tag::remote-info-execute-listener ActionListener listener = new ActionListener() { @@ -504,8 +503,8 @@ public class ClusterClientDocumentationIT extends OpenSearchRestHighLevelClientT { Template template = new Template(Settings.builder().put("index.number_of_replicas", 3).build(), null, null); ComponentTemplate componentTemplate = new ComponentTemplate(template, null, null); - PutComponentTemplateRequest putComponentTemplateRequest = - new PutComponentTemplateRequest().name("ct1").componentTemplate(componentTemplate); + PutComponentTemplateRequest putComponentTemplateRequest = new PutComponentTemplateRequest().name("ct1") + .componentTemplate(componentTemplate); client.cluster().putComponentTemplate(putComponentTemplateRequest, RequestOptions.DEFAULT); assertTrue(client.cluster().putComponentTemplate(putComponentTemplateRequest, RequestOptions.DEFAULT).isAcknowledged()); @@ -647,20 +646,16 @@ public class ClusterClientDocumentationIT extends OpenSearchRestHighLevelClientT public void testDeleteComponentTemplate() throws Exception { RestHighLevelClient client = highLevelClient(); { - PutComponentTemplateRequest request = new PutComponentTemplateRequest() - .name("ct1"); + PutComponentTemplateRequest request = new PutComponentTemplateRequest().name("ct1"); - Settings settings = Settings.builder() - .put("index.number_of_shards", 3) - .put("index.number_of_replicas", 1) - .build(); - String mappingJson = "{\n" + - " \"properties\": {\n" + - " \"message\": {\n" + - " \"type\": \"text\"\n" + - " }\n" + - " }\n" + - "}"; + Settings settings = Settings.builder().put("index.number_of_shards", 3).put("index.number_of_replicas", 1).build(); + String mappingJson = "{\n" + + " \"properties\": {\n" + + " \"message\": {\n" + + " \"type\": \"text\"\n" + + " }\n" + + " }\n" + + "}"; AliasMetadata twitterAlias = AliasMetadata.builder("twitter_alias").build(); Map aliases = new HashMap<>(); aliases.put("twitter_alias", twitterAlias); @@ -688,13 +683,9 @@ public class ClusterClientDocumentationIT extends OpenSearchRestHighLevelClientT assertThat(acknowledged, equalTo(true)); { - PutComponentTemplateRequest request = new PutComponentTemplateRequest() - .name("ct1"); + PutComponentTemplateRequest request = new PutComponentTemplateRequest().name("ct1"); - Settings settings = Settings.builder() - .put("index.number_of_shards", 3) - .put("index.number_of_replicas", 1) - .build(); + Settings settings = Settings.builder().put("index.number_of_shards", 3).put("index.number_of_replicas", 1).build(); Template template = new Template(settings, null, null); request.componentTemplate(new ComponentTemplate(template, null, null)); assertTrue(client.cluster().putComponentTemplate(request, RequestOptions.DEFAULT).isAcknowledged()); diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/IndicesClientDocumentationIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/IndicesClientDocumentationIT.java index d4ad4b958ef..ad2b0d1e603 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/IndicesClientDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/IndicesClientDocumentationIT.java @@ -158,8 +158,7 @@ public class IndicesClientDocumentationIT extends OpenSearchRestHighLevelClientT RestHighLevelClient client = highLevelClient(); { - CreateIndexResponse createIndexResponse = client.indices().create(new CreateIndexRequest("twitter"), - RequestOptions.DEFAULT); + CreateIndexResponse createIndexResponse = client.indices().create(new CreateIndexRequest("twitter"), RequestOptions.DEFAULT); assertTrue(createIndexResponse.isAcknowledged()); } @@ -219,6 +218,7 @@ public class IndicesClientDocumentationIT extends OpenSearchRestHighLevelClientT assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } + public void testDeleteIndex() throws IOException { RestHighLevelClient client = highLevelClient(); @@ -587,9 +587,7 @@ public class IndicesClientDocumentationIT extends OpenSearchRestHighLevelClientT CreateIndexResponse createIndexResponse = client.indices().create(new CreateIndexRequest("twitter"), RequestOptions.DEFAULT); assertTrue(createIndexResponse.isAcknowledged()); PutMappingRequest request = new PutMappingRequest("twitter"); - request.source("{ \"properties\": { \"message\": { \"type\": \"text\" } } }", - XContentType.JSON - ); + request.source("{ \"properties\": { \"message\": { \"type\": \"text\" } } }", XContentType.JSON); AcknowledgedResponse putMappingResponse = client.indices().putMapping(request, RequestOptions.DEFAULT); assertTrue(putMappingResponse.isAcknowledged()); } @@ -635,9 +633,7 @@ public class IndicesClientDocumentationIT extends OpenSearchRestHighLevelClientT CreateIndexResponse createIndexResponse = client.indices().create(new CreateIndexRequest("twitter"), RequestOptions.DEFAULT); assertTrue(createIndexResponse.isAcknowledged()); PutMappingRequest request = new PutMappingRequest("twitter"); - request.source("{ \"properties\": { \"message\": { \"type\": \"text\" } } }", - XContentType.JSON - ); + request.source("{ \"properties\": { \"message\": { \"type\": \"text\" } } }", XContentType.JSON); AcknowledgedResponse putMappingResponse = client.indices().putMapping(request, RequestOptions.DEFAULT); assertTrue(putMappingResponse.isAcknowledged()); } @@ -699,17 +695,18 @@ public class IndicesClientDocumentationIT extends OpenSearchRestHighLevelClientT assertTrue(createIndexResponse.isAcknowledged()); PutMappingRequest request = new PutMappingRequest("twitter"); request.source( - "{\n" + - " \"properties\": {\n" + - " \"message\": {\n" + - " \"type\": \"text\"\n" + - " },\n" + - " \"timestamp\": {\n" + - " \"type\": \"date\"\n" + - " }\n" + - " }\n" + - "}", // <1> - XContentType.JSON); + "{\n" + + " \"properties\": {\n" + + " \"message\": {\n" + + " \"type\": \"text\"\n" + + " },\n" + + " \"timestamp\": {\n" + + " \"type\": \"date\"\n" + + " }\n" + + " }\n" + + "}", // <1> + XContentType.JSON + ); AcknowledgedResponse putMappingResponse = client.indices().putMapping(request, RequestOptions.DEFAULT); assertTrue(putMappingResponse.isAcknowledged()); } @@ -767,10 +764,8 @@ public class IndicesClientDocumentationIT extends OpenSearchRestHighLevelClientT final CountDownLatch latch = new CountDownLatch(1); final ActionListener latchListener = new LatchedActionListener<>(listener, latch); listener = ActionListener.wrap(r -> { - final Map> mappings = - r.mappings(); - final Map fieldMappings = - mappings.get("twitter"); + final Map> mappings = r.mappings(); + final Map fieldMappings = mappings.get("twitter"); final GetFieldMappingsResponse.FieldMappingMetadata metadata1 = fieldMappings.get("message"); final String fullName = metadata1.fullName(); @@ -788,10 +783,8 @@ public class IndicesClientDocumentationIT extends OpenSearchRestHighLevelClientT assertTrue(latch.await(30L, TimeUnit.SECONDS)); } - } - public void testOpenIndex() throws Exception { RestHighLevelClient client = highLevelClient(); @@ -1112,8 +1105,8 @@ public class IndicesClientDocumentationIT extends OpenSearchRestHighLevelClientT { Settings settings = Settings.builder().put("number_of_shards", 3).build(); - CreateIndexResponse createIndexResponse = client.indices().create( - new CreateIndexRequest("index").settings(settings), RequestOptions.DEFAULT); + CreateIndexResponse createIndexResponse = client.indices() + .create(new CreateIndexRequest("index").settings(settings), RequestOptions.DEFAULT); assertTrue(createIndexResponse.isAcknowledged()); } @@ -1142,8 +1135,7 @@ public class IndicesClientDocumentationIT extends OpenSearchRestHighLevelClientT assertEquals("3", numberOfShardsString); assertEquals(Integer.valueOf(3), numberOfShards); - assertNull("refresh_interval returned but was never set!", - getSettingsResponse.getSetting("index", "index.refresh_interval")); + assertNull("refresh_interval returned but was never set!", getSettingsResponse.getSetting("index", "index.refresh_interval")); // tag::get-settings-execute-listener ActionListener listener = @@ -1176,8 +1168,8 @@ public class IndicesClientDocumentationIT extends OpenSearchRestHighLevelClientT { Settings settings = Settings.builder().put("number_of_shards", 3).build(); - CreateIndexResponse createIndexResponse = client.indices().create( - new CreateIndexRequest("index").settings(settings), RequestOptions.DEFAULT); + CreateIndexResponse createIndexResponse = client.indices() + .create(new CreateIndexRequest("index").settings(settings), RequestOptions.DEFAULT); assertTrue(createIndexResponse.isAcknowledged()); } @@ -1203,16 +1195,13 @@ public class IndicesClientDocumentationIT extends OpenSearchRestHighLevelClientT assertNotNull("with defaults enabled we should get a value for refresh_interval!", refreshInterval); assertEquals(refreshInterval, indexDefaultSettings.get("index.refresh_interval")); - ActionListener listener = - new ActionListener() { - @Override - public void onResponse(GetSettingsResponse GetSettingsResponse) { - } + ActionListener listener = new ActionListener() { + @Override + public void onResponse(GetSettingsResponse GetSettingsResponse) {} - @Override - public void onFailure(Exception e) { - } - }; + @Override + public void onFailure(Exception e) {} + }; // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); @@ -1228,11 +1217,8 @@ public class IndicesClientDocumentationIT extends OpenSearchRestHighLevelClientT { Settings settings = Settings.builder().put("number_of_shards", 3).build(); String mappings = "{\"properties\":{\"field-1\":{\"type\":\"integer\"}}}"; - CreateIndexRequest createIndexRequest = new CreateIndexRequest("index") - .settings(settings) - .mapping(mappings, XContentType.JSON); - CreateIndexResponse createIndexResponse = client.indices().create( - createIndexRequest, RequestOptions.DEFAULT); + CreateIndexRequest createIndexRequest = new CreateIndexRequest("index").settings(settings).mapping(mappings, XContentType.JSON); + CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT); assertTrue(createIndexResponse.isAcknowledged()); } @@ -1264,8 +1250,7 @@ public class IndicesClientDocumentationIT extends OpenSearchRestHighLevelClientT // end::get-index-response assertEquals( - Collections.singletonMap("properties", - Collections.singletonMap("field-1", Collections.singletonMap("type", "integer"))), + Collections.singletonMap("properties", Collections.singletonMap("field-1", Collections.singletonMap("type", "integer"))), indexTypeMappings ); assertTrue(indexAliases.isEmpty()); @@ -1526,8 +1511,8 @@ public class IndicesClientDocumentationIT extends OpenSearchRestHighLevelClientT RestHighLevelClient client = highLevelClient(); { - CreateIndexResponse createIndexResponse = client.indices().create(new CreateIndexRequest("index") - .alias(new Alias("alias")), RequestOptions.DEFAULT); + CreateIndexResponse createIndexResponse = client.indices() + .create(new CreateIndexRequest("index").alias(new Alias("alias")), RequestOptions.DEFAULT); assertTrue(createIndexResponse.isAcknowledged()); } @@ -1690,8 +1675,10 @@ public class IndicesClientDocumentationIT extends OpenSearchRestHighLevelClientT @SuppressWarnings("unchecked") String firstNode = ((Map) nodes.get("nodes")).keySet().iterator().next(); createIndex("source_index", Settings.builder().put("index.number_of_shards", 4).put("index.number_of_replicas", 0).build()); - updateIndexSettings("source_index", Settings.builder().put("index.routing.allocation.require._name", firstNode) - .put("index.blocks.write", true)); + updateIndexSettings( + "source_index", + Settings.builder().put("index.routing.allocation.require._name", firstNode).put("index.blocks.write", true) + ); } // tag::shrink-index-request @@ -1759,8 +1746,14 @@ public class IndicesClientDocumentationIT extends OpenSearchRestHighLevelClientT RestHighLevelClient client = highLevelClient(); { - createIndex("source_index", Settings.builder().put("index.number_of_shards", 2).put("index.number_of_replicas", 0) - .put("index.number_of_routing_shards", 4).build()); + createIndex( + "source_index", + Settings.builder() + .put("index.number_of_shards", 2) + .put("index.number_of_replicas", 0) + .put("index.number_of_routing_shards", 4) + .build() + ); updateIndexSettings("source_index", Settings.builder().put("index.blocks.write", true)); } @@ -1984,8 +1977,8 @@ public class IndicesClientDocumentationIT extends OpenSearchRestHighLevelClientT RestHighLevelClient client = highLevelClient(); { - CreateIndexResponse createIndexResponse = client.indices().create(new CreateIndexRequest("index").alias(new Alias("alias")), - RequestOptions.DEFAULT); + CreateIndexResponse createIndexResponse = client.indices() + .create(new CreateIndexRequest("index").alias(new Alias("alias")), RequestOptions.DEFAULT); assertTrue(createIndexResponse.isAcknowledged()); } @@ -2317,9 +2310,7 @@ public class IndicesClientDocumentationIT extends OpenSearchRestHighLevelClientT PutIndexTemplateRequest putRequest = new PutIndexTemplateRequest("my-template"); putRequest.patterns(Arrays.asList("pattern-1", "log-*")); putRequest.settings(Settings.builder().put("index.number_of_shards", 3).put("index.number_of_replicas", 1)); - putRequest.mapping("{ \"properties\": { \"message\": { \"type\": \"text\" } } }", - XContentType.JSON - ); + putRequest.mapping("{ \"properties\": { \"message\": { \"type\": \"text\" } } }", XContentType.JSON); assertTrue(client.indices().putTemplate(putRequest, RequestOptions.DEFAULT).isAcknowledged()); } @@ -2374,14 +2365,13 @@ public class IndicesClientDocumentationIT extends OpenSearchRestHighLevelClientT public void testGetIndexTemplatesV2() throws Exception { RestHighLevelClient client = highLevelClient(); { - Template template = new Template(Settings.builder().put("index.number_of_shards", 3).put("index.number_of_replicas", 1).build(), + Template template = new Template( + Settings.builder().put("index.number_of_shards", 3).put("index.number_of_replicas", 1).build(), new CompressedXContent("{ \"properties\": { \"message\": { \"type\": \"text\" } } }"), - null); - PutComposableIndexTemplateRequest putRequest = new PutComposableIndexTemplateRequest() - .name("my-template") - .indexTemplate( - new ComposableIndexTemplate(Arrays.asList("pattern-1", "log-*"), template, null, null, null, null) - ); + null + ); + PutComposableIndexTemplateRequest putRequest = new PutComposableIndexTemplateRequest().name("my-template") + .indexTemplate(new ComposableIndexTemplate(Arrays.asList("pattern-1", "log-*"), template, null, null, null, null)); assertTrue(client.indices().putIndexTemplate(putRequest, RequestOptions.DEFAULT).isAcknowledged()); } @@ -2504,8 +2494,11 @@ public class IndicesClientDocumentationIT extends OpenSearchRestHighLevelClientT { Template template = new Template(Settings.builder().put("index.number_of_replicas", 3).build(), null, null); ComponentTemplate componentTemplate = new ComponentTemplate(template, null, null); - client.cluster().putComponentTemplate(new PutComponentTemplateRequest().name("ct1").componentTemplate(componentTemplate), - RequestOptions.DEFAULT); + client.cluster() + .putComponentTemplate( + new PutComponentTemplateRequest().name("ct1").componentTemplate(componentTemplate), + RequestOptions.DEFAULT + ); // tag::put-index-template-v2-request-component-template PutComposableIndexTemplateRequest request = new PutComposableIndexTemplateRequest() @@ -2590,10 +2583,15 @@ public class IndicesClientDocumentationIT extends OpenSearchRestHighLevelClientT public void testDeleteIndexTemplateV2() throws Exception { RestHighLevelClient client = highLevelClient(); { - PutComposableIndexTemplateRequest request = new PutComposableIndexTemplateRequest() - .name("my-template"); - ComposableIndexTemplate composableIndexTemplate = new ComposableIndexTemplate(Arrays.asList("pattern-1", "log-*"), - null, null, null, null, null); // <2> + PutComposableIndexTemplateRequest request = new PutComposableIndexTemplateRequest().name("my-template"); + ComposableIndexTemplate composableIndexTemplate = new ComposableIndexTemplate( + Arrays.asList("pattern-1", "log-*"), + null, + null, + null, + null, + null + ); // <2> request.indexTemplate(composableIndexTemplate); assertTrue(client.indices().putIndexTemplate(request, RequestOptions.DEFAULT).isAcknowledged()); } @@ -2616,10 +2614,15 @@ public class IndicesClientDocumentationIT extends OpenSearchRestHighLevelClientT assertThat(acknowledged, equalTo(true)); { - PutComposableIndexTemplateRequest request = new PutComposableIndexTemplateRequest() - .name("my-template"); - ComposableIndexTemplate composableIndexTemplate = new ComposableIndexTemplate(Arrays.asList("pattern-1", "log-*"), - null, null, null, null, null); // <2> + PutComposableIndexTemplateRequest request = new PutComposableIndexTemplateRequest().name("my-template"); + ComposableIndexTemplate composableIndexTemplate = new ComposableIndexTemplate( + Arrays.asList("pattern-1", "log-*"), + null, + null, + null, + null, + null + ); // <2> request.indexTemplate(composableIndexTemplate); assertTrue(client.indices().putIndexTemplate(request, RequestOptions.DEFAULT).isAcknowledged()); } @@ -2653,11 +2656,16 @@ public class IndicesClientDocumentationIT extends OpenSearchRestHighLevelClientT RestHighLevelClient client = highLevelClient(); { - PutComposableIndexTemplateRequest request = new PutComposableIndexTemplateRequest() - .name("my-template"); // <1> + PutComposableIndexTemplateRequest request = new PutComposableIndexTemplateRequest().name("my-template"); // <1> Template template = new Template(Settings.builder().put("index.number_of_replicas", 3).build(), null, null); - ComposableIndexTemplate composableIndexTemplate = new ComposableIndexTemplate(Arrays.asList("pattern-1", "log-*"), - template, null, null, null, null); + ComposableIndexTemplate composableIndexTemplate = new ComposableIndexTemplate( + Arrays.asList("pattern-1", "log-*"), + template, + null, + null, + null, + null + ); request.indexTemplate(composableIndexTemplate); assertTrue(client.indices().putIndexTemplate(request, RequestOptions.DEFAULT).isAcknowledged()); } @@ -2896,15 +2904,17 @@ public class IndicesClientDocumentationIT extends OpenSearchRestHighLevelClientT CreateIndexResponse resp = client.indices().create(req, RequestOptions.DEFAULT); assertTrue(resp.isAcknowledged()); - PutMappingRequest pmReq = new PutMappingRequest("my_index") - .source(XContentFactory.jsonBuilder().startObject() + PutMappingRequest pmReq = new PutMappingRequest("my_index").source( + XContentFactory.jsonBuilder() + .startObject() .startObject("properties") - .startObject("my_field") - .field("type", "text") - .field("analyzer", "english") - .endObject() + .startObject("my_field") + .field("type", "text") + .field("analyzer", "english") .endObject() - .endObject()); + .endObject() + .endObject() + ); AcknowledgedResponse pmResp = client.indices().putMapping(pmReq, RequestOptions.DEFAULT); assertTrue(pmResp.isAcknowledged()); @@ -3032,24 +3042,16 @@ public class IndicesClientDocumentationIT extends OpenSearchRestHighLevelClientT } { IndicesAliasesRequest request = new IndicesAliasesRequest(); - AliasActions aliasAction = - new AliasActions(AliasActions.Type.ADD) - .index("index1") - .alias("alias1"); + AliasActions aliasAction = new AliasActions(AliasActions.Type.ADD).index("index1").alias("alias1"); request.addAliasAction(aliasAction); - AcknowledgedResponse indicesAliasesResponse = - client.indices().updateAliases(request, RequestOptions.DEFAULT); + AcknowledgedResponse indicesAliasesResponse = client.indices().updateAliases(request, RequestOptions.DEFAULT); assertTrue(indicesAliasesResponse.isAcknowledged()); } { IndicesAliasesRequest request = new IndicesAliasesRequest(); - AliasActions aliasAction = - new AliasActions(AliasActions.Type.ADD) - .index("index1") - .alias("alias2"); + AliasActions aliasAction = new AliasActions(AliasActions.Type.ADD).index("index1").alias("alias2"); request.addAliasAction(aliasAction); - AcknowledgedResponse indicesAliasesResponse = - client.indices().updateAliases(request, RequestOptions.DEFAULT); + AcknowledgedResponse indicesAliasesResponse = client.indices().updateAliases(request, RequestOptions.DEFAULT); assertTrue(indicesAliasesResponse.isAcknowledged()); } { diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/IngestClientDocumentationIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/IngestClientDocumentationIT.java index 0736dd2e2ef..a6157f29031 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/IngestClientDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/IngestClientDocumentationIT.java @@ -120,9 +120,8 @@ public class IngestClientDocumentationIT extends OpenSearchRestHighLevelClientTe RestHighLevelClient client = highLevelClient(); { - String source = - "{\"description\":\"my set of processors\"," + - "\"processors\":[{\"set\":{\"field\":\"foo\",\"value\":\"bar\"}}]}"; + String source = "{\"description\":\"my set of processors\"," + + "\"processors\":[{\"set\":{\"field\":\"foo\",\"value\":\"bar\"}}]}"; PutPipelineRequest request = new PutPipelineRequest( "my-pipeline-id", new BytesArray(source.getBytes(StandardCharsets.UTF_8)), @@ -351,7 +350,7 @@ public class IngestClientDocumentationIT extends OpenSearchRestHighLevelClientTe } } // end::simulate-pipeline-response - assert(response.getResults().size() > 0); + assert (response.getResults().size() > 0); } } @@ -359,17 +358,16 @@ public class IngestClientDocumentationIT extends OpenSearchRestHighLevelClientTe RestHighLevelClient client = highLevelClient(); { - String source = - "{\"" + - "pipeline\":{" + - "\"description\":\"_description\"," + - "\"processors\":[{\"set\":{\"field\":\"field2\",\"value\":\"_value\"}}]" + - "}," + - "\"docs\":[" + - "{\"_index\":\"index\",\"_id\":\"id\",\"_source\":{\"foo\":\"bar\"}}," + - "{\"_index\":\"index\",\"_id\":\"id\",\"_source\":{\"foo\":\"rab\"}}" + - "]" + - "}"; + String source = "{\"" + + "pipeline\":{" + + "\"description\":\"_description\"," + + "\"processors\":[{\"set\":{\"field\":\"field2\",\"value\":\"_value\"}}]" + + "}," + + "\"docs\":[" + + "{\"_index\":\"index\",\"_id\":\"id\",\"_source\":{\"foo\":\"bar\"}}," + + "{\"_index\":\"index\",\"_id\":\"id\",\"_source\":{\"foo\":\"rab\"}}" + + "]" + + "}"; SimulatePipelineRequest request = new SimulatePipelineRequest( new BytesArray(source.getBytes(StandardCharsets.UTF_8)), XContentType.JSON diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/QueryDSLDocumentationTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/QueryDSLDocumentationTests.java index 135a0bea730..47a116458cb 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/QueryDSLDocumentationTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/QueryDSLDocumentationTests.java @@ -473,30 +473,18 @@ public class QueryDSLDocumentationTests extends OpenSearchTestCase { } public void testRankFeatureSaturationPivot() { - RankFeatureQueryBuilders.saturation( - "pagerank", - 8 - ); + RankFeatureQueryBuilders.saturation("pagerank", 8); } public void testRankFeatureLog() { - RankFeatureQueryBuilders.log( - "pagerank", - 4f - ); + RankFeatureQueryBuilders.log("pagerank", 4f); } public void testRankFeatureSigmoid() { - RankFeatureQueryBuilders.sigmoid( - "pagerank", - 7, - 0.6f - ); + RankFeatureQueryBuilders.sigmoid("pagerank", 7, 0.6f); } public void testRankFeatureLinear() { - RankFeatureQueryBuilders.linear( - "pagerank" - ); + RankFeatureQueryBuilders.linear("pagerank"); } } diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/SearchDocumentationIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/SearchDocumentationIT.java index 1d51837bf51..d514f66ff36 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/SearchDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/SearchDocumentationIT.java @@ -144,7 +144,7 @@ import static org.hamcrest.Matchers.greaterThan; */ public class SearchDocumentationIT extends OpenSearchRestHighLevelClientTestCase { - @SuppressWarnings({"unused", "unchecked"}) + @SuppressWarnings({ "unused", "unchecked" }) public void testSearch() throws Exception { indexSearchTestData(); RestHighLevelClient client = highLevelClient(); @@ -319,12 +319,9 @@ public class SearchDocumentationIT extends OpenSearchRestHighLevelClientTestCase RestHighLevelClient client = highLevelClient(); { BulkRequest request = new BulkRequest(); - request.add(new IndexRequest("posts").id("1") - .source(XContentType.JSON, "company", "OpenSearch", "age", 20)); - request.add(new IndexRequest("posts").id("2") - .source(XContentType.JSON, "company", "OpenSearch", "age", 30)); - request.add(new IndexRequest("posts").id("3") - .source(XContentType.JSON, "company", "OpenSearch", "age", 40)); + request.add(new IndexRequest("posts").id("1").source(XContentType.JSON, "company", "OpenSearch", "age", 20)); + request.add(new IndexRequest("posts").id("2").source(XContentType.JSON, "company", "OpenSearch", "age", 30)); + request.add(new IndexRequest("posts").id("3").source(XContentType.JSON, "company", "OpenSearch", "age", 40)); request.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT); assertSame(RestStatus.OK, bulkResponse.status()); @@ -390,7 +387,7 @@ public class SearchDocumentationIT extends OpenSearchRestHighLevelClientTestCase } } - @SuppressWarnings({"unused", "rawtypes"}) + @SuppressWarnings({ "unused", "rawtypes" }) public void testSearchRequestSuggestions() throws IOException { RestHighLevelClient client = highLevelClient(); { @@ -438,15 +435,42 @@ public class SearchDocumentationIT extends OpenSearchRestHighLevelClientTestCase RestHighLevelClient client = highLevelClient(); { BulkRequest request = new BulkRequest(); - request.add(new IndexRequest("posts").id("1") - .source(XContentType.JSON, "title", "In which order are my OpenSearch queries executed?", "user", - Arrays.asList("foobar", "quxx"), "innerObject", Collections.singletonMap("key", "value"))); - request.add(new IndexRequest("posts").id("2") - .source(XContentType.JSON, "title", "Current status and upcoming changes in OpenSearch", "user", - Arrays.asList("foobar", "grault"), "innerObject", Collections.singletonMap("key", "value"))); - request.add(new IndexRequest("posts").id("3") - .source(XContentType.JSON, "title", "The Future of Federated Search in OpenSearch", "user", - Arrays.asList("foobar", "quuz"), "innerObject", Collections.singletonMap("key", "value"))); + request.add( + new IndexRequest("posts").id("1") + .source( + XContentType.JSON, + "title", + "In which order are my OpenSearch queries executed?", + "user", + Arrays.asList("foobar", "quxx"), + "innerObject", + Collections.singletonMap("key", "value") + ) + ); + request.add( + new IndexRequest("posts").id("2") + .source( + XContentType.JSON, + "title", + "Current status and upcoming changes in OpenSearch", + "user", + Arrays.asList("foobar", "grault"), + "innerObject", + Collections.singletonMap("key", "value") + ) + ); + request.add( + new IndexRequest("posts").id("3") + .source( + XContentType.JSON, + "title", + "The Future of Federated Search in OpenSearch", + "user", + Arrays.asList("foobar", "quuz"), + "innerObject", + Collections.singletonMap("key", "value") + ) + ); request.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT); assertSame(RestStatus.OK, bulkResponse.status()); @@ -465,9 +489,9 @@ public class SearchDocumentationIT extends OpenSearchRestHighLevelClientTestCase highlightBuilder.field(highlightUser); searchSourceBuilder.highlighter(highlightBuilder); // end::search-request-highlighting - searchSourceBuilder.query(QueryBuilders.boolQuery() - .should(matchQuery("title", "OpenSearch")) - .should(matchQuery("user", "foobar"))); + searchSourceBuilder.query( + QueryBuilders.boolQuery().should(matchQuery("title", "OpenSearch")).should(matchQuery("user", "foobar")) + ); searchRequest.source(searchSourceBuilder); SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); { @@ -501,8 +525,7 @@ public class SearchDocumentationIT extends OpenSearchRestHighLevelClientTestCase public void testSearchRequestProfiling() throws IOException { RestHighLevelClient client = highLevelClient(); { - IndexRequest request = new IndexRequest("posts").id("1") - .source(XContentType.JSON, "tags", "opensearch", "comments", 123); + IndexRequest request = new IndexRequest("posts").id("1").source(XContentType.JSON, "tags", "opensearch", "comments", 123); request.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL); IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT); assertSame(RestStatus.CREATED, indexResponse.status()); @@ -573,12 +596,15 @@ public class SearchDocumentationIT extends OpenSearchRestHighLevelClientTestCase RestHighLevelClient client = highLevelClient(); { BulkRequest request = new BulkRequest(); - request.add(new IndexRequest("posts").id("1") - .source(XContentType.JSON, "title", "In which order are my OpenSearch queries executed?")); - request.add(new IndexRequest("posts").id("2") - .source(XContentType.JSON, "title", "Current status and upcoming changes in OpenSearch")); - request.add(new IndexRequest("posts").id("3") - .source(XContentType.JSON, "title", "The Future of Federated Search in OpenSearch")); + request.add( + new IndexRequest("posts").id("1").source(XContentType.JSON, "title", "In which order are my OpenSearch queries executed?") + ); + request.add( + new IndexRequest("posts").id("2").source(XContentType.JSON, "title", "Current status and upcoming changes in OpenSearch") + ); + request.add( + new IndexRequest("posts").id("3").source(XContentType.JSON, "title", "The Future of Federated Search in OpenSearch") + ); request.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT); assertSame(RestStatus.OK, bulkResponse.status()); @@ -851,7 +877,6 @@ public class SearchDocumentationIT extends OpenSearchRestHighLevelClientTestCase assertTrue(latch.await(30L, TimeUnit.SECONDS)); } - @SuppressWarnings("unused") public void testMultiSearchTemplateWithInlineScript() throws Exception { indexSearchTestData(); @@ -934,9 +959,6 @@ public class SearchDocumentationIT extends OpenSearchRestHighLevelClientTestCase } // end::multi-search-template-request-stored - - - // tag::multi-search-template-execute MultiSearchTemplateResponse multiResponse = client.msearchTemplate(multiRequest, RequestOptions.DEFAULT); // end::multi-search-template-execute @@ -990,7 +1012,6 @@ public class SearchDocumentationIT extends OpenSearchRestHighLevelClientTestCase assertEquals(RestStatus.OK.getStatus(), scriptResponse.getStatusLine().getStatusCode()); } - public void testExplain() throws Exception { indexSearchTestData(); RestHighLevelClient client = highLevelClient(); @@ -1103,9 +1124,9 @@ public class SearchDocumentationIT extends OpenSearchRestHighLevelClientTestCase assertTrue(isSearchable); assertFalse(isAggregatable); - assertArrayEquals(indices, new String[]{"authors", "contributors"}); + assertArrayEquals(indices, new String[] { "authors", "contributors" }); assertNull(nonSearchableIndices); - assertArrayEquals(nonAggregatableIndices, new String[]{"authors"}); + assertArrayEquals(nonAggregatableIndices, new String[] { "authors" }); // tag::field-caps-execute-listener ActionListener listener = new ActionListener() { @@ -1261,52 +1282,86 @@ public class SearchDocumentationIT extends OpenSearchRestHighLevelClientTestCase } private void indexSearchTestData() throws IOException { - CreateIndexRequest authorsRequest = new CreateIndexRequest("authors") - .mapping(XContentFactory.jsonBuilder().startObject() + CreateIndexRequest authorsRequest = new CreateIndexRequest("authors").mapping( + XContentFactory.jsonBuilder() + .startObject() .startObject("properties") - .startObject("id") - .field("type", "keyword") - .endObject() - .startObject("user") - .field("type", "keyword") - .field("doc_values", "false") - .endObject() + .startObject("id") + .field("type", "keyword") .endObject() - .endObject()); + .startObject("user") + .field("type", "keyword") + .field("doc_values", "false") + .endObject() + .endObject() + .endObject() + ); CreateIndexResponse authorsResponse = highLevelClient().indices().create(authorsRequest, RequestOptions.DEFAULT); assertTrue(authorsResponse.isAcknowledged()); - CreateIndexRequest reviewersRequest = new CreateIndexRequest("contributors") - .mapping(XContentFactory.jsonBuilder().startObject() + CreateIndexRequest reviewersRequest = new CreateIndexRequest("contributors").mapping( + XContentFactory.jsonBuilder() + .startObject() .startObject("properties") - .startObject("id") - .field("type", "keyword") - .endObject() - .startObject("user") - .field("type", "keyword") - .field("store", "true") - .endObject() + .startObject("id") + .field("type", "keyword") .endObject() - .endObject()); + .startObject("user") + .field("type", "keyword") + .field("store", "true") + .endObject() + .endObject() + .endObject() + ); CreateIndexResponse reviewersResponse = highLevelClient().indices().create(reviewersRequest, RequestOptions.DEFAULT); assertTrue(reviewersResponse.isAcknowledged()); BulkRequest bulkRequest = new BulkRequest(); - bulkRequest.add(new IndexRequest("posts").id("1") - .source(XContentType.JSON, "id", 1, "title", "In which order are my OpenSearch queries executed?", "user", - Arrays.asList("foobar", "quxx"), "innerObject", Collections.singletonMap("key", "value"))); - bulkRequest.add(new IndexRequest("posts").id("2") - .source(XContentType.JSON, "id", 2, "title", "Current status and upcoming changes in OpenSearch", "user", - Arrays.asList("foobar", "grault"), "innerObject", Collections.singletonMap("key", "value"))); - bulkRequest.add(new IndexRequest("posts").id("3") - .source(XContentType.JSON, "id", 3, "title", "The Future of Federated Search in OpenSearch", "user", - Arrays.asList("foobar", "quuz"), "innerObject", Collections.singletonMap("key", "value"))); - - bulkRequest.add(new IndexRequest("authors").id("1") - .source(XContentType.JSON, "id", 1, "user", "foobar")); - bulkRequest.add(new IndexRequest("contributors").id("1") - .source(XContentType.JSON, "id", 1, "user", "quuz")); + bulkRequest.add( + new IndexRequest("posts").id("1") + .source( + XContentType.JSON, + "id", + 1, + "title", + "In which order are my OpenSearch queries executed?", + "user", + Arrays.asList("foobar", "quxx"), + "innerObject", + Collections.singletonMap("key", "value") + ) + ); + bulkRequest.add( + new IndexRequest("posts").id("2") + .source( + XContentType.JSON, + "id", + 2, + "title", + "Current status and upcoming changes in OpenSearch", + "user", + Arrays.asList("foobar", "grault"), + "innerObject", + Collections.singletonMap("key", "value") + ) + ); + bulkRequest.add( + new IndexRequest("posts").id("3") + .source( + XContentType.JSON, + "id", + 3, + "title", + "The Future of Federated Search in OpenSearch", + "user", + Arrays.asList("foobar", "quuz"), + "innerObject", + Collections.singletonMap("key", "value") + ) + ); + bulkRequest.add(new IndexRequest("authors").id("1").source(XContentType.JSON, "id", 1, "user", "foobar")); + bulkRequest.add(new IndexRequest("contributors").id("1").source(XContentType.JSON, "id", 1, "user", "quuz")); bulkRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); BulkResponse bulkResponse = highLevelClient().bulk(bulkRequest, RequestOptions.DEFAULT); @@ -1314,8 +1369,7 @@ public class SearchDocumentationIT extends OpenSearchRestHighLevelClientTestCase assertFalse(bulkResponse.hasFailures()); } - - @SuppressWarnings({"unused", "unchecked"}) + @SuppressWarnings({ "unused", "unchecked" }) public void testCount() throws Exception { indexCountTestData(); RestHighLevelClient client = highLevelClient(); @@ -1400,32 +1454,59 @@ public class SearchDocumentationIT extends OpenSearchRestHighLevelClientTestCase } private static void indexCountTestData() throws IOException { - CreateIndexRequest authorsRequest = new CreateIndexRequest("author") - .mapping(XContentFactory.jsonBuilder().startObject() + CreateIndexRequest authorsRequest = new CreateIndexRequest("author").mapping( + XContentFactory.jsonBuilder() + .startObject() .startObject("properties") - .startObject("user") - .field("type", "keyword") - .field("doc_values", "false") - .endObject() + .startObject("user") + .field("type", "keyword") + .field("doc_values", "false") .endObject() - .endObject()); + .endObject() + .endObject() + ); CreateIndexResponse authorsResponse = highLevelClient().indices().create(authorsRequest, RequestOptions.DEFAULT); assertTrue(authorsResponse.isAcknowledged()); BulkRequest bulkRequest = new BulkRequest(); - bulkRequest.add(new IndexRequest("blog").id("1") - .source(XContentType.JSON, "title", "Doubling Down on Open?", "user", - Collections.singletonList("foobar"), "innerObject", Collections.singletonMap("key", "value"))); - bulkRequest.add(new IndexRequest("blog").id("2") - .source(XContentType.JSON, "title", "XYZ Joins Forces with OpenSearch", "user", - Arrays.asList("foobar", "matt"), "innerObject", Collections.singletonMap("key", "value"))); - bulkRequest.add(new IndexRequest("blog").id("3") - .source(XContentType.JSON, "title", "On Net Neutrality", "user", - Arrays.asList("tyler", "foobar"), "innerObject", Collections.singletonMap("key", "value"))); - - bulkRequest.add(new IndexRequest("author").id("1") - .source(XContentType.JSON, "user", "foobar")); + bulkRequest.add( + new IndexRequest("blog").id("1") + .source( + XContentType.JSON, + "title", + "Doubling Down on Open?", + "user", + Collections.singletonList("foobar"), + "innerObject", + Collections.singletonMap("key", "value") + ) + ); + bulkRequest.add( + new IndexRequest("blog").id("2") + .source( + XContentType.JSON, + "title", + "XYZ Joins Forces with OpenSearch", + "user", + Arrays.asList("foobar", "matt"), + "innerObject", + Collections.singletonMap("key", "value") + ) + ); + bulkRequest.add( + new IndexRequest("blog").id("3") + .source( + XContentType.JSON, + "title", + "On Net Neutrality", + "user", + Arrays.asList("tyler", "foobar"), + "innerObject", + Collections.singletonMap("key", "value") + ) + ); + bulkRequest.add(new IndexRequest("author").id("1").source(XContentType.JSON, "user", "foobar")); bulkRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); BulkResponse bulkResponse = highLevelClient().bulk(bulkRequest, RequestOptions.DEFAULT); diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/SnapshotClientDocumentationIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/SnapshotClientDocumentationIT.java index d45ab0dcd33..0ca3c0cd5a5 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/SnapshotClientDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/SnapshotClientDocumentationIT.java @@ -318,7 +318,6 @@ public class SnapshotClientDocumentationIT extends OpenSearchRestHighLevelClient request.includeAliases(false); // <1> // end::restore-snapshot-request-include-aliases - // tag::restore-snapshot-request-indices request.indices("test_index"); // <1> // end::restore-snapshot-request-indices diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/StoredScriptsDocumentationIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/StoredScriptsDocumentationIT.java index 48944a23f87..c9c36a6165c 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/StoredScriptsDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/StoredScriptsDocumentationIT.java @@ -85,10 +85,11 @@ public class StoredScriptsDocumentationIT extends OpenSearchRestHighLevelClientT public void testGetStoredScript() throws Exception { RestHighLevelClient client = highLevelClient(); - final StoredScriptSource scriptSource = - new StoredScriptSource("painless", - "Math.log(_score * 2) + params.my_modifier", - Collections.singletonMap(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType())); + final StoredScriptSource scriptSource = new StoredScriptSource( + "painless", + "Math.log(_score * 2) + params.my_modifier", + Collections.singletonMap(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType()) + ); putStoredScript("calculate-score", scriptSource); @@ -148,10 +149,11 @@ public class StoredScriptsDocumentationIT extends OpenSearchRestHighLevelClientT public void testDeleteStoredScript() throws Exception { RestHighLevelClient client = highLevelClient(); - final StoredScriptSource scriptSource = - new StoredScriptSource("painless", - "Math.log(_score * 2) + params.my_modifier", - Collections.singletonMap(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType())); + final StoredScriptSource scriptSource = new StoredScriptSource( + "painless", + "Math.log(_score * 2) + params.my_modifier", + Collections.singletonMap(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType()) + ); putStoredScript("calculate-score", scriptSource); @@ -256,7 +258,6 @@ public class StoredScriptsDocumentationIT extends OpenSearchRestHighLevelClientT request.content(BytesReference.bytes(builder), XContentType.JSON); // <1> // end::put-stored-script-content-painless - // tag::put-stored-script-execute AcknowledgedResponse putStoredScriptResponse = client.putScript(request, RequestOptions.DEFAULT); // end::put-stored-script-execute @@ -321,8 +322,7 @@ public class StoredScriptsDocumentationIT extends OpenSearchRestHighLevelClientT } private void putStoredScript(String id, StoredScriptSource scriptSource) throws IOException { - PutStoredScriptRequest request = - new PutStoredScriptRequest(id, "score", new BytesArray("{}"), XContentType.JSON, scriptSource); + PutStoredScriptRequest request = new PutStoredScriptRequest(id, "score", new BytesArray("{}"), XContentType.JSON, scriptSource); assertAcked(execute(request, highLevelClient()::putScript, highLevelClient()::putScriptAsync)); } } diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/TasksClientDocumentationIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/TasksClientDocumentationIT.java index a49eea9c14c..05479e2e3e8 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/TasksClientDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/TasksClientDocumentationIT.java @@ -202,7 +202,6 @@ public class TasksClientDocumentationIT extends OpenSearchRestHighLevelClientTes List groups = response.getTaskGroups(); // <2> // end::cancel-tasks-response-calc - // tag::cancel-tasks-response-failures List nodeFailures = response.getNodeFailures(); // <1> List taskFailures = response.getTaskFailures(); // <2> diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/indices/AnalyzeRequestTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/indices/AnalyzeRequestTests.java index 3819e652e96..8ae1dc0f4db 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/indices/AnalyzeRequestTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/indices/AnalyzeRequestTests.java @@ -56,8 +56,7 @@ public abstract class AnalyzeRequestTests extends AbstractRequestTestCase { +public class CloseIndexResponseTests extends AbstractResponseTestCase< + org.opensearch.action.admin.indices.close.CloseIndexResponse, + CloseIndexResponse> { @Override protected org.opensearch.action.admin.indices.close.CloseIndexResponse createServerTestInstance(XContentType xContentType) { @@ -113,15 +114,18 @@ public class CloseIndexResponseTests extends } @Override - protected void assertInstances(final org.opensearch.action.admin.indices.close.CloseIndexResponse serverInstance, - final CloseIndexResponse clientInstance) { + protected void assertInstances( + final org.opensearch.action.admin.indices.close.CloseIndexResponse serverInstance, + final CloseIndexResponse clientInstance + ) { assertNotSame(serverInstance, clientInstance); assertThat(clientInstance.isAcknowledged(), equalTo(serverInstance.isAcknowledged())); assertThat(clientInstance.isShardsAcknowledged(), equalTo(serverInstance.isShardsAcknowledged())); assertThat(clientInstance.getIndices(), hasSize(serverInstance.getIndices().size())); serverInstance.getIndices().forEach(expectedIndexResult -> { - List actualIndexResults = clientInstance.getIndices().stream() + List actualIndexResults = clientInstance.getIndices() + .stream() .filter(result -> result.getIndex().equals(expectedIndexResult.getIndex().getName())) .collect(Collectors.toList()); assertThat(actualIndexResults, hasSize(1)); @@ -142,10 +146,11 @@ public class CloseIndexResponseTests extends if (expectedIndexResult.getShards() != null) { assertThat(actualIndexResult.getException(), nullValue()); - List failedShardResults = - Arrays.stream(expectedIndexResult.getShards()) - .filter(org.opensearch.action.admin.indices.close.CloseIndexResponse.ShardResult::hasFailures) - .collect(Collectors.toList()); + List failedShardResults = Arrays.stream( + expectedIndexResult.getShards() + ) + .filter(org.opensearch.action.admin.indices.close.CloseIndexResponse.ShardResult::hasFailures) + .collect(Collectors.toList()); if (failedShardResults.isEmpty()) { assertThat(actualIndexResult.hasFailures(), is(false)); @@ -169,8 +174,8 @@ public class CloseIndexResponseTests extends assertThat(actualShardResult.getFailures().length, equalTo(failedShardResult.getFailures().length)); for (int i = 0; i < failedShardResult.getFailures().length; i++) { - org.opensearch.action.admin.indices.close.CloseIndexResponse.ShardResult.Failure expectedFailure = - failedShardResult.getFailures()[i]; + org.opensearch.action.admin.indices.close.CloseIndexResponse.ShardResult.Failure expectedFailure = failedShardResult + .getFailures()[i]; CloseIndexResponse.ShardResult.Failure actualFailure = actualShardResult.getFailures()[i]; assertThat(actualFailure.getNodeId(), equalTo(expectedFailure.getNodeId())); assertThat(actualFailure.index(), equalTo(expectedFailure.index())); @@ -193,7 +198,8 @@ public class CloseIndexResponseTests extends final XContentParser parser = xContent.createParser( NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, - bytes.streamInput()); + bytes.streamInput() + ); final CloseIndexResponse actual = doParseToClientInstance(parser); assertThat(actual, notNullValue()); @@ -204,7 +210,8 @@ public class CloseIndexResponseTests extends { final boolean acknowledged = randomBoolean(); final boolean shardsAcknowledged = acknowledged ? randomBoolean() : false; - final ShardsAcknowledgedResponse expected = new ShardsAcknowledgedResponse(acknowledged, shardsAcknowledged){}; + final ShardsAcknowledgedResponse expected = new ShardsAcknowledgedResponse(acknowledged, shardsAcknowledged) { + }; final XContentType xContentType = randomFrom(XContentType.values()); final BytesReference bytes = toShuffledXContent(expected, xContentType, getParams(), randomBoolean()); @@ -212,7 +219,8 @@ public class CloseIndexResponseTests extends final XContentParser parser = xContent.createParser( NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, - bytes.streamInput()); + bytes.streamInput() + ); final CloseIndexResponse actual = doParseToClientInstance(parser); assertThat(actual, notNullValue()); @@ -222,13 +230,17 @@ public class CloseIndexResponseTests extends } } - private org.opensearch.action.admin.indices.close.CloseIndexResponse.ShardResult.Failure newFailure(final String indexName, - final int shard, - final String nodeId) { - Exception exception = randomFrom(new IndexNotFoundException(indexName), + private org.opensearch.action.admin.indices.close.CloseIndexResponse.ShardResult.Failure newFailure( + final String indexName, + final int shard, + final String nodeId + ) { + Exception exception = randomFrom( + new IndexNotFoundException(indexName), new ActionNotFoundTransportException("test"), new IOException("boom", new NullPointerException()), - new OpenSearchStatusException("something", RestStatus.TOO_MANY_REQUESTS)); + new OpenSearchStatusException("something", RestStatus.TOO_MANY_REQUESTS) + ); return new org.opensearch.action.admin.indices.close.CloseIndexResponse.ShardResult.Failure(indexName, shard, exception, nodeId); } } diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/indices/CreateIndexRequestTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/indices/CreateIndexRequestTests.java index 46d66aa8c68..6d9695c376e 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/indices/CreateIndexRequestTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/indices/CreateIndexRequestTests.java @@ -68,8 +68,10 @@ public class CreateIndexRequestTests extends AbstractXContentTestCase exceptions = new ArrayList<>(); for (int i = 0; i < failedShards; i++) { - exceptions.add(new DefaultShardOperationFailedException(randomAlphaOfLength(8).toLowerCase(Locale.getDefault()), - randomInt(totalShards), new OpenSearchException("boom"))); + exceptions.add( + new DefaultShardOperationFailedException( + randomAlphaOfLength(8).toLowerCase(Locale.getDefault()), + randomInt(totalShards), + new OpenSearchException("boom") + ) + ); } - return new DataStreamsStatsAction.Response(totalShards, successfulShards, failedShards, exceptions, - dataStreamCount, backingIndicesTotal, new ByteSizeValue(totalStoreSize), - dataStreamStats.toArray(new DataStreamsStatsAction.DataStreamStats[0])); + return new DataStreamsStatsAction.Response( + totalShards, + successfulShards, + failedShards, + exceptions, + dataStreamCount, + backingIndicesTotal, + new ByteSizeValue(totalStoreSize), + dataStreamStats.toArray(new DataStreamsStatsAction.DataStreamStats[0]) + ); } @Override @@ -99,8 +112,7 @@ public class DataStreamsStatsResponseTests extends AbstractResponseTestCase true) - .test(); + GetComponentTemplatesResponse::fromXContent + ).supportsUnknownFields(true).randomFieldsExcludeFilter(a -> true).test(); } public static Template randomTemplate() { @@ -80,8 +78,10 @@ public class GetComponentTemplatesResponseTests extends OpenSearchTestCase { if (randomBoolean()) { return Collections.singletonMap(randomAlphaOfLength(4), randomAlphaOfLength(4)); } else { - return Collections.singletonMap(randomAlphaOfLength(5), - Collections.singletonMap(randomAlphaOfLength(4), randomAlphaOfLength(4))); + return Collections.singletonMap( + randomAlphaOfLength(5), + Collections.singletonMap(randomAlphaOfLength(4), randomAlphaOfLength(4)) + ); } } @@ -141,8 +141,6 @@ public class GetComponentTemplatesResponseTests extends OpenSearchTestCase { } private static Settings randomSettings() { - return Settings.builder() - .put(randomAlphaOfLength(4), randomAlphaOfLength(10)) - .build(); + return Settings.builder().put(randomAlphaOfLength(4), randomAlphaOfLength(10)).build(); } } diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetComposableIndexTemplatesResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetComposableIndexTemplatesResponseTests.java index ab2a54519e9..d2fd4ed1629 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetComposableIndexTemplatesResponseTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetComposableIndexTemplatesResponseTests.java @@ -53,10 +53,8 @@ public class GetComposableIndexTemplatesResponseTests extends OpenSearchTestCase this::createParser, GetComposableIndexTemplatesResponseTests::createTestInstance, GetComposableIndexTemplatesResponseTests::toXContent, - GetComposableIndexTemplatesResponse::fromXContent) - .supportsUnknownFields(true) - .randomFieldsExcludeFilter(a -> true) - .test(); + GetComposableIndexTemplatesResponse::fromXContent + ).supportsUnknownFields(true).randomFieldsExcludeFilter(a -> true).test(); } private static GetComposableIndexTemplatesResponse createTestInstance() { diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetFieldMappingsResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetFieldMappingsResponseTests.java index 5d23ab2514e..b8662420851 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetFieldMappingsResponseTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetFieldMappingsResponseTests.java @@ -51,17 +51,14 @@ public class GetFieldMappingsResponseTests extends OpenSearchTestCase { this::createParser, GetFieldMappingsResponseTests::createTestInstance, GetFieldMappingsResponseTests::toXContent, - GetFieldMappingsResponse::fromXContent) - .supportsUnknownFields(true) - .randomFieldsExcludeFilter(getRandomFieldsExcludeFilter()) - .test(); + GetFieldMappingsResponse::fromXContent + ).supportsUnknownFields(true).randomFieldsExcludeFilter(getRandomFieldsExcludeFilter()).test(); } private Predicate getRandomFieldsExcludeFilter() { // allow random fields at the level of `index` and `index.mappings.field` // otherwise random field could be evaluated as index name or type name - return s -> false == (s.matches("(?[^.]+)") - || s.matches("(?[^.]+)\\.mappings\\.(?[^.]+)")); + return s -> false == (s.matches("(?[^.]+)") || s.matches("(?[^.]+)\\.mappings\\.(?[^.]+)")); } private static GetFieldMappingsResponse createTestInstance() { diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetIndexResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetIndexResponseTests.java index 1b7d340605f..2141ce30dce 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetIndexResponseTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetIndexResponseTests.java @@ -69,8 +69,8 @@ public class GetIndexResponseTests extends OpenSearchTestCase { this::createParser, GetIndexResponseTests::createTestInstance, GetIndexResponseTests::toXContent, - GetIndexResponse::fromXContent) - .supportsUnknownFields(false) + GetIndexResponse::fromXContent + ).supportsUnknownFields(false) .assertToXContentEquivalence(false) .assertEqualsConsumer(GetIndexResponseTests::assertEqualInstances) .test(); @@ -93,12 +93,12 @@ public class GetIndexResponseTests extends OpenSearchTestCase { Map dataStreams = new HashMap<>(); IndexScopedSettings indexScopedSettings = IndexScopedSettings.DEFAULT_SCOPED_SETTINGS; boolean includeDefaults = randomBoolean(); - for (String index: indices) { + for (String index : indices) { mappings.put(index, createMappingsForIndex()); List aliasMetadataList = new ArrayList<>(); int aliasesNum = randomIntBetween(0, 3); - for (int i=0; i expectedMapping = - XContentHelper.convertToMap(mappingSource, true, xContentBuilder.contentType()).v2(); + Map expectedMapping = XContentHelper.convertToMap(mappingSource, true, xContentBuilder.contentType()) + .v2(); assertThat(result.mappings().sourceAsMap(), equalTo(expectedMapping.get("_doc"))); assertThat(result.aliases().size(), equalTo(esIMD.aliases().size())); @@ -146,8 +154,7 @@ public class GetIndexTemplatesResponseTests extends OpenSearchTestCase { } private Predicate randomFieldsExcludeFilter() { - return (field) -> - field.isEmpty() + return (field) -> field.isEmpty() || field.endsWith("aliases") || field.endsWith("settings") || field.endsWith("settings.index") @@ -159,11 +166,10 @@ public class GetIndexTemplatesResponseTests extends OpenSearchTestCase { private static void assertEqualInstances(GetIndexTemplatesResponse expectedInstance, GetIndexTemplatesResponse newInstance) { assertEquals(expectedInstance, newInstance); // Check there's no doc types at the root of the mapping - Map expectedMap = XContentHelper.convertToMap( - new BytesArray(mappingString), true, XContentType.JSON).v2(); + Map expectedMap = XContentHelper.convertToMap(new BytesArray(mappingString), true, XContentType.JSON).v2(); for (IndexTemplateMetadata template : newInstance.getIndexTemplates()) { MappingMetadata mappingMD = template.mappings(); - if(mappingMD != null) { + if (mappingMD != null) { Map mappingAsMap = mappingMD.sourceAsMap(); assertEquals(expectedMap, mappingAsMap); } @@ -206,18 +212,18 @@ public class GetIndexTemplatesResponseTests extends OpenSearchTestCase { // As the client class GetIndexTemplatesResponse doesn't have toXContent method, adding this method here only for the test static void toXContent(GetIndexTemplatesResponse response, XContentBuilder builder) throws IOException { - //Create a server-side counterpart for the client-side class and call toXContent on it + // Create a server-side counterpart for the client-side class and call toXContent on it List serverIndexTemplates = new ArrayList<>(); List clientIndexTemplates = response.getIndexTemplates(); for (IndexTemplateMetadata clientITMD : clientIndexTemplates) { org.opensearch.cluster.metadata.IndexTemplateMetadata.Builder serverTemplateBuilder = - org.opensearch.cluster.metadata.IndexTemplateMetadata.builder(clientITMD.name()); + org.opensearch.cluster.metadata.IndexTemplateMetadata.builder(clientITMD.name()); serverTemplateBuilder.patterns(clientITMD.patterns()); Iterator aliases = clientITMD.aliases().valuesIt(); - aliases.forEachRemaining((a)->serverTemplateBuilder.putAlias(a)); + aliases.forEachRemaining((a) -> serverTemplateBuilder.putAlias(a)); serverTemplateBuilder.settings(clientITMD.settings()); serverTemplateBuilder.order(clientITMD.order()); @@ -228,8 +234,8 @@ public class GetIndexTemplatesResponseTests extends OpenSearchTestCase { serverIndexTemplates.add(serverTemplateBuilder.build()); } - org.opensearch.action.admin.indices.template.get.GetIndexTemplatesResponse serverResponse = new - org.opensearch.action.admin.indices.template.get.GetIndexTemplatesResponse(serverIndexTemplates); + org.opensearch.action.admin.indices.template.get.GetIndexTemplatesResponse serverResponse = + new org.opensearch.action.admin.indices.template.get.GetIndexTemplatesResponse(serverIndexTemplates); serverResponse.toXContent(builder, ToXContent.EMPTY_PARAMS); } diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetMappingsResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetMappingsResponseTests.java index 6721514309b..817bce359b7 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetMappingsResponseTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetMappingsResponseTests.java @@ -61,16 +61,15 @@ public class GetMappingsResponseTests extends OpenSearchTestCase { this::createParser, GetMappingsResponseTests::createTestInstance, GetMappingsResponseTests::toXContent, - GetMappingsResponse::fromXContent) - .supportsUnknownFields(true) + GetMappingsResponse::fromXContent + ).supportsUnknownFields(true) .assertEqualsConsumer(GetMappingsResponseTests::assertEqualInstances) .randomFieldsExcludeFilter(randomFieldsExcludeFilter()) .test(); } private static GetMappingsResponse createTestInstance() { - Map mappings = Collections.singletonMap( - "index-" + randomAlphaOfLength(5), randomMappingMetadata()); + Map mappings = Collections.singletonMap("index-" + randomAlphaOfLength(5), randomMappingMetadata()); return new GetMappingsResponse(mappings); } @@ -113,8 +112,7 @@ public class GetMappingsResponseTests extends OpenSearchTestCase { } private static void toXContent(GetMappingsResponse response, XContentBuilder builder) throws IOException { - Params params = new ToXContent.MapParams( - Collections.singletonMap(BaseRestHandler.INCLUDE_TYPE_NAME_PARAMETER, "false")); + Params params = new ToXContent.MapParams(Collections.singletonMap(BaseRestHandler.INCLUDE_TYPE_NAME_PARAMETER, "false")); ImmutableOpenMap.Builder> allMappings = ImmutableOpenMap.builder(); for (Map.Entry indexEntry : response.mappings().entrySet()) { diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/indices/PutIndexTemplateRequestTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/indices/PutIndexTemplateRequestTests.java index 82205dae8c6..f3800ac430e 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/indices/PutIndexTemplateRequestTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/indices/PutIndexTemplateRequestTests.java @@ -92,10 +92,16 @@ public class PutIndexTemplateRequestTests extends AbstractXContentTestCase { +public class ResizeRequestTests extends AbstractRequestTestCase { @Override protected ResizeRequest createClientTestInstance() { - return new ResizeRequest("target", "source") - .setAliases(Arrays.asList(new Alias("target1"), new Alias("target2"))) + return new ResizeRequest("target", "source").setAliases(Arrays.asList(new Alias("target1"), new Alias("target2"))) .setSettings(Settings.builder().put("index.foo", "bar").build()); } @Override - protected org.opensearch.action.admin.indices.shrink.ResizeRequest doParseToServerInstance(XContentParser parser) - throws IOException { - org.opensearch.action.admin.indices.shrink.ResizeRequest req - = new org.opensearch.action.admin.indices.shrink.ResizeRequest("target", "source"); + protected org.opensearch.action.admin.indices.shrink.ResizeRequest doParseToServerInstance(XContentParser parser) throws IOException { + org.opensearch.action.admin.indices.shrink.ResizeRequest req = new org.opensearch.action.admin.indices.shrink.ResizeRequest( + "target", + "source" + ); req.fromXContent(parser); return req; } @Override - protected void assertInstances(org.opensearch.action.admin.indices.shrink.ResizeRequest serverInstance, - ResizeRequest clientTestInstance) { + protected void assertInstances( + org.opensearch.action.admin.indices.shrink.ResizeRequest serverInstance, + ResizeRequest clientTestInstance + ) { assertEquals(serverInstance.getSourceIndex(), clientTestInstance.getSourceIndex()); assertEquals(serverInstance.getTargetIndexRequest().index(), clientTestInstance.getTargetIndex()); assertEquals(serverInstance.getTargetIndexRequest().settings(), clientTestInstance.getSettings()); diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/indices/ResizeResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/indices/ResizeResponseTests.java index 12c2619033f..954efed52d7 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/indices/ResizeResponseTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/indices/ResizeResponseTests.java @@ -38,8 +38,9 @@ import org.opensearch.common.xcontent.XContentType; import java.io.IOException; -public class ResizeResponseTests extends - AbstractResponseTestCase { +public class ResizeResponseTests extends AbstractResponseTestCase< + org.opensearch.action.admin.indices.shrink.ResizeResponse, + ResizeResponse> { @Override protected org.opensearch.action.admin.indices.shrink.ResizeResponse createServerTestInstance(XContentType xContentType) { @@ -53,8 +54,10 @@ public class ResizeResponseTests extends } @Override - protected void assertInstances(org.opensearch.action.admin.indices.shrink.ResizeResponse serverTestInstance, - ResizeResponse clientInstance) { + protected void assertInstances( + org.opensearch.action.admin.indices.shrink.ResizeResponse serverTestInstance, + ResizeResponse clientInstance + ) { assertEquals(serverTestInstance.isAcknowledged(), clientInstance.isAcknowledged()); assertEquals(serverTestInstance.isShardsAcknowledged(), clientInstance.isShardsAcknowledged()); assertEquals(serverTestInstance.index(), clientInstance.index()); diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/indices/rollover/RolloverRequestTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/indices/rollover/RolloverRequestTests.java index 363d3e375b4..9d51c09ba2e 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/indices/rollover/RolloverRequestTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/indices/rollover/RolloverRequestTests.java @@ -45,7 +45,6 @@ import java.util.List; import static org.hamcrest.Matchers.containsInAnyOrder; - public class RolloverRequestTests extends OpenSearchTestCase { public void testConstructorAndFieldAssignments() { // test constructor @@ -62,7 +61,7 @@ public class RolloverRequestTests extends OpenSearchTestCase { MaxAgeCondition maxAgeCondition = new MaxAgeCondition(new TimeValue(10)); MaxSizeCondition maxSizeCondition = new MaxSizeCondition(new ByteSizeValue(2000)); MaxDocsCondition maxDocsCondition = new MaxDocsCondition(10000L); - Condition[] expectedConditions = new Condition[] {maxAgeCondition, maxSizeCondition, maxDocsCondition}; + Condition[] expectedConditions = new Condition[] { maxAgeCondition, maxSizeCondition, maxDocsCondition }; rolloverRequest.addMaxIndexAgeCondition(maxAgeCondition.value()); rolloverRequest.addMaxIndexSizeCondition(maxSizeCondition.value()); rolloverRequest.addMaxIndexDocsCondition(maxDocsCondition.value()); @@ -71,8 +70,7 @@ public class RolloverRequestTests extends OpenSearchTestCase { } public void testValidation() { - IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> - new RolloverRequest(null, null)); + IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> new RolloverRequest(null, null)); assertEquals("The index alias cannot be null!", exception.getMessage()); } } diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/indices/rollover/RolloverResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/indices/rollover/RolloverResponseTests.java index f2b438c890d..7577aa66bfc 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/indices/rollover/RolloverResponseTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/indices/rollover/RolloverResponseTests.java @@ -69,10 +69,8 @@ public class RolloverResponseTests extends OpenSearchTestCase { this::createParser, RolloverResponseTests::createTestInstance, RolloverResponseTests::toXContent, - RolloverResponse::fromXContent) - .supportsUnknownFields(true) - .randomFieldsExcludeFilter(getRandomFieldsExcludeFilter()) - .test(); + RolloverResponse::fromXContent + ).supportsUnknownFields(true).randomFieldsExcludeFilter(getRandomFieldsExcludeFilter()).test(); } private static RolloverResponse createTestInstance() { @@ -96,8 +94,7 @@ public class RolloverResponseTests extends OpenSearchTestCase { } private static void toXContent(RolloverResponse response, XContentBuilder builder) throws IOException { - Params params = new ToXContent.MapParams( - Collections.singletonMap(BaseRestHandler.INCLUDE_TYPE_NAME_PARAMETER, "false")); + Params params = new ToXContent.MapParams(Collections.singletonMap(BaseRestHandler.INCLUDE_TYPE_NAME_PARAMETER, "false")); org.opensearch.action.admin.indices.rollover.RolloverResponse serverResponse = new org.opensearch.action.admin.indices.rollover.RolloverResponse( response.getOldIndex(), diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/tasks/CancelTasksResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/tasks/CancelTasksResponseTests.java index 828742ebe74..102ebb5fcd3 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/tasks/CancelTasksResponseTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/tasks/CancelTasksResponseTests.java @@ -62,7 +62,8 @@ import java.util.stream.Collectors; import static java.util.Collections.emptyMap; import static java.util.Collections.emptySet; -public class CancelTasksResponseTests extends AbstractResponseTestCase { private static String NODE_ID = "node_id"; @@ -74,25 +75,27 @@ public class CancelTasksResponseTests extends AbstractResponseTestCase nodeFailures = new ArrayList<>(); for (int i = 0; i < randomIntBetween(1, 4); i++) { - taskFailures.add(new TaskOperationFailure(randomAlphaOfLength(4), (long) i, - new RuntimeException(randomAlphaOfLength(4)))); + taskFailures.add(new TaskOperationFailure(randomAlphaOfLength(4), (long) i, new RuntimeException(randomAlphaOfLength(4)))); } for (int i = 0; i < randomIntBetween(1, 4); i++) { nodeFailures.add(new OpenSearchException(new RuntimeException(randomAlphaOfLength(10)))); } for (int i = 0; i < 4; i++) { - tasks.add(new org.opensearch.tasks.TaskInfo( - new TaskId(NODE_ID, (long) i), - randomAlphaOfLength(4), - randomAlphaOfLength(4), - randomAlphaOfLength(10), - new FakeTaskStatus(randomAlphaOfLength(4), randomInt()), - randomLongBetween(1, 3), - randomIntBetween(5, 10), - false, - new TaskId("node1", randomLong()), - Collections.singletonMap("x-header-of", "some-value"))); + tasks.add( + new org.opensearch.tasks.TaskInfo( + new TaskId(NODE_ID, (long) i), + randomAlphaOfLength(4), + randomAlphaOfLength(4), + randomAlphaOfLength(10), + new FakeTaskStatus(randomAlphaOfLength(4), randomInt()), + randomLongBetween(1, 3), + randomIntBetween(5, 10), + false, + new TaskId("node1", randomLong()), + Collections.singletonMap("x-header-of", "some-value") + ) + ); } return new ByNodeCancelTasksResponse(tasks, taskFailures, nodeFailures); @@ -104,15 +107,16 @@ public class CancelTasksResponseTests extends AbstractResponseTestCase sTasks = serverTestInstance.getTasks(); List cTasks = clientInstance.getTasks(); - Map cTasksMap = - cTasks.stream().collect(Collectors.toMap(org.opensearch.client.tasks.TaskInfo::getTaskId, - Function.identity())); + Map cTasksMap = cTasks.stream() + .collect(Collectors.toMap(org.opensearch.client.tasks.TaskInfo::getTaskId, Function.identity())); for (TaskInfo ti : sTasks) { org.opensearch.client.tasks.TaskInfo taskInfo = cTasksMap.get( new org.opensearch.client.tasks.TaskId(ti.getTaskId().getNodeId(), ti.getTaskId().getId()) @@ -132,27 +136,23 @@ public class CancelTasksResponseTests extends AbstractResponseTestCase serverNodeFailures = serverTestInstance.getNodeFailures(); List cNodeFailures = clientInstance.getNodeFailures(); - List sExceptionsMessages = serverNodeFailures.stream().map(x -> - org.opensearch.client.tasks.OpenSearchException.buildMessage( - "exception", x.getMessage(), null) - ).collect(Collectors.toList() - ); + List sExceptionsMessages = serverNodeFailures.stream() + .map(x -> org.opensearch.client.tasks.OpenSearchException.buildMessage("exception", x.getMessage(), null)) + .collect(Collectors.toList()); - List cExceptionsMessages = cNodeFailures.stream().map( - org.opensearch.client.tasks.OpenSearchException::getMsg - ).collect(Collectors.toList()); + List cExceptionsMessages = cNodeFailures.stream() + .map(org.opensearch.client.tasks.OpenSearchException::getMsg) + .collect(Collectors.toList()); assertEquals(new HashSet<>(sExceptionsMessages), new HashSet<>(cExceptionsMessages)); List sTaskFailures = serverTestInstance.getTaskFailures(); List cTaskFailures = clientInstance.getTaskFailures(); - Map cTasksFailuresMap = - cTaskFailures.stream().collect(Collectors.toMap( - org.opensearch.client.tasks.TaskOperationFailure::getTaskId, - Function.identity())); + Map cTasksFailuresMap = cTaskFailures.stream() + .collect(Collectors.toMap(org.opensearch.client.tasks.TaskOperationFailure::getTaskId, Function.identity())); for (TaskOperationFailure tof : sTaskFailures) { org.opensearch.client.tasks.TaskOperationFailure failure = cTasksFailuresMap.get(tof.getTaskId()); assertEquals(tof.getNodeId(), failure.getNodeId()); @@ -205,17 +205,17 @@ public class CancelTasksResponseTests extends AbstractResponseTestCase tasks, List taskFailures, - List nodeFailures) { + List nodeFailures + ) { super(tasks, taskFailures, nodeFailures); } - // it knows the hardcoded address space. @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { DiscoveryNodes.Builder dnBuilder = new DiscoveryNodes.Builder(); - InetAddress inetAddress = InetAddress.getByAddress(new byte[]{(byte) 192, (byte) 168, (byte) 0, (byte) 1}); + InetAddress inetAddress = InetAddress.getByAddress(new byte[] { (byte) 192, (byte) 168, (byte) 0, (byte) 1 }); TransportAddress transportAddress = new TransportAddress(inetAddress, randomIntBetween(0, 65535)); dnBuilder.add(new DiscoveryNode(NODE_ID, NODE_ID, transportAddress, emptyMap(), emptySet(), Version.CURRENT)); @@ -228,5 +228,3 @@ public class CancelTasksResponseTests extends AbstractResponseTestCase { @Override @@ -46,8 +47,8 @@ public class OpenSearchExceptionTests extends AbstractResponseTestCase { * @param previousDeadHostState the previous state of the host which allows us to increase the wait till the next retry attempt */ DeadHostState(DeadHostState previousDeadHostState) { - long timeoutNanos = (long)Math.min(MIN_CONNECTION_TIMEOUT_NANOS * 2 * Math.pow(2, previousDeadHostState.failedAttempts * 0.5 - 1), - MAX_CONNECTION_TIMEOUT_NANOS); + long timeoutNanos = (long) Math.min( + MIN_CONNECTION_TIMEOUT_NANOS * 2 * Math.pow(2, previousDeadHostState.failedAttempts * 0.5 - 1), + MAX_CONNECTION_TIMEOUT_NANOS + ); this.deadUntilNanos = previousDeadHostState.timeSupplier.get() + timeoutNanos; this.failedAttempts = previousDeadHostState.failedAttempts + 1; this.timeSupplier = previousDeadHostState.timeSupplier; @@ -102,18 +104,22 @@ final class DeadHostState implements Comparable { @Override public int compareTo(DeadHostState other) { if (timeSupplier != other.timeSupplier) { - throw new IllegalArgumentException("can't compare DeadHostStates holding different time suppliers as they may " + - "be based on different clocks"); + throw new IllegalArgumentException( + "can't compare DeadHostStates holding different time suppliers as they may " + "be based on different clocks" + ); } return Long.compare(deadUntilNanos, other.deadUntilNanos); } @Override public String toString() { - return "DeadHostState{" + - "failedAttempts=" + failedAttempts + - ", deadUntilNanos=" + deadUntilNanos + - ", timeSupplier=" + timeSupplier + - '}'; + return "DeadHostState{" + + "failedAttempts=" + + failedAttempts + + ", deadUntilNanos=" + + deadUntilNanos + + ", timeSupplier=" + + timeSupplier + + '}'; } } diff --git a/client/rest/src/main/java/org/opensearch/client/HasAttributeNodeSelector.java b/client/rest/src/main/java/org/opensearch/client/HasAttributeNodeSelector.java index a2b9bc758a3..e6005c207ec 100644 --- a/client/rest/src/main/java/org/opensearch/client/HasAttributeNodeSelector.java +++ b/client/rest/src/main/java/org/opensearch/client/HasAttributeNodeSelector.java @@ -79,8 +79,7 @@ public final class HasAttributeNodeSelector implements NodeSelector { return false; } HasAttributeNodeSelector that = (HasAttributeNodeSelector) o; - return Objects.equals(key, that.key) && - Objects.equals(value, that.value); + return Objects.equals(key, that.key) && Objects.equals(value, that.value); } @Override diff --git a/client/rest/src/main/java/org/opensearch/client/HeapBufferedAsyncResponseConsumer.java b/client/rest/src/main/java/org/opensearch/client/HeapBufferedAsyncResponseConsumer.java index 618f00b29e7..e2993e48a5a 100644 --- a/client/rest/src/main/java/org/opensearch/client/HeapBufferedAsyncResponseConsumer.java +++ b/client/rest/src/main/java/org/opensearch/client/HeapBufferedAsyncResponseConsumer.java @@ -89,8 +89,9 @@ public class HeapBufferedAsyncResponseConsumer extends AbstractAsyncResponseCons protected void onEntityEnclosed(HttpEntity entity, ContentType contentType) throws IOException { long len = entity.getContentLength(); if (len > bufferLimitBytes) { - throw new ContentTooLongException("entity content is too long [" + len + - "] for the configured buffer limit [" + bufferLimitBytes + "]"); + throw new ContentTooLongException( + "entity content is too long [" + len + "] for the configured buffer limit [" + bufferLimitBytes + "]" + ); } if (len < 0) { len = 4096; diff --git a/client/rest/src/main/java/org/opensearch/client/HttpAsyncResponseConsumerFactory.java b/client/rest/src/main/java/org/opensearch/client/HttpAsyncResponseConsumerFactory.java index df575f5cbd2..7a56e03a116 100644 --- a/client/rest/src/main/java/org/opensearch/client/HttpAsyncResponseConsumerFactory.java +++ b/client/rest/src/main/java/org/opensearch/client/HttpAsyncResponseConsumerFactory.java @@ -61,7 +61,7 @@ public interface HttpAsyncResponseConsumerFactory { */ class HeapBufferedResponseConsumerFactory implements HttpAsyncResponseConsumerFactory { - //default buffer limit is 100MB + // default buffer limit is 100MB static final int DEFAULT_BUFFER_LIMIT = 100 * 1024 * 1024; private final int bufferLimit; diff --git a/client/rest/src/main/java/org/opensearch/client/Node.java b/client/rest/src/main/java/org/opensearch/client/Node.java index b7aabd564ac..41c2926a7d5 100644 --- a/client/rest/src/main/java/org/opensearch/client/Node.java +++ b/client/rest/src/main/java/org/opensearch/client/Node.java @@ -85,8 +85,7 @@ public class Node { * @param roles roles that the OpenSearch process has on the host * @param attributes attributes declared on the node */ - public Node(HttpHost host, Set boundHosts, String name, String version, - Roles roles, Map> attributes) { + public Node(HttpHost host, Set boundHosts, String name, String version, Roles roles, Map> attributes) { if (host == null) { throw new IllegalArgumentException("host cannot be null"); } @@ -216,12 +215,14 @@ public class Node { public boolean isMasterEligible() { return roles.contains("master"); } + /** * Teturns whether or not the node stores data. */ public boolean isData() { return roles.contains("data"); } + /** * Teturns whether or not the node runs ingest pipelines. */ diff --git a/client/rest/src/main/java/org/opensearch/client/NodeSelector.java b/client/rest/src/main/java/org/opensearch/client/NodeSelector.java index 0e11c113be3..398a3a72b94 100644 --- a/client/rest/src/main/java/org/opensearch/client/NodeSelector.java +++ b/client/rest/src/main/java/org/opensearch/client/NodeSelector.java @@ -89,9 +89,7 @@ public interface NodeSelector { for (Iterator itr = nodes.iterator(); itr.hasNext();) { Node node = itr.next(); if (node.getRoles() == null) continue; - if (node.getRoles().isMasterEligible() - && false == node.getRoles().isData() - && false == node.getRoles().isIngest()) { + if (node.getRoles().isMasterEligible() && false == node.getRoles().isData() && false == node.getRoles().isIngest()) { itr.remove(); } } diff --git a/client/rest/src/main/java/org/opensearch/client/PersistentCredentialsAuthenticationStrategy.java b/client/rest/src/main/java/org/opensearch/client/PersistentCredentialsAuthenticationStrategy.java index a602ad694d0..8a35d6eb607 100644 --- a/client/rest/src/main/java/org/opensearch/client/PersistentCredentialsAuthenticationStrategy.java +++ b/client/rest/src/main/java/org/opensearch/client/PersistentCredentialsAuthenticationStrategy.java @@ -63,8 +63,13 @@ final class PersistentCredentialsAuthenticationStrategy extends TargetAuthentica @Override public void authFailed(HttpHost host, AuthScheme authScheme, HttpContext context) { if (logger.isDebugEnabled()) { - logger.debug("Authentication to " + host + " failed (scheme: " + authScheme.getSchemeName() - + "). Preserving credentials for next request"); + logger.debug( + "Authentication to " + + host + + " failed (scheme: " + + authScheme.getSchemeName() + + "). Preserving credentials for next request" + ); } // Do nothing. // The superclass implementation of method will clear the credentials from the cache, but we don't diff --git a/client/rest/src/main/java/org/opensearch/client/PreferHasAttributeNodeSelector.java b/client/rest/src/main/java/org/opensearch/client/PreferHasAttributeNodeSelector.java index 1a8145e8d39..ddec1da068b 100644 --- a/client/rest/src/main/java/org/opensearch/client/PreferHasAttributeNodeSelector.java +++ b/client/rest/src/main/java/org/opensearch/client/PreferHasAttributeNodeSelector.java @@ -108,8 +108,7 @@ public final class PreferHasAttributeNodeSelector implements NodeSelector { return false; } PreferHasAttributeNodeSelector that = (PreferHasAttributeNodeSelector) o; - return Objects.equals(key, that.key) && - Objects.equals(value, that.value); + return Objects.equals(key, that.key) && Objects.equals(value, that.value); } @Override diff --git a/client/rest/src/main/java/org/opensearch/client/Request.java b/client/rest/src/main/java/org/opensearch/client/Request.java index 8116265ea9b..df81ca7f717 100644 --- a/client/rest/src/main/java/org/opensearch/client/Request.java +++ b/client/rest/src/main/java/org/opensearch/client/Request.java @@ -100,7 +100,7 @@ public final class Request { * @param paramSource a map of key value pairs where the key is the url parameter. * @throws IllegalArgumentException if a parameter with that name has already been set. */ - public void addParameters(Map paramSource){ + public void addParameters(Map paramSource) { paramSource.forEach(this::addParameter); } @@ -203,10 +203,10 @@ public final class Request { Request other = (Request) obj; return method.equals(other.method) - && endpoint.equals(other.endpoint) - && parameters.equals(other.parameters) - && Objects.equals(entity, other.entity) - && options.equals(other.options); + && endpoint.equals(other.endpoint) + && parameters.equals(other.parameters) + && Objects.equals(entity, other.entity) + && options.equals(other.options); } @Override diff --git a/client/rest/src/main/java/org/opensearch/client/RequestLogger.java b/client/rest/src/main/java/org/opensearch/client/RequestLogger.java index 921cf7a2a14..297885fa313 100644 --- a/client/rest/src/main/java/org/opensearch/client/RequestLogger.java +++ b/client/rest/src/main/java/org/opensearch/client/RequestLogger.java @@ -61,16 +61,23 @@ final class RequestLogger { private static final Log tracer = LogFactory.getLog("tracer"); - private RequestLogger() { - } + private RequestLogger() {} /** * Logs a request that yielded a response */ static void logResponse(Log logger, HttpUriRequest request, HttpHost host, HttpResponse httpResponse) { if (logger.isDebugEnabled()) { - logger.debug("request [" + request.getMethod() + " " + host + getUri(request.getRequestLine()) + - "] returned [" + httpResponse.getStatusLine() + "]"); + logger.debug( + "request [" + + request.getMethod() + + " " + + host + + getUri(request.getRequestLine()) + + "] returned [" + + httpResponse.getStatusLine() + + "]" + ); } if (logger.isWarnEnabled()) { Header[] warnings = httpResponse.getHeaders("Warning"); @@ -82,14 +89,14 @@ final class RequestLogger { String requestLine; try { requestLine = buildTraceRequest(request, host); - } catch(IOException e) { + } catch (IOException e) { requestLine = ""; tracer.trace("error while reading request for trace purposes", e); } String responseLine; try { responseLine = buildTraceResponse(httpResponse); - } catch(IOException e) { + } catch (IOException e) { responseLine = ""; tracer.trace("error while reading response for trace purposes", e); } @@ -117,8 +124,13 @@ final class RequestLogger { } static String buildWarningMessage(HttpUriRequest request, HttpHost host, Header[] warnings) { - StringBuilder message = new StringBuilder("request [").append(request.getMethod()).append(" ").append(host) - .append(getUri(request.getRequestLine())).append("] returned ").append(warnings.length).append(" warnings: "); + StringBuilder message = new StringBuilder("request [").append(request.getMethod()) + .append(" ") + .append(host) + .append(getUri(request.getRequestLine())) + .append("] returned ") + .append(warnings.length) + .append(" warnings: "); for (int i = 0; i < warnings.length; i++) { if (i > 0) { message.append(","); @@ -133,7 +145,7 @@ final class RequestLogger { */ static String buildTraceRequest(HttpUriRequest request, HttpHost host) throws IOException { String requestLine = "curl -iX " + request.getMethod() + " '" + host + getUri(request.getRequestLine()) + "'"; - if (request instanceof HttpEntityEnclosingRequest) { + if (request instanceof HttpEntityEnclosingRequest) { HttpEntityEnclosingRequest enclosingRequest = (HttpEntityEnclosingRequest) request; if (enclosingRequest.getEntity() != null) { requestLine += " -d '"; @@ -171,7 +183,7 @@ final class RequestLogger { } try (BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), charset))) { String line; - while( (line = reader.readLine()) != null) { + while ((line = reader.readLine()) != null) { responseLine.append("\n# ").append(line); } } diff --git a/client/rest/src/main/java/org/opensearch/client/RequestOptions.java b/client/rest/src/main/java/org/opensearch/client/RequestOptions.java index 0f351b06140..5390e303ff4 100644 --- a/client/rest/src/main/java/org/opensearch/client/RequestOptions.java +++ b/client/rest/src/main/java/org/opensearch/client/RequestOptions.java @@ -52,7 +52,11 @@ public final class RequestOptions { * Default request options. */ public static final RequestOptions DEFAULT = new Builder( - Collections.emptyList(), HeapBufferedResponseConsumerFactory.DEFAULT, null, null).build(); + Collections.emptyList(), + HeapBufferedResponseConsumerFactory.DEFAULT, + null, + null + ).build(); private final List
headers; private final HttpAsyncResponseConsumerFactory httpAsyncResponseConsumerFactory; @@ -159,8 +163,8 @@ public final class RequestOptions { RequestOptions other = (RequestOptions) obj; return headers.equals(other.headers) - && httpAsyncResponseConsumerFactory.equals(other.httpAsyncResponseConsumerFactory) - && Objects.equals(warningsHandler, other.warningsHandler); + && httpAsyncResponseConsumerFactory.equals(other.httpAsyncResponseConsumerFactory) + && Objects.equals(warningsHandler, other.warningsHandler); } @Override @@ -179,8 +183,12 @@ public final class RequestOptions { private WarningsHandler warningsHandler; private RequestConfig requestConfig; - private Builder(List
headers, HttpAsyncResponseConsumerFactory httpAsyncResponseConsumerFactory, - WarningsHandler warningsHandler, RequestConfig requestConfig) { + private Builder( + List
headers, + HttpAsyncResponseConsumerFactory httpAsyncResponseConsumerFactory, + WarningsHandler warningsHandler, + RequestConfig requestConfig + ) { this.headers = new ArrayList<>(headers); this.httpAsyncResponseConsumerFactory = httpAsyncResponseConsumerFactory; this.warningsHandler = warningsHandler; @@ -218,8 +226,10 @@ public final class RequestOptions { * @throws NullPointerException if {@code httpAsyncResponseConsumerFactory} is null. */ public void setHttpAsyncResponseConsumerFactory(HttpAsyncResponseConsumerFactory httpAsyncResponseConsumerFactory) { - this.httpAsyncResponseConsumerFactory = - Objects.requireNonNull(httpAsyncResponseConsumerFactory, "httpAsyncResponseConsumerFactory cannot be null"); + this.httpAsyncResponseConsumerFactory = Objects.requireNonNull( + httpAsyncResponseConsumerFactory, + "httpAsyncResponseConsumerFactory cannot be null" + ); } /** @@ -274,8 +284,7 @@ public final class RequestOptions { } if (other instanceof ReqHeader) { Header otherHeader = (Header) other; - return Objects.equals(getName(), otherHeader.getName()) && - Objects.equals(getValue(), otherHeader.getValue()); + return Objects.equals(getName(), otherHeader.getName()) && Objects.equals(getValue(), otherHeader.getValue()); } return false; } diff --git a/client/rest/src/main/java/org/opensearch/client/Response.java b/client/rest/src/main/java/org/opensearch/client/Response.java index 9d4ae1ae35b..d380607b7df 100644 --- a/client/rest/src/main/java/org/opensearch/client/Response.java +++ b/client/rest/src/main/java/org/opensearch/client/Response.java @@ -120,32 +120,22 @@ public class Response { * format (with quotes and leading space). Start/end of line characters and * atomic groups are used to prevent backtracking. */ - private static final Pattern WARNING_HEADER_DATE_PATTERN = Pattern.compile( - "^ " + // start of line, leading space - // quoted RFC 1123 date format - "\"" + // opening quote - "(?>Mon|Tue|Wed|Thu|Fri|Sat|Sun), " + // day of week, atomic group to prevent backtracking - "\\d{2} " + // 2-digit day - "(?>Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) " + // month, atomic group to prevent backtracking - "\\d{4} " + // 4-digit year - "\\d{2}:\\d{2}:\\d{2} " + // (two-digit hour):(two-digit minute):(two-digit second) - "GMT" + // GMT - "\"$"); // closing quote (optional, since an older version can still send a warn-date), end of line + private static final Pattern WARNING_HEADER_DATE_PATTERN = Pattern.compile("^ " + // start of line, leading space + // quoted RFC 1123 date format + "\"" + // opening quote + "(?>Mon|Tue|Wed|Thu|Fri|Sat|Sun), " + // day of week, atomic group to prevent backtracking + "\\d{2} " + // 2-digit day + "(?>Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) " + // month, atomic group to prevent backtracking + "\\d{4} " + // 4-digit year + "\\d{2}:\\d{2}:\\d{2} " + // (two-digit hour):(two-digit minute):(two-digit second) + "GMT" + // GMT + "\"$"); // closing quote (optional, since an older version can still send a warn-date), end of line /** * Length of RFC 1123 format (with quotes and leading space), used in * matchWarningHeaderPatternByPrefix(String). */ - private static final int WARNING_HEADER_DATE_LENGTH = 0 - + 1 - + 1 - + 3 + 1 + 1 - + 2 + 1 - + 3 + 1 - + 4 + 1 - + 2 + 1 + 2 + 1 + 2 + 1 - + 3 - + 1; + private static final int WARNING_HEADER_DATE_LENGTH = 0 + 1 + 1 + 3 + 1 + 1 + 2 + 1 + 3 + 1 + 4 + 1 + 2 + 1 + 2 + 1 + 2 + 1 + 3 + 1; /** * Tests if a string matches the RFC 7234 specification for warning headers. @@ -215,10 +205,6 @@ public class Response { @Override public String toString() { - return "Response{" + - "requestLine=" + requestLine + - ", host=" + host + - ", response=" + response.getStatusLine() + - '}'; + return "Response{" + "requestLine=" + requestLine + ", host=" + host + ", response=" + response.getStatusLine() + '}'; } } diff --git a/client/rest/src/main/java/org/opensearch/client/ResponseException.java b/client/rest/src/main/java/org/opensearch/client/ResponseException.java index 5892304241f..8104c32c422 100644 --- a/client/rest/src/main/java/org/opensearch/client/ResponseException.java +++ b/client/rest/src/main/java/org/opensearch/client/ResponseException.java @@ -58,7 +58,8 @@ public final class ResponseException extends IOException { } static String buildMessage(Response response) throws IOException { - String message = String.format(Locale.ROOT, + String message = String.format( + Locale.ROOT, "method [%s], host [%s], URI [%s], status line [%s]", response.getRequestLine().getMethod(), response.getHost(), diff --git a/client/rest/src/main/java/org/opensearch/client/RestClient.java b/client/rest/src/main/java/org/opensearch/client/RestClient.java index 9c254f697f0..4e7cb41ca02 100644 --- a/client/rest/src/main/java/org/opensearch/client/RestClient.java +++ b/client/rest/src/main/java/org/opensearch/client/RestClient.java @@ -132,9 +132,16 @@ public class RestClient implements Closeable { private final WarningsHandler warningsHandler; private final boolean compressionEnabled; - RestClient(CloseableHttpAsyncClient client, Header[] defaultHeaders, List nodes, String pathPrefix, - FailureListener failureListener, NodeSelector nodeSelector, boolean strictDeprecationMode, - boolean compressionEnabled) { + RestClient( + CloseableHttpAsyncClient client, + Header[] defaultHeaders, + List nodes, + String pathPrefix, + FailureListener failureListener, + NodeSelector nodeSelector, + boolean strictDeprecationMode, + boolean compressionEnabled + ) { this.client = client; this.defaultHeaders = Collections.unmodifiableList(Arrays.asList(defaultHeaders)); this.failureListener = failureListener; @@ -185,7 +192,7 @@ public class RestClient implements Closeable { port = 443; } - String url = decodedParts[1] + "." + domain; + String url = decodedParts[1] + "." + domain; return builder(new HttpHost(url, port, "https")); } @@ -238,8 +245,7 @@ public class RestClient implements Closeable { nodesByHost.put(node.getHost(), node); authCache.put(node.getHost(), new BasicScheme()); } - this.nodeTuple = new NodeTuple<>( - Collections.unmodifiableList(new ArrayList<>(nodesByHost.values())), authCache); + this.nodeTuple = new NodeTuple<>(Collections.unmodifiableList(new ArrayList<>(nodesByHost.values())), authCache); this.blacklist.clear(); } @@ -289,14 +295,13 @@ public class RestClient implements Closeable { return performRequest(nextNodes(), internalRequest, null); } - private Response performRequest(final NodeTuple> nodeTuple, - final InternalRequest request, - Exception previousException) throws IOException { + private Response performRequest(final NodeTuple> nodeTuple, final InternalRequest request, Exception previousException) + throws IOException { RequestContext context = request.createContextForNextAttempt(nodeTuple.nodes.next(), nodeTuple.authCache); HttpResponse httpResponse; try { httpResponse = client.execute(context.requestProducer, context.asyncResponseConsumer, context.context, null).get(); - } catch(Exception e) { + } catch (Exception e) { RequestLogger.logFailedRequest(logger, request.httpRequest, context.node, e); onFailure(context.node); Exception cause = extractAndWrapCause(e); @@ -344,11 +349,11 @@ public class RestClient implements Closeable { } ResponseException responseException = new ResponseException(response); if (isRetryStatus(statusCode)) { - //mark host dead and retry against next one + // mark host dead and retry against next one onFailure(node); return new ResponseOrResponseException(responseException); } - //mark host alive and don't retry, as the error should be a request problem + // mark host alive and don't retry, as the error should be a request problem onResponse(node); throw responseException; } @@ -381,9 +386,11 @@ public class RestClient implements Closeable { } } - private void performRequestAsync(final NodeTuple> nodeTuple, - final InternalRequest request, - final FailureTrackingResponseListener listener) { + private void performRequestAsync( + final NodeTuple> nodeTuple, + final InternalRequest request, + final FailureTrackingResponseListener listener + ) { request.cancellable.runIfNotCancelled(() -> { final RequestContext context = request.createContextForNextAttempt(nodeTuple.nodes.next(), nodeTuple.authCache); client.execute(context.requestProducer, context.asyncResponseConsumer, context.context, new FutureCallback() { @@ -401,7 +408,7 @@ public class RestClient implements Closeable { listener.onDefinitiveFailure(responseOrResponseException.responseException); } } - } catch(Exception e) { + } catch (Exception e) { listener.onDefinitiveFailure(e); } } @@ -417,7 +424,7 @@ public class RestClient implements Closeable { } else { listener.onDefinitiveFailure(failure); } - } catch(Exception e) { + } catch (Exception e) { listener.onDefinitiveFailure(e); } } @@ -449,8 +456,12 @@ public class RestClient implements Closeable { * Select nodes to try and sorts them so that the first one will be tried initially, then the following ones * if the previous attempt failed and so on. Package private for testing. */ - static Iterable selectNodes(NodeTuple> nodeTuple, Map blacklist, - AtomicInteger lastNodeIndex, NodeSelector nodeSelector) throws IOException { + static Iterable selectNodes( + NodeTuple> nodeTuple, + Map blacklist, + AtomicInteger lastNodeIndex, + NodeSelector nodeSelector + ) throws IOException { /* * Sort the nodes into living and dead lists. */ @@ -505,8 +516,9 @@ public class RestClient implements Closeable { return singletonList(Collections.min(selectedDeadNodes).node); } } - throw new IOException("NodeSelector [" + nodeSelector + "] rejected all nodes, " - + "living " + livingNodes + " and dead " + deadNodes); + throw new IOException( + "NodeSelector [" + nodeSelector + "] rejected all nodes, " + "living " + livingNodes + " and dead " + deadNodes + ); } /** @@ -525,17 +537,18 @@ public class RestClient implements Closeable { * Receives as an argument the host that was used for the failed attempt. */ private void onFailure(Node node) { - while(true) { - DeadHostState previousDeadHostState = - blacklist.putIfAbsent(node.getHost(), new DeadHostState(DeadHostState.DEFAULT_TIME_SUPPLIER)); + while (true) { + DeadHostState previousDeadHostState = blacklist.putIfAbsent( + node.getHost(), + new DeadHostState(DeadHostState.DEFAULT_TIME_SUPPLIER) + ); if (previousDeadHostState == null) { if (logger.isDebugEnabled()) { logger.debug("added [" + node + "] to blacklist"); } break; } - if (blacklist.replace(node.getHost(), previousDeadHostState, - new DeadHostState(previousDeadHostState))) { + if (blacklist.replace(node.getHost(), previousDeadHostState, new DeadHostState(previousDeadHostState))) { if (logger.isDebugEnabled()) { logger.debug("updated [" + node + "] already in blacklist"); } @@ -555,7 +568,7 @@ public class RestClient implements Closeable { } private static boolean isRetryStatus(int statusCode) { - switch(statusCode) { + switch (statusCode) { case 502: case 503: case 504: @@ -571,7 +584,7 @@ public class RestClient implements Closeable { } private static HttpRequestBase createHttpRequest(String method, URI uri, HttpEntity entity, boolean compressionEnabled) { - switch(method.toUpperCase(Locale.ROOT)) { + switch (method.toUpperCase(Locale.ROOT)) { case HttpDeleteWithEntity.METHOD_NAME: return addRequestBody(new HttpDeleteWithEntity(uri), entity, compressionEnabled); case HttpGetWithEntity.METHOD_NAME: @@ -601,7 +614,7 @@ public class RestClient implements Closeable { if (compressionEnabled) { entity = new ContentCompressingEntity(entity); } - ((HttpEntityEnclosingRequestBase)httpRequest).setEntity(entity); + ((HttpEntityEnclosingRequestBase) httpRequest).setEntity(entity); } else { throw new UnsupportedOperationException(httpRequest.getMethod() + " with body is not supported"); } @@ -630,7 +643,7 @@ public class RestClient implements Closeable { uriBuilder.addParameter(param.getKey(), param.getValue()); } return uriBuilder.build(); - } catch(URISyntaxException e) { + } catch (URISyntaxException e) { throw new IllegalArgumentException(e.getMessage(), e); } } @@ -765,7 +778,7 @@ public class RestClient implements Closeable { InternalRequest(Request request) { this.request = request; Map params = new HashMap<>(request.getParameters()); - //ignore is a special parameter supported by the clients, shouldn't be sent to es + // ignore is a special parameter supported by the clients, shouldn't be sent to es String ignoreString = params.remove("ignore"); this.ignoreErrorCodes = getIgnoreErrorCodes(ignoreString, request.getMethod()); URI uri = buildUri(pathPrefix, request.getEndpoint(), params); @@ -773,8 +786,9 @@ public class RestClient implements Closeable { this.cancellable = Cancellable.fromRequest(httpRequest); setHeaders(httpRequest, request.getOptions().getHeaders()); setRequestConfig(httpRequest, request.getOptions().getRequestConfig()); - this.warningsHandler = request.getOptions().getWarningsHandler() == null ? - RestClient.this.warningsHandler : request.getOptions().getWarningsHandler(); + this.warningsHandler = request.getOptions().getWarningsHandler() == null + ? RestClient.this.warningsHandler + : request.getOptions().getWarningsHandler(); } private void setHeaders(HttpRequest httpRequest, Collection
requestHeaders) { @@ -814,10 +828,11 @@ public class RestClient implements Closeable { RequestContext(InternalRequest request, Node node, AuthCache authCache) { this.node = node; - //we stream the request body if the entity allows for it + // we stream the request body if the entity allows for it this.requestProducer = HttpAsyncMethods.create(node.getHost(), request.httpRequest); - this.asyncResponseConsumer = - request.request.getOptions().getHttpAsyncResponseConsumerFactory().createHttpAsyncResponseConsumer(); + this.asyncResponseConsumer = request.request.getOptions() + .getHttpAsyncResponseConsumerFactory() + .createHttpAsyncResponseConsumer(); this.context = HttpClientContext.create(); context.setAuthCache(authCache); } @@ -827,7 +842,7 @@ public class RestClient implements Closeable { Set ignoreErrorCodes; if (ignoreString == null) { if (HttpHead.METHOD_NAME.equals(requestMethod)) { - //404 never causes error if returned for a HEAD request + // 404 never causes error if returned for a HEAD request ignoreErrorCodes = Collections.singleton(404); } else { ignoreErrorCodes = Collections.emptySet(); @@ -836,7 +851,7 @@ public class RestClient implements Closeable { String[] ignoresArray = ignoreString.split(","); ignoreErrorCodes = new HashSet<>(); if (HttpHead.METHOD_NAME.equals(requestMethod)) { - //404 never causes error if returned for a HEAD request + // 404 never causes error if returned for a HEAD request ignoreErrorCodes.add(404); } for (String ignoreCode : ignoresArray) { @@ -874,12 +889,12 @@ public class RestClient implements Closeable { throw new RuntimeException("thread waiting for the response was interrupted", exception); } if (exception instanceof ExecutionException) { - ExecutionException executionException = (ExecutionException)exception; + ExecutionException executionException = (ExecutionException) exception; Throwable t = executionException.getCause() == null ? executionException : executionException.getCause(); if (t instanceof Error) { - throw (Error)t; + throw (Error) t; } - exception = (Exception)t; + exception = (Exception) t; } if (exception instanceof ConnectTimeoutException) { ConnectTimeoutException e = new ConnectTimeoutException(exception.getMessage()); @@ -909,7 +924,7 @@ public class RestClient implements Closeable { if (exception instanceof IOException) { return new IOException(exception.getMessage(), exception); } - if (exception instanceof RuntimeException){ + if (exception instanceof RuntimeException) { return new RuntimeException(exception.getMessage(), exception); } return new RuntimeException("error while performing request", exception); diff --git a/client/rest/src/main/java/org/opensearch/client/RestClientBuilder.java b/client/rest/src/main/java/org/opensearch/client/RestClientBuilder.java index cd6d9b9b75f..0b259c7983c 100644 --- a/client/rest/src/main/java/org/opensearch/client/RestClientBuilder.java +++ b/client/rest/src/main/java/org/opensearch/client/RestClientBuilder.java @@ -246,26 +246,37 @@ public final class RestClientBuilder { failureListener = new RestClient.FailureListener(); } CloseableHttpAsyncClient httpClient = AccessController.doPrivileged( - (PrivilegedAction) this::createHttpClient); - RestClient restClient = new RestClient(httpClient, defaultHeaders, nodes, - pathPrefix, failureListener, nodeSelector, strictDeprecationMode, compressionEnabled); + (PrivilegedAction) this::createHttpClient + ); + RestClient restClient = new RestClient( + httpClient, + defaultHeaders, + nodes, + pathPrefix, + failureListener, + nodeSelector, + strictDeprecationMode, + compressionEnabled + ); httpClient.start(); return restClient; } private CloseableHttpAsyncClient createHttpClient() { - //default timeouts are all infinite + // default timeouts are all infinite RequestConfig.Builder requestConfigBuilder = RequestConfig.custom() - .setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS) - .setSocketTimeout(DEFAULT_SOCKET_TIMEOUT_MILLIS); + .setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS) + .setSocketTimeout(DEFAULT_SOCKET_TIMEOUT_MILLIS); if (requestConfigCallback != null) { requestConfigBuilder = requestConfigCallback.customizeRequestConfig(requestConfigBuilder); } try { - HttpAsyncClientBuilder httpClientBuilder = HttpAsyncClientBuilder.create().setDefaultRequestConfig(requestConfigBuilder.build()) - //default settings for connection pooling may be too constraining - .setMaxConnPerRoute(DEFAULT_MAX_CONN_PER_ROUTE).setMaxConnTotal(DEFAULT_MAX_CONN_TOTAL) + HttpAsyncClientBuilder httpClientBuilder = HttpAsyncClientBuilder.create() + .setDefaultRequestConfig(requestConfigBuilder.build()) + // default settings for connection pooling may be too constraining + .setMaxConnPerRoute(DEFAULT_MAX_CONN_PER_ROUTE) + .setMaxConnTotal(DEFAULT_MAX_CONN_TOTAL) .setSSLContext(SSLContext.getDefault()) .setTargetAuthenticationStrategy(new PersistentCredentialsAuthenticationStrategy()); if (httpClientConfigCallback != null) { diff --git a/client/rest/src/test/java/org/opensearch/client/DeadHostStateTests.java b/client/rest/src/test/java/org/opensearch/client/DeadHostStateTests.java index cafb17d41d4..15d101daf36 100644 --- a/client/rest/src/test/java/org/opensearch/client/DeadHostStateTests.java +++ b/client/rest/src/test/java/org/opensearch/client/DeadHostStateTests.java @@ -32,7 +32,6 @@ package org.opensearch.client; - import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; @@ -47,7 +46,7 @@ import static org.junit.Assert.fail; public class DeadHostStateTests extends RestClientTestCase { - private static long[] EXPECTED_TIMEOUTS_SECONDS = new long[]{60, 84, 120, 169, 240, 339, 480, 678, 960, 1357, 1800}; + private static long[] EXPECTED_TIMEOUTS_SECONDS = new long[] { 60, 84, 120, 169, 240, 339, 480, 678, 960, 1357, 1800 }; public void testInitialDeadHostStateDefaultTimeSupplier() { DeadHostState deadHostState = new DeadHostState(DeadHostState.DEFAULT_TIME_SUPPLIER); @@ -89,12 +88,13 @@ public class DeadHostStateTests extends RestClientTestCase { public void testCompareToDifferingTimeSupplier() { try { - new DeadHostState(DeadHostState.DEFAULT_TIME_SUPPLIER).compareTo( - new DeadHostState(() -> 0L)); + new DeadHostState(DeadHostState.DEFAULT_TIME_SUPPLIER).compareTo(new DeadHostState(() -> 0L)); fail("expected failure"); } catch (IllegalArgumentException e) { - assertEquals("can't compare DeadHostStates holding different time suppliers as they may " + - "be based on different clocks", e.getMessage()); + assertEquals( + "can't compare DeadHostStates holding different time suppliers as they may " + "be based on different clocks", + e.getMessage() + ); } } @@ -126,12 +126,14 @@ public class DeadHostStateTests extends RestClientTestCase { assertThat(TimeUnit.NANOSECONDS.toSeconds(previous.getDeadUntilNanos()), equalTo(expectedTimeoutsSecond)); previous = new DeadHostState(previous); } - //check that from here on the timeout does not increase + // check that from here on the timeout does not increase int iters = randomIntBetween(5, 30); for (int i = 0; i < iters; i++) { DeadHostState deadHostState = new DeadHostState(previous); - assertThat(TimeUnit.NANOSECONDS.toSeconds(deadHostState.getDeadUntilNanos()), - equalTo(EXPECTED_TIMEOUTS_SECONDS[EXPECTED_TIMEOUTS_SECONDS.length - 1])); + assertThat( + TimeUnit.NANOSECONDS.toSeconds(deadHostState.getDeadUntilNanos()), + equalTo(EXPECTED_TIMEOUTS_SECONDS[EXPECTED_TIMEOUTS_SECONDS.length - 1]) + ); previous = deadHostState; } } diff --git a/client/rest/src/test/java/org/opensearch/client/FailureTrackingResponseListenerTests.java b/client/rest/src/test/java/org/opensearch/client/FailureTrackingResponseListenerTests.java index 12fc8150484..0a997a586ac 100644 --- a/client/rest/src/test/java/org/opensearch/client/FailureTrackingResponseListenerTests.java +++ b/client/rest/src/test/java/org/opensearch/client/FailureTrackingResponseListenerTests.java @@ -91,7 +91,7 @@ public class FailureTrackingResponseListenerTests extends RestClientTestCase { assertEquals(1, exception.getSuppressed().length); assertSame(expectedExceptions[i--], exception.getSuppressed()[0]); exception = exception.getSuppressed()[0]; - } while(i >= 0); + } while (i >= 0); } } diff --git a/client/rest/src/test/java/org/opensearch/client/HasAttributeNodeSelectorTests.java b/client/rest/src/test/java/org/opensearch/client/HasAttributeNodeSelectorTests.java index 9bda646ff94..fd18bba6ee5 100644 --- a/client/rest/src/test/java/org/opensearch/client/HasAttributeNodeSelectorTests.java +++ b/client/rest/src/test/java/org/opensearch/client/HasAttributeNodeSelectorTests.java @@ -76,9 +76,13 @@ public class HasAttributeNodeSelectorTests extends RestClientTestCase { if (randomBoolean()) { roles.add("ingest"); } - return new Node(new HttpHost("dummy"), Collections.emptySet(), - randomAsciiAlphanumOfLength(5), randomAsciiAlphanumOfLength(5), - new Roles(roles), - attributes); + return new Node( + new HttpHost("dummy"), + Collections.emptySet(), + randomAsciiAlphanumOfLength(5), + randomAsciiAlphanumOfLength(5), + new Roles(roles), + attributes + ); } } diff --git a/client/rest/src/test/java/org/opensearch/client/HeapBufferedAsyncResponseConsumerTests.java b/client/rest/src/test/java/org/opensearch/client/HeapBufferedAsyncResponseConsumerTests.java index 75229cbb5cc..22852fe4cb7 100644 --- a/client/rest/src/test/java/org/opensearch/client/HeapBufferedAsyncResponseConsumerTests.java +++ b/client/rest/src/test/java/org/opensearch/client/HeapBufferedAsyncResponseConsumerTests.java @@ -63,7 +63,7 @@ import static org.mockito.Mockito.verify; public class HeapBufferedAsyncResponseConsumerTests extends RestClientTestCase { - //maximum buffer that this test ends up allocating is 50MB + // maximum buffer that this test ends up allocating is 50MB private static final int MAX_TEST_BUFFER_SIZE = 50 * 1024 * 1024; private static final int TEST_BUFFER_LIMIT = 10 * 1024 * 1024; @@ -79,7 +79,7 @@ public class HeapBufferedAsyncResponseConsumerTests extends RestClientTestCase { HttpResponse httpResponse = new BasicHttpResponse(statusLine); httpResponse.setEntity(new StringEntity("test", ContentType.TEXT_PLAIN)); - //everything goes well + // everything goes well consumer.responseReceived(httpResponse); consumer.consumeContent(contentDecoder, ioControl); consumer.responseCompleted(httpContext); @@ -102,12 +102,12 @@ public class HeapBufferedAsyncResponseConsumerTests extends RestClientTestCase { public void testConfiguredBufferLimit() throws Exception { try { new HeapBufferedAsyncResponseConsumer(randomIntBetween(Integer.MIN_VALUE, 0)); - } catch(IllegalArgumentException e) { + } catch (IllegalArgumentException e) { assertEquals("bufferLimit must be greater than 0", e.getMessage()); } try { new HeapBufferedAsyncResponseConsumer(0); - } catch(IllegalArgumentException e) { + } catch (IllegalArgumentException e) { assertEquals("bufferLimit must be greater than 0", e.getMessage()); } int bufferLimit = randomIntBetween(1, MAX_TEST_BUFFER_SIZE - 100); @@ -116,16 +116,17 @@ public class HeapBufferedAsyncResponseConsumerTests extends RestClientTestCase { } public void testCanConfigureHeapBufferLimitFromOutsidePackage() throws ClassNotFoundException, NoSuchMethodException, - IllegalAccessException, InvocationTargetException, InstantiationException { + IllegalAccessException, InvocationTargetException, InstantiationException { int bufferLimit = randomIntBetween(1, Integer.MAX_VALUE); - //we use reflection to make sure that the class can be instantiated from the outside, and the constructor is public - Constructor constructor = - HttpAsyncResponseConsumerFactory.HeapBufferedResponseConsumerFactory.class.getConstructor(Integer.TYPE); + // we use reflection to make sure that the class can be instantiated from the outside, and the constructor is public + Constructor constructor = HttpAsyncResponseConsumerFactory.HeapBufferedResponseConsumerFactory.class.getConstructor( + Integer.TYPE + ); assertEquals(Modifier.PUBLIC, constructor.getModifiers() & Modifier.PUBLIC); Object object = constructor.newInstance(bufferLimit); assertThat(object, instanceOf(HttpAsyncResponseConsumerFactory.HeapBufferedResponseConsumerFactory.class)); HttpAsyncResponseConsumerFactory.HeapBufferedResponseConsumerFactory consumerFactory = - (HttpAsyncResponseConsumerFactory.HeapBufferedResponseConsumerFactory) object; + (HttpAsyncResponseConsumerFactory.HeapBufferedResponseConsumerFactory) object; HttpAsyncResponseConsumer consumer = consumerFactory.createHttpAsyncResponseConsumer(); assertThat(consumer, instanceOf(HeapBufferedAsyncResponseConsumer.class)); HeapBufferedAsyncResponseConsumer bufferedAsyncResponseConsumer = (HeapBufferedAsyncResponseConsumer) consumer; @@ -154,9 +155,11 @@ public class HeapBufferedAsyncResponseConsumerTests extends RestClientTestCase { contentLength.set(randomLongBetween(bufferLimit + 1, MAX_TEST_BUFFER_SIZE)); try { consumer.onEntityEnclosed(entity, ContentType.APPLICATION_JSON); - } catch(ContentTooLongException e) { - assertEquals("entity content is too long [" + entity.getContentLength() + - "] for the configured buffer limit [" + bufferLimit + "]", e.getMessage()); + } catch (ContentTooLongException e) { + assertEquals( + "entity content is too long [" + entity.getContentLength() + "] for the configured buffer limit [" + bufferLimit + "]", + e.getMessage() + ); } } } diff --git a/client/rest/src/test/java/org/opensearch/client/HostsTrackingFailureListener.java b/client/rest/src/test/java/org/opensearch/client/HostsTrackingFailureListener.java index f81308e77f3..2b256e72053 100644 --- a/client/rest/src/test/java/org/opensearch/client/HostsTrackingFailureListener.java +++ b/client/rest/src/test/java/org/opensearch/client/HostsTrackingFailureListener.java @@ -55,7 +55,7 @@ class HostsTrackingFailureListener extends RestClient.FailureListener { void assertCalled(List nodes) { HttpHost[] hosts = new HttpHost[nodes.size()]; - for (int i = 0 ; i < nodes.size(); i++) { + for (int i = 0; i < nodes.size(); i++) { hosts[i] = nodes.get(i).getHost(); } assertCalled(hosts); diff --git a/client/rest/src/test/java/org/opensearch/client/NodeSelectorTests.java b/client/rest/src/test/java/org/opensearch/client/NodeSelectorTests.java index 6807779ef0a..f7cb0733bb8 100644 --- a/client/rest/src/test/java/org/opensearch/client/NodeSelectorTests.java +++ b/client/rest/src/test/java/org/opensearch/client/NodeSelectorTests.java @@ -89,9 +89,13 @@ public class NodeSelectorTests extends RestClientTestCase { if (ingest) { roles.add("ingest"); } - return new Node(new HttpHost("dummy"), Collections.emptySet(), - randomAsciiAlphanumOfLength(5), randomAsciiAlphanumOfLength(5), - new Roles(roles), - Collections.>emptyMap()); + return new Node( + new HttpHost("dummy"), + Collections.emptySet(), + randomAsciiAlphanumOfLength(5), + randomAsciiAlphanumOfLength(5), + new Roles(roles), + Collections.>emptyMap() + ); } } diff --git a/client/rest/src/test/java/org/opensearch/client/NodeTests.java b/client/rest/src/test/java/org/opensearch/client/NodeTests.java index 76da3969278..352296fa302 100644 --- a/client/rest/src/test/java/org/opensearch/client/NodeTests.java +++ b/client/rest/src/test/java/org/opensearch/client/NodeTests.java @@ -56,49 +56,109 @@ public class NodeTests extends RestClientTestCase { attributes.put("foo", singletonList("bar")); attributes.put("baz", Arrays.asList("bort", "zoom")); assertEquals("[host=http://1]", new Node(new HttpHost("1")).toString()); - assertEquals("[host=http://1, attributes={foo=[bar], baz=[bort, zoom]}]", - new Node(new HttpHost("1"), null, null, null, null, attributes).toString()); - assertEquals("[host=http://1, roles=data,ingest,master]", new Node(new HttpHost("1"), - null, null, null, new Roles(new TreeSet<>(Arrays.asList("master", "data", "ingest"))), null).toString()); - assertEquals("[host=http://1, version=ver]", new Node(new HttpHost("1"), - null, null, "ver", null, null).toString()); - assertEquals("[host=http://1, name=nam]", new Node(new HttpHost("1"), - null, "nam", null, null, null).toString()); - assertEquals("[host=http://1, bound=[http://1, http://2]]", new Node(new HttpHost("1"), - new HashSet<>(Arrays.asList(new HttpHost("1"), new HttpHost("2"))), null, null, null, null).toString()); assertEquals( - "[host=http://1, bound=[http://1, http://2], " - + "name=nam, version=ver, roles=master, attributes={foo=[bar], baz=[bort, zoom]}]", - new Node(new HttpHost("1"), new HashSet<>(Arrays.asList(new HttpHost("1"), new HttpHost("2"))), - "nam", "ver", new Roles(Collections.singleton("master")), attributes).toString()); + "[host=http://1, attributes={foo=[bar], baz=[bort, zoom]}]", + new Node(new HttpHost("1"), null, null, null, null, attributes).toString() + ); + assertEquals( + "[host=http://1, roles=data,ingest,master]", + new Node(new HttpHost("1"), null, null, null, new Roles(new TreeSet<>(Arrays.asList("master", "data", "ingest"))), null) + .toString() + ); + assertEquals("[host=http://1, version=ver]", new Node(new HttpHost("1"), null, null, "ver", null, null).toString()); + assertEquals("[host=http://1, name=nam]", new Node(new HttpHost("1"), null, "nam", null, null, null).toString()); + assertEquals( + "[host=http://1, bound=[http://1, http://2]]", + new Node(new HttpHost("1"), new HashSet<>(Arrays.asList(new HttpHost("1"), new HttpHost("2"))), null, null, null, null) + .toString() + ); + assertEquals( + "[host=http://1, bound=[http://1, http://2], " + + "name=nam, version=ver, roles=master, attributes={foo=[bar], baz=[bort, zoom]}]", + new Node( + new HttpHost("1"), + new HashSet<>(Arrays.asList(new HttpHost("1"), new HttpHost("2"))), + "nam", + "ver", + new Roles(Collections.singleton("master")), + attributes + ).toString() + ); } public void testEqualsAndHashCode() { HttpHost host = new HttpHost(randomAsciiAlphanumOfLength(5)); - Node node = new Node(host, - randomBoolean() ? null : singleton(host), - randomBoolean() ? null : randomAsciiAlphanumOfLength(5), - randomBoolean() ? null : randomAsciiAlphanumOfLength(5), - randomBoolean() ? null : new Roles(new TreeSet<>(Arrays.asList("master", "data", "ingest"))), - randomBoolean() ? null : singletonMap("foo", singletonList("bar"))); + Node node = new Node( + host, + randomBoolean() ? null : singleton(host), + randomBoolean() ? null : randomAsciiAlphanumOfLength(5), + randomBoolean() ? null : randomAsciiAlphanumOfLength(5), + randomBoolean() ? null : new Roles(new TreeSet<>(Arrays.asList("master", "data", "ingest"))), + randomBoolean() ? null : singletonMap("foo", singletonList("bar")) + ); assertFalse(node.equals(null)); assertTrue(node.equals(node)); assertEquals(node.hashCode(), node.hashCode()); - Node copy = new Node(host, node.getBoundHosts(), node.getName(), node.getVersion(), - node.getRoles(), node.getAttributes()); + Node copy = new Node(host, node.getBoundHosts(), node.getName(), node.getVersion(), node.getRoles(), node.getAttributes()); assertTrue(node.equals(copy)); assertEquals(node.hashCode(), copy.hashCode()); - assertFalse(node.equals(new Node(new HttpHost(host.toHostString() + "changed"), node.getBoundHosts(), - node.getName(), node.getVersion(), node.getRoles(), node.getAttributes()))); - assertFalse(node.equals(new Node(host, new HashSet<>(Arrays.asList(host, new HttpHost(host.toHostString() + "changed"))), - node.getName(), node.getVersion(), node.getRoles(), node.getAttributes()))); - assertFalse(node.equals(new Node(host, node.getBoundHosts(), node.getName() + "changed", - node.getVersion(), node.getRoles(), node.getAttributes()))); - assertFalse(node.equals(new Node(host, node.getBoundHosts(), node.getName(), - node.getVersion() + "changed", node.getRoles(), node.getAttributes()))); - assertFalse(node.equals(new Node(host, node.getBoundHosts(), node.getName(), - node.getVersion(), new Roles(Collections.emptySet()), node.getAttributes()))); - assertFalse(node.equals(new Node(host, node.getBoundHosts(), node.getName(), - node.getVersion(), node.getRoles(), singletonMap("bort", singletonList("bing"))))); + assertFalse( + node.equals( + new Node( + new HttpHost(host.toHostString() + "changed"), + node.getBoundHosts(), + node.getName(), + node.getVersion(), + node.getRoles(), + node.getAttributes() + ) + ) + ); + assertFalse( + node.equals( + new Node( + host, + new HashSet<>(Arrays.asList(host, new HttpHost(host.toHostString() + "changed"))), + node.getName(), + node.getVersion(), + node.getRoles(), + node.getAttributes() + ) + ) + ); + assertFalse( + node.equals( + new Node(host, node.getBoundHosts(), node.getName() + "changed", node.getVersion(), node.getRoles(), node.getAttributes()) + ) + ); + assertFalse( + node.equals( + new Node(host, node.getBoundHosts(), node.getName(), node.getVersion() + "changed", node.getRoles(), node.getAttributes()) + ) + ); + assertFalse( + node.equals( + new Node( + host, + node.getBoundHosts(), + node.getName(), + node.getVersion(), + new Roles(Collections.emptySet()), + node.getAttributes() + ) + ) + ); + assertFalse( + node.equals( + new Node( + host, + node.getBoundHosts(), + node.getName(), + node.getVersion(), + node.getRoles(), + singletonMap("bort", singletonList("bing")) + ) + ) + ); } } diff --git a/client/rest/src/test/java/org/opensearch/client/PreferHasAttributeNodeSelectorTests.java b/client/rest/src/test/java/org/opensearch/client/PreferHasAttributeNodeSelectorTests.java index fcf573f7dd5..0135cde5737 100644 --- a/client/rest/src/test/java/org/opensearch/client/PreferHasAttributeNodeSelectorTests.java +++ b/client/rest/src/test/java/org/opensearch/client/PreferHasAttributeNodeSelectorTests.java @@ -86,9 +86,13 @@ public class PreferHasAttributeNodeSelectorTests extends RestClientTestCase { if (randomBoolean()) { roles.add("ingest"); } - return new Node(new HttpHost("dummy"), Collections.emptySet(), - randomAsciiAlphanumOfLength(5), randomAsciiAlphanumOfLength(5), + return new Node( + new HttpHost("dummy"), + Collections.emptySet(), + randomAsciiAlphanumOfLength(5), + randomAsciiAlphanumOfLength(5), new Roles(roles), - attributes); + attributes + ); } } diff --git a/client/rest/src/test/java/org/opensearch/client/RequestLoggerTests.java b/client/rest/src/test/java/org/opensearch/client/RequestLoggerTests.java index ed4867d2ea9..3c317db1b72 100644 --- a/client/rest/src/test/java/org/opensearch/client/RequestLoggerTests.java +++ b/client/rest/src/test/java/org/opensearch/client/RequestLoggerTests.java @@ -83,13 +83,15 @@ public class RequestLoggerTests extends RestClientTestCase { expected += " -d '" + requestBody + "'"; HttpEntityEnclosingRequest enclosingRequest = (HttpEntityEnclosingRequest) request; HttpEntity entity; - switch(randomIntBetween(0, 4)) { + switch (randomIntBetween(0, 4)) { case 0: entity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); break; case 1: - entity = new InputStreamEntity(new ByteArrayInputStream(requestBody.getBytes(StandardCharsets.UTF_8)), - ContentType.APPLICATION_JSON); + entity = new InputStreamEntity( + new ByteArrayInputStream(requestBody.getBytes(StandardCharsets.UTF_8)), + ContentType.APPLICATION_JSON + ); break; case 2: entity = new NStringEntity(requestBody, ContentType.APPLICATION_JSON); @@ -109,7 +111,7 @@ public class RequestLoggerTests extends RestClientTestCase { String traceRequest = RequestLogger.buildTraceRequest(request, host); assertThat(traceRequest, equalTo(expected)); if (hasBody) { - //check that the body is still readable as most entities are not repeatable + // check that the body is still readable as most entities are not repeatable String body = EntityUtils.toString(((HttpEntityEnclosingRequest) request).getEntity(), StandardCharsets.UTF_8); assertThat(body, equalTo(requestBody)); } @@ -135,28 +137,30 @@ public class RequestLoggerTests extends RestClientTestCase { expected += "\n# \"field\": \"value\""; expected += "\n# }"; HttpEntity entity; - switch(randomIntBetween(0, 2)) { - case 0: - entity = new StringEntity(responseBody, ContentType.APPLICATION_JSON); - break; - case 1: - //test a non repeatable entity - entity = new InputStreamEntity(new ByteArrayInputStream(responseBody.getBytes(StandardCharsets.UTF_8)), - ContentType.APPLICATION_JSON); - break; - case 2: - // Evil entity without a charset - entity = new StringEntity(responseBody, ContentType.create("application/json", (Charset) null)); - break; - default: - throw new UnsupportedOperationException(); + switch (randomIntBetween(0, 2)) { + case 0: + entity = new StringEntity(responseBody, ContentType.APPLICATION_JSON); + break; + case 1: + // test a non repeatable entity + entity = new InputStreamEntity( + new ByteArrayInputStream(responseBody.getBytes(StandardCharsets.UTF_8)), + ContentType.APPLICATION_JSON + ); + break; + case 2: + // Evil entity without a charset + entity = new StringEntity(responseBody, ContentType.create("application/json", (Charset) null)); + break; + default: + throw new UnsupportedOperationException(); } httpResponse.setEntity(entity); } String traceResponse = RequestLogger.buildTraceResponse(httpResponse); assertThat(traceResponse, equalTo(expected)); if (hasBody) { - //check that the body is still readable as most entities are not repeatable + // check that the body is still readable as most entities are not repeatable String body = EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8); assertThat(body, equalTo(responseBody)); } @@ -166,8 +170,12 @@ public class RequestLoggerTests extends RestClientTestCase { HttpHost host = new HttpHost("localhost", 9200); HttpUriRequest request = randomHttpRequest(new URI("/index/type/_api")); int numWarnings = randomIntBetween(1, 5); - StringBuilder expected = new StringBuilder("request [").append(request.getMethod()).append(" ").append(host) - .append("/index/type/_api] returned ").append(numWarnings).append(" warnings: "); + StringBuilder expected = new StringBuilder("request [").append(request.getMethod()) + .append(" ") + .append(host) + .append("/index/type/_api] returned ") + .append(numWarnings) + .append(" warnings: "); Header[] warnings = new Header[numWarnings]; for (int i = 0; i < numWarnings; i++) { String warning = "this is warning number " + i; @@ -182,7 +190,7 @@ public class RequestLoggerTests extends RestClientTestCase { private static HttpUriRequest randomHttpRequest(URI uri) { int requestType = randomIntBetween(0, 7); - switch(requestType) { + switch (requestType) { case 0: return new HttpGetWithEntity(uri); case 1: diff --git a/client/rest/src/test/java/org/opensearch/client/RequestOptionsTests.java b/client/rest/src/test/java/org/opensearch/client/RequestOptionsTests.java index a0b397b1e9d..aaa40db1442 100644 --- a/client/rest/src/test/java/org/opensearch/client/RequestOptionsTests.java +++ b/client/rest/src/test/java/org/opensearch/client/RequestOptionsTests.java @@ -81,8 +81,8 @@ public class RequestOptionsTests extends RestClientTestCase { assertEquals(headers, options.getHeaders()); try { - options.getHeaders().add( - new RequestOptions.ReqHeader(randomAsciiAlphanumOfLengthBetween(5, 10), randomAsciiAlphanumOfLength(3))); + options.getHeaders() + .add(new RequestOptions.ReqHeader(randomAsciiAlphanumOfLengthBetween(5, 10), randomAsciiAlphanumOfLength(3))); fail("expected failure"); } catch (UnsupportedOperationException e) { assertNull(e.getMessage()); @@ -167,23 +167,23 @@ public class RequestOptionsTests extends RestClientTestCase { RequestOptions.Builder mutant = options.toBuilder(); int mutationType = between(0, 2); switch (mutationType) { - case 0: - mutant.addHeader("extra", "m"); - return mutant.build(); - case 1: - mutant.setHttpAsyncResponseConsumerFactory(new HeapBufferedResponseConsumerFactory(5)); - return mutant.build(); - case 2: - mutant.setWarningsHandler(new WarningsHandler() { - @Override - public boolean warningsShouldFailRequest(List warnings) { - fail("never called"); - return false; - } - }); - return mutant.build(); - default: - throw new UnsupportedOperationException("Unknown mutation type [" + mutationType + "]"); + case 0: + mutant.addHeader("extra", "m"); + return mutant.build(); + case 1: + mutant.setHttpAsyncResponseConsumerFactory(new HeapBufferedResponseConsumerFactory(5)); + return mutant.build(); + case 2: + mutant.setWarningsHandler(new WarningsHandler() { + @Override + public boolean warningsShouldFailRequest(List warnings) { + fail("never called"); + return false; + } + }); + return mutant.build(); + default: + throw new UnsupportedOperationException("Unknown mutation type [" + mutationType + "]"); } } } diff --git a/client/rest/src/test/java/org/opensearch/client/RequestTests.java b/client/rest/src/test/java/org/opensearch/client/RequestTests.java index 097fa422283..ba15c0d0b73 100644 --- a/client/rest/src/test/java/org/opensearch/client/RequestTests.java +++ b/client/rest/src/test/java/org/opensearch/client/RequestTests.java @@ -52,7 +52,7 @@ import static org.junit.Assert.fail; public class RequestTests extends RestClientTestCase { public void testConstructor() { - final String method = randomFrom(new String[] {"GET", "PUT", "POST", "HEAD", "DELETE"}); + final String method = randomFrom(new String[] { "GET", "PUT", "POST", "HEAD", "DELETE" }); final String endpoint = randomAsciiLettersOfLengthBetween(1, 10); try { @@ -75,7 +75,7 @@ public class RequestTests extends RestClientTestCase { } public void testAddParameters() { - final String method = randomFrom(new String[] {"GET", "PUT", "POST", "HEAD", "DELETE"}); + final String method = randomFrom(new String[] { "GET", "PUT", "POST", "HEAD", "DELETE" }); final String endpoint = randomAsciiLettersOfLengthBetween(1, 10); int parametersCount = between(1, 3); final Map parameters = new HashMap<>(parametersCount); @@ -113,10 +113,11 @@ public class RequestTests extends RestClientTestCase { } public void testSetEntity() { - final String method = randomFrom(new String[] {"GET", "PUT", "POST", "HEAD", "DELETE"}); + final String method = randomFrom(new String[] { "GET", "PUT", "POST", "HEAD", "DELETE" }); final String endpoint = randomAsciiLettersOfLengthBetween(1, 10); - final HttpEntity entity = - randomBoolean() ? new StringEntity(randomAsciiLettersOfLengthBetween(1, 100), ContentType.TEXT_PLAIN) : null; + final HttpEntity entity = randomBoolean() + ? new StringEntity(randomAsciiLettersOfLengthBetween(1, 100), ContentType.TEXT_PLAIN) + : null; Request request = new Request(method, endpoint); request.setEntity(entity); @@ -124,7 +125,7 @@ public class RequestTests extends RestClientTestCase { } public void testSetJsonEntity() throws IOException { - final String method = randomFrom(new String[] {"GET", "PUT", "POST", "HEAD", "DELETE"}); + final String method = randomFrom(new String[] { "GET", "PUT", "POST", "HEAD", "DELETE" }); final String endpoint = randomAsciiLettersOfLengthBetween(1, 10); Request request = new Request(method, endpoint); @@ -139,7 +140,7 @@ public class RequestTests extends RestClientTestCase { } public void testSetOptions() { - final String method = randomFrom(new String[] {"GET", "PUT", "POST", "HEAD", "DELETE"}); + final String method = randomFrom(new String[] { "GET", "PUT", "POST", "HEAD", "DELETE" }); final String endpoint = randomAsciiLettersOfLengthBetween(1, 10); Request request = new Request(method, endpoint); @@ -183,8 +184,9 @@ public class RequestTests extends RestClientTestCase { private static Request randomRequest() { Request request = new Request( - randomFrom(new String[] {"GET", "PUT", "DELETE", "POST", "HEAD", "OPTIONS"}), - randomAsciiAlphanumOfLength(5)); + randomFrom(new String[] { "GET", "PUT", "DELETE", "POST", "HEAD", "OPTIONS" }), + randomAsciiAlphanumOfLength(5) + ); int parameterCount = between(0, 5); for (int i = 0; i < parameterCount; i++) { @@ -195,11 +197,14 @@ public class RequestTests extends RestClientTestCase { if (randomBoolean()) { request.setJsonEntity(randomAsciiAlphanumOfLength(10)); } else { - request.setEntity(randomFrom(new HttpEntity[] { - new StringEntity(randomAsciiAlphanumOfLength(10), ContentType.APPLICATION_JSON), - new NStringEntity(randomAsciiAlphanumOfLength(10), ContentType.APPLICATION_JSON), - new ByteArrayEntity(randomBytesOfLength(40), ContentType.APPLICATION_JSON) - })); + request.setEntity( + randomFrom( + new HttpEntity[] { + new StringEntity(randomAsciiAlphanumOfLength(10), ContentType.APPLICATION_JSON), + new NStringEntity(randomAsciiAlphanumOfLength(10), ContentType.APPLICATION_JSON), + new ByteArrayEntity(randomBytesOfLength(40), ContentType.APPLICATION_JSON) } + ) + ); } } @@ -230,19 +235,19 @@ public class RequestTests extends RestClientTestCase { Request mutant = copy(request); int mutationType = between(0, 2); switch (mutationType) { - case 0: - mutant.addParameter(randomAsciiAlphanumOfLength(mutant.getParameters().size() + 4), "extra"); - return mutant; - case 1: - mutant.setJsonEntity("mutant"); // randomRequest can't produce this value - return mutant; - case 2: - RequestOptions.Builder options = mutant.getOptions().toBuilder(); - options.addHeader("extra", "m"); - mutant.setOptions(options); - return mutant; - default: - throw new UnsupportedOperationException("Unknown mutation type [" + mutationType + "]"); + case 0: + mutant.addParameter(randomAsciiAlphanumOfLength(mutant.getParameters().size() + 4), "extra"); + return mutant; + case 1: + mutant.setJsonEntity("mutant"); // randomRequest can't produce this value + return mutant; + case 2: + RequestOptions.Builder options = mutant.getOptions().toBuilder(); + options.addHeader("extra", "m"); + mutant.setOptions(options); + return mutant; + default: + throw new UnsupportedOperationException("Unknown mutation type [" + mutationType + "]"); } } diff --git a/client/rest/src/test/java/org/opensearch/client/ResponseExceptionTests.java b/client/rest/src/test/java/org/opensearch/client/ResponseExceptionTests.java index 8bd36908b40..8ecd3e1a29c 100644 --- a/client/rest/src/test/java/org/opensearch/client/ResponseExceptionTests.java +++ b/client/rest/src/test/java/org/opensearch/client/ResponseExceptionTests.java @@ -69,9 +69,11 @@ public class ResponseExceptionTests extends RestClientTestCase { if (getRandom().nextBoolean()) { entity = new StringEntity(responseBody, ContentType.APPLICATION_JSON); } else { - //test a non repeatable entity - entity = new InputStreamEntity(new ByteArrayInputStream(responseBody.getBytes(StandardCharsets.UTF_8)), - ContentType.APPLICATION_JSON); + // test a non repeatable entity + entity = new InputStreamEntity( + new ByteArrayInputStream(responseBody.getBytes(StandardCharsets.UTF_8)), + ContentType.APPLICATION_JSON + ); } httpResponse.setEntity(entity); } @@ -88,7 +90,8 @@ public class ResponseExceptionTests extends RestClientTestCase { assertNull(responseException.getResponse().getEntity()); } - String message = String.format(Locale.ROOT, + String message = String.format( + Locale.ROOT, "method [%s], host [%s], URI [%s], status line [%s]", response.getRequestLine().getMethod(), response.getHost(), diff --git a/client/rest/src/test/java/org/opensearch/client/RestClientBuilderIntegTests.java b/client/rest/src/test/java/org/opensearch/client/RestClientBuilderIntegTests.java index 421536be795..10bf9568c87 100644 --- a/client/rest/src/test/java/org/opensearch/client/RestClientBuilderIntegTests.java +++ b/client/rest/src/test/java/org/opensearch/client/RestClientBuilderIntegTests.java @@ -122,18 +122,25 @@ public class RestClientBuilderIntegTests extends RestClientTestCase { private static SSLContext getSslContext() throws Exception { SSLContext sslContext = SSLContext.getInstance(getProtocol()); - try (InputStream certFile = RestClientBuilderIntegTests.class.getResourceAsStream("/test.crt"); - InputStream keyStoreFile = RestClientBuilderIntegTests.class.getResourceAsStream("/test_truststore.jks")) { + try ( + InputStream certFile = RestClientBuilderIntegTests.class.getResourceAsStream("/test.crt"); + InputStream keyStoreFile = RestClientBuilderIntegTests.class.getResourceAsStream("/test_truststore.jks") + ) { // Build a keystore of default type programmatically since we can't use JKS keystores to // init a KeyManagerFactory in FIPS 140 JVMs. KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, "password".toCharArray()); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); - PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(Files.readAllBytes(Paths.get(RestClientBuilderIntegTests.class - .getResource("/test.der").toURI()))); + PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec( + Files.readAllBytes(Paths.get(RestClientBuilderIntegTests.class.getResource("/test.der").toURI())) + ); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); - keyStore.setKeyEntry("mykey", keyFactory.generatePrivate(privateKeySpec), "password".toCharArray(), - new Certificate[]{certFactory.generateCertificate(certFile)}); + keyStore.setKeyEntry( + "mykey", + keyFactory.generatePrivate(privateKeySpec), + "password".toCharArray(), + new Certificate[] { certFactory.generateCertificate(certFile) } + ); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keyStore, "password".toCharArray()); KeyStore trustStore = KeyStore.getInstance("JKS"); diff --git a/client/rest/src/test/java/org/opensearch/client/RestClientBuilderTests.java b/client/rest/src/test/java/org/opensearch/client/RestClientBuilderTests.java index 529f305c870..ac81cd1132a 100644 --- a/client/rest/src/test/java/org/opensearch/client/RestClientBuilderTests.java +++ b/client/rest/src/test/java/org/opensearch/client/RestClientBuilderTests.java @@ -52,44 +52,44 @@ public class RestClientBuilderTests extends RestClientTestCase { public void testBuild() throws IOException { try { - RestClient.builder((HttpHost[])null); + RestClient.builder((HttpHost[]) null); fail("should have failed"); - } catch(IllegalArgumentException e) { + } catch (IllegalArgumentException e) { assertEquals("hosts must not be null nor empty", e.getMessage()); } try { RestClient.builder(new HttpHost[] {}); fail("should have failed"); - } catch(IllegalArgumentException e) { + } catch (IllegalArgumentException e) { assertEquals("hosts must not be null nor empty", e.getMessage()); } try { - RestClient.builder((Node[])null); + RestClient.builder((Node[]) null); fail("should have failed"); - } catch(IllegalArgumentException e) { + } catch (IllegalArgumentException e) { assertEquals("nodes must not be null or empty", e.getMessage()); } try { RestClient.builder(new Node[] {}); fail("should have failed"); - } catch(IllegalArgumentException e) { + } catch (IllegalArgumentException e) { assertEquals("nodes must not be null or empty", e.getMessage()); } try { RestClient.builder(new Node(new HttpHost("localhost", 9200)), null); fail("should have failed"); - } catch(IllegalArgumentException e) { + } catch (IllegalArgumentException e) { assertEquals("node cannot be null", e.getMessage()); } try { RestClient.builder(new HttpHost("localhost", 9200), null); fail("should have failed"); - } catch(IllegalArgumentException e) { + } catch (IllegalArgumentException e) { assertEquals("host cannot be null", e.getMessage()); } @@ -100,35 +100,35 @@ public class RestClientBuilderTests extends RestClientTestCase { try { RestClient.builder(new HttpHost("localhost", 9200)).setDefaultHeaders(null); fail("should have failed"); - } catch(NullPointerException e) { + } catch (NullPointerException e) { assertEquals("defaultHeaders must not be null", e.getMessage()); } try { - RestClient.builder(new HttpHost("localhost", 9200)).setDefaultHeaders(new Header[]{null}); + RestClient.builder(new HttpHost("localhost", 9200)).setDefaultHeaders(new Header[] { null }); fail("should have failed"); - } catch(NullPointerException e) { + } catch (NullPointerException e) { assertEquals("default header must not be null", e.getMessage()); } try { RestClient.builder(new HttpHost("localhost", 9200)).setFailureListener(null); fail("should have failed"); - } catch(NullPointerException e) { + } catch (NullPointerException e) { assertEquals("failureListener must not be null", e.getMessage()); } try { RestClient.builder(new HttpHost("localhost", 9200)).setHttpClientConfigCallback(null); fail("should have failed"); - } catch(NullPointerException e) { + } catch (NullPointerException e) { assertEquals("httpClientConfigCallback must not be null", e.getMessage()); } try { RestClient.builder(new HttpHost("localhost", 9200)).setRequestConfigCallback(null); fail("should have failed"); - } catch(NullPointerException e) { + } catch (NullPointerException e) { assertEquals("requestConfigCallback must not be null", e.getMessage()); } @@ -270,7 +270,7 @@ public class RestClientBuilderTests extends RestClientTestCase { public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) { RequestConfig requestConfig = requestConfigBuilder.build(); assertEquals(RequestConfig.DEFAULT.getConnectionRequestTimeout(), requestConfig.getConnectionRequestTimeout()); - //this way we get notified if the default ever changes + // this way we get notified if the default ever changes assertEquals(-1, requestConfig.getConnectionRequestTimeout()); return requestConfigBuilder; } diff --git a/client/rest/src/test/java/org/opensearch/client/RestClientMultipleHostsIntegTests.java b/client/rest/src/test/java/org/opensearch/client/RestClientMultipleHostsIntegTests.java index cfacadb1650..277446191a3 100644 --- a/client/rest/src/test/java/org/opensearch/client/RestClientMultipleHostsIntegTests.java +++ b/client/rest/src/test/java/org/opensearch/client/RestClientMultipleHostsIntegTests.java @@ -108,7 +108,7 @@ public class RestClientMultipleHostsIntegTests extends RestClientTestCase { private static HttpServer createHttpServer() throws Exception { HttpServer httpServer = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); httpServer.start(); - //returns a different status code depending on the path + // returns a different status code depending on the path for (int statusCode : getAllStatusCodes()) { httpServer.createContext(pathPrefix + "/" + statusCode, new ResponseHandler(statusCode)); } @@ -138,8 +138,7 @@ public class RestClientMultipleHostsIntegTests extends RestClientTestCase { requestCameInLatch.countDown(); try { cancelHandlerLatch.await(); - } catch (InterruptedException ignore) { - } finally { + } catch (InterruptedException ignore) {} finally { exchange.sendResponseHeaders(200, 0); exchange.close(); } @@ -173,7 +172,7 @@ public class RestClientMultipleHostsIntegTests extends RestClientTestCase { @Before public void stopRandomHost() { - //verify that shutting down some hosts doesn't matter as long as one working host is left behind + // verify that shutting down some hosts doesn't matter as long as one working host is left behind if (httpServers.length > 1 && randomBoolean()) { List updatedHttpServers = new ArrayList<>(httpServers.length - 1); int nodeIndex = randomIntBetween(0, httpServers.length - 1); @@ -196,12 +195,12 @@ public class RestClientMultipleHostsIntegTests extends RestClientTestCase { int numRequests = randomIntBetween(5, 20); for (int i = 0; i < numRequests; i++) { final String method = RestClientTestUtil.randomHttpMethod(getRandom()); - //we don't test status codes that are subject to retries as they interfere with hosts being stopped + // we don't test status codes that are subject to retries as they interfere with hosts being stopped final int statusCode = randomBoolean() ? randomOkStatusCode(getRandom()) : randomErrorNoRetryStatusCode(getRandom()); Response response; try { response = restClient.performRequest(new Request(method, "/" + statusCode)); - } catch(ResponseException responseException) { + } catch (ResponseException responseException) { response = responseException.getResponse(); } assertEquals(method, response.getRequestLine().getMethod()); @@ -216,7 +215,7 @@ public class RestClientMultipleHostsIntegTests extends RestClientTestCase { final List responses = new CopyOnWriteArrayList<>(); for (int i = 0; i < numRequests; i++) { final String method = RestClientTestUtil.randomHttpMethod(getRandom()); - //we don't test status codes that are subject to retries as they interfere with hosts being stopped + // we don't test status codes that are subject to retries as they interfere with hosts being stopped final int statusCode = randomBoolean() ? randomOkStatusCode(getRandom()) : randomErrorNoRetryStatusCode(getRandom()); restClient.performRequestAsync(new Request(method, "/" + statusCode), new ResponseListener() { @Override @@ -239,8 +238,7 @@ public class RestClientMultipleHostsIntegTests extends RestClientTestCase { Response response = testResponse.getResponse(); assertEquals(testResponse.method, response.getRequestLine().getMethod()); assertEquals(testResponse.statusCode, response.getStatusLine().getStatusCode()); - assertEquals((pathPrefix.length() > 0 ? pathPrefix : "") + "/" + testResponse.statusCode, - response.getRequestLine().getUri()); + assertEquals((pathPrefix.length() > 0 ? pathPrefix : "") + "/" + testResponse.statusCode, response.getRequestLine().getUri()); } } @@ -266,7 +264,7 @@ public class RestClientMultipleHostsIntegTests extends RestClientTestCase { } }); if (randomBoolean()) { - //we wait for the request to get to the server-side otherwise we almost always cancel + // we wait for the request to get to the server-side otherwise we almost always cancel // the request artificially on the client-side before even sending it waitForCancelHandler.awaitRequest(); } diff --git a/client/rest/src/test/java/org/opensearch/client/RestClientMultipleHostsTests.java b/client/rest/src/test/java/org/opensearch/client/RestClientMultipleHostsTests.java index 4c90794091b..0011622fe24 100644 --- a/client/rest/src/test/java/org/opensearch/client/RestClientMultipleHostsTests.java +++ b/client/rest/src/test/java/org/opensearch/client/RestClientMultipleHostsTests.java @@ -98,8 +98,10 @@ public class RestClientMultipleHostsTests extends RestClientTestCase { Set hostsSet = hostsSet(); for (int j = 0; j < nodes.size(); j++) { int statusCode = randomOkStatusCode(getRandom()); - Response response = RestClientSingleHostTests.performRequestSyncOrAsync(restClient, - new Request(randomHttpMethod(getRandom()), "/" + statusCode)); + Response response = RestClientSingleHostTests.performRequestSyncOrAsync( + restClient, + new Request(randomHttpMethod(getRandom()), "/" + statusCode) + ); assertEquals(statusCode, response.getStatusLine().getStatusCode()); assertTrue("host not found: " + response.getHost(), hostsSet.remove(response.getHost())); } @@ -117,10 +119,12 @@ public class RestClientMultipleHostsTests extends RestClientTestCase { String method = randomHttpMethod(getRandom()); int statusCode = randomErrorNoRetryStatusCode(getRandom()); try { - Response response = RestClientSingleHostTests.performRequestSyncOrAsync(restClient, - new Request(method, "/" + statusCode)); + Response response = RestClientSingleHostTests.performRequestSyncOrAsync( + restClient, + new Request(method, "/" + statusCode) + ); if (method.equals("HEAD") && statusCode == 404) { - //no exception gets thrown although we got a 404 + // no exception gets thrown although we got a 404 assertEquals(404, response.getStatusLine().getStatusCode()); assertEquals(statusCode, response.getStatusLine().getStatusCode()); assertTrue("host not found: " + response.getHost(), hostsSet.remove(response.getHost())); @@ -145,31 +149,33 @@ public class RestClientMultipleHostsTests extends RestClientTestCase { public void testRoundRobinRetryErrors() throws Exception { RestClient restClient = createRestClient(NodeSelector.ANY); String retryEndpoint = randomErrorRetryEndpoint(); - try { + try { RestClientSingleHostTests.performRequestSyncOrAsync(restClient, new Request(randomHttpMethod(getRandom()), retryEndpoint)); fail("request should have failed"); } catch (ResponseException e) { Set hostsSet = hostsSet(); - //first request causes all the hosts to be blacklisted, the returned exception holds one suppressed exception each + // first request causes all the hosts to be blacklisted, the returned exception holds one suppressed exception each failureListener.assertCalled(nodes); do { Response response = e.getResponse(); assertEquals(Integer.parseInt(retryEndpoint.substring(1)), response.getStatusLine().getStatusCode()); - assertTrue("host [" + response.getHost() + "] not found, most likely used multiple times", - hostsSet.remove(response.getHost())); + assertTrue( + "host [" + response.getHost() + "] not found, most likely used multiple times", + hostsSet.remove(response.getHost()) + ); if (e.getSuppressed().length > 0) { assertEquals(1, e.getSuppressed().length); Throwable suppressed = e.getSuppressed()[0]; assertThat(suppressed, instanceOf(ResponseException.class)); - e = (ResponseException)suppressed; + e = (ResponseException) suppressed; } else { e = null; } - } while(e != null); + } while (e != null); assertEquals("every host should have been used but some weren't: " + hostsSet, 0, hostsSet.size()); } catch (IOException e) { Set hostsSet = hostsSet(); - //first request causes all the hosts to be blacklisted, the returned exception holds one suppressed exception each + // first request causes all the hosts to be blacklisted, the returned exception holds one suppressed exception each failureListener.assertCalled(nodes); do { HttpHost httpHost = HttpHost.create(e.getMessage()); @@ -182,47 +188,53 @@ public class RestClientMultipleHostsTests extends RestClientTestCase { } else { e = null; } - } while(e != null); + } while (e != null); assertEquals("every host should have been used but some weren't: " + hostsSet, 0, hostsSet.size()); } int numIters = RandomNumbers.randomIntBetween(getRandom(), 2, 5); for (int i = 1; i <= numIters; i++) { - //check that one different host is resurrected at each new attempt + // check that one different host is resurrected at each new attempt Set hostsSet = hostsSet(); for (int j = 0; j < nodes.size(); j++) { retryEndpoint = randomErrorRetryEndpoint(); - try { - RestClientSingleHostTests.performRequestSyncOrAsync(restClient, - new Request(randomHttpMethod(getRandom()), retryEndpoint)); + try { + RestClientSingleHostTests.performRequestSyncOrAsync( + restClient, + new Request(randomHttpMethod(getRandom()), retryEndpoint) + ); fail("request should have failed"); } catch (ResponseException e) { Response response = e.getResponse(); assertThat(response.getStatusLine().getStatusCode(), equalTo(Integer.parseInt(retryEndpoint.substring(1)))); - assertTrue("host [" + response.getHost() + "] not found, most likely used multiple times", - hostsSet.remove(response.getHost())); - //after the first request, all hosts are blacklisted, a single one gets resurrected each time + assertTrue( + "host [" + response.getHost() + "] not found, most likely used multiple times", + hostsSet.remove(response.getHost()) + ); + // after the first request, all hosts are blacklisted, a single one gets resurrected each time failureListener.assertCalled(response.getHost()); assertEquals(0, e.getSuppressed().length); } catch (IOException e) { HttpHost httpHost = HttpHost.create(e.getMessage()); assertTrue("host [" + httpHost + "] not found, most likely used multiple times", hostsSet.remove(httpHost)); - //after the first request, all hosts are blacklisted, a single one gets resurrected each time + // after the first request, all hosts are blacklisted, a single one gets resurrected each time failureListener.assertCalled(httpHost); assertEquals(0, e.getSuppressed().length); } } assertEquals("every host should have been used but some weren't: " + hostsSet, 0, hostsSet.size()); if (getRandom().nextBoolean()) { - //mark one host back alive through a successful request and check that all requests after that are sent to it + // mark one host back alive through a successful request and check that all requests after that are sent to it HttpHost selectedHost = null; int iters = RandomNumbers.randomIntBetween(getRandom(), 2, 10); for (int y = 0; y < iters; y++) { int statusCode = randomErrorNoRetryStatusCode(getRandom()); Response response; try { - response = RestClientSingleHostTests.performRequestSyncOrAsync(restClient, - new Request(randomHttpMethod(getRandom()), "/" + statusCode)); + response = RestClientSingleHostTests.performRequestSyncOrAsync( + restClient, + new Request(randomHttpMethod(getRandom()), "/" + statusCode) + ); } catch (ResponseException e) { response = e.getResponse(); } @@ -234,20 +246,22 @@ public class RestClientMultipleHostsTests extends RestClientTestCase { } } failureListener.assertNotCalled(); - //let the selected host catch up on number of failures, it gets selected a consecutive number of times as it's the one - //selected to be retried earlier (due to lower number of failures) till all the hosts have the same number of failures + // let the selected host catch up on number of failures, it gets selected a consecutive number of times as it's the one + // selected to be retried earlier (due to lower number of failures) till all the hosts have the same number of failures for (int y = 0; y < i + 1; y++) { retryEndpoint = randomErrorRetryEndpoint(); try { - RestClientSingleHostTests.performRequestSyncOrAsync(restClient, - new Request(randomHttpMethod(getRandom()), retryEndpoint)); + RestClientSingleHostTests.performRequestSyncOrAsync( + restClient, + new Request(randomHttpMethod(getRandom()), retryEndpoint) + ); fail("request should have failed"); } catch (ResponseException e) { Response response = e.getResponse(); assertThat(response.getStatusLine().getStatusCode(), equalTo(Integer.parseInt(retryEndpoint.substring(1)))); assertThat(response.getHost(), equalTo(selectedHost)); failureListener.assertCalled(selectedHost); - } catch(IOException e) { + } catch (IOException e) { HttpHost httpHost = HttpHost.create(e.getMessage()); assertThat(httpHost, equalTo(selectedHost)); failureListener.assertCalled(selectedHost); @@ -286,9 +300,9 @@ public class RestClientMultipleHostsTests extends RestClientTestCase { RestClient restClient = createRestClient(NodeSelector.SKIP_DEDICATED_MASTERS); List newNodes = new ArrayList<>(nodes.size()); for (int i = 0; i < nodes.size(); i++) { - Node.Roles roles = i == 0 ? - new Node.Roles(new TreeSet<>(Arrays.asList("data", "ingest"))) : - new Node.Roles(new TreeSet<>(Arrays.asList("master"))); + Node.Roles roles = i == 0 + ? new Node.Roles(new TreeSet<>(Arrays.asList("data", "ingest"))) + : new Node.Roles(new TreeSet<>(Arrays.asList("master"))); newNodes.add(new Node(nodes.get(i).getHost(), null, null, null, roles, null)); } restClient.setNodes(newNodes); @@ -305,7 +319,7 @@ public class RestClientMultipleHostsTests extends RestClientTestCase { } private static String randomErrorRetryEndpoint() { - switch(RandomNumbers.randomIntBetween(getRandom(), 0, 3)) { + switch (RandomNumbers.randomIntBetween(getRandom(), 0, 3)) { case 0: return "/" + randomErrorRetryStatusCode(getRandom()); case 1: diff --git a/client/rest/src/test/java/org/opensearch/client/RestClientSingleHostIntegTests.java b/client/rest/src/test/java/org/opensearch/client/RestClientSingleHostIntegTests.java index b412130be77..0500d282a50 100644 --- a/client/rest/src/test/java/org/opensearch/client/RestClientSingleHostIntegTests.java +++ b/client/rest/src/test/java/org/opensearch/client/RestClientSingleHostIntegTests.java @@ -108,7 +108,7 @@ public class RestClientSingleHostIntegTests extends RestClientTestCase { private HttpServer createHttpServer() throws Exception { HttpServer httpServer = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); httpServer.start(); - //returns a different status code depending on the path + // returns a different status code depending on the path for (int statusCode : getAllStatusCodes()) { httpServer.createContext(pathPrefix + "/" + statusCode, new ResponseHandler(statusCode)); } @@ -129,8 +129,7 @@ public class RestClientSingleHostIntegTests extends RestClientTestCase { public void handle(HttpExchange exchange) throws IOException { try { cancelHandlerLatch.await(); - } catch (InterruptedException ignore) { - } finally { + } catch (InterruptedException ignore) {} finally { exchange.sendResponseHeaders(200, 0); exchange.close(); } @@ -146,7 +145,7 @@ public class RestClientSingleHostIntegTests extends RestClientTestCase { @Override public void handle(HttpExchange httpExchange) throws IOException { - //copy request body to response body so we can verify it was sent + // copy request body to response body so we can verify it was sent StringBuilder body = new StringBuilder(); try (InputStreamReader reader = new InputStreamReader(httpExchange.getRequestBody(), Consts.UTF_8)) { char[] buffer = new char[256]; @@ -155,7 +154,7 @@ public class RestClientSingleHostIntegTests extends RestClientTestCase { body.append(buffer, 0, read); } } - //copy request headers to response headers so we can verify they were sent + // copy request headers to response headers so we can verify they were sent Headers requestHeaders = httpExchange.getRequestHeaders(); Headers responseHeaders = httpExchange.getResponseHeaders(); for (Map.Entry> header : requestHeaders.entrySet()) { @@ -178,7 +177,8 @@ public class RestClientSingleHostIntegTests extends RestClientTestCase { credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user", "pass")); final RestClientBuilder restClientBuilder = RestClient.builder( - new HttpHost(httpServer.getAddress().getHostString(), httpServer.getAddress().getPort())).setDefaultHeaders(defaultHeaders); + new HttpHost(httpServer.getAddress().getHostString(), httpServer.getAddress().getPort()) + ).setDefaultHeaders(defaultHeaders); if (pathPrefix.length() > 0) { restClientBuilder.setPathPrefix(pathPrefix); } @@ -237,8 +237,9 @@ public class RestClientSingleHostIntegTests extends RestClientTestCase { assertTrue("timeout waiting for requests to be sent", latch.await(10, TimeUnit.SECONDS)); if (exceptions.isEmpty() == false) { - AssertionError error = new AssertionError("expected no failures but got some. see suppressed for first 10 of [" - + exceptions.size() + "] failures"); + AssertionError error = new AssertionError( + "expected no failures but got some. see suppressed for first 10 of [" + exceptions.size() + "] failures" + ); for (Exception exception : exceptions.subList(0, Math.min(10, exceptions.size()))) { error.addSuppressed(exception); } @@ -280,7 +281,7 @@ public class RestClientSingleHostIntegTests extends RestClientTestCase { HttpHost httpHost = new HttpHost(httpServer.getAddress().getHostString(), httpServer.getAddress().getPort()); HttpGet httpGet = new HttpGet(pathPrefix + "/200"); - //calling abort before the request is sent is a no-op + // calling abort before the request is sent is a no-op httpGet.abort(); assertTrue(httpGet.isAborted()); @@ -292,8 +293,8 @@ public class RestClientSingleHostIntegTests extends RestClientTestCase { try { future.get(); fail("expected cancellation exception"); - } catch(CancellationException e) { - //expected + } catch (CancellationException e) { + // expected } assertTrue(future.isCancelled()); } @@ -307,8 +308,8 @@ public class RestClientSingleHostIntegTests extends RestClientTestCase { assertTrue(future.isCancelled()); future.get(); throw new AssertionError("exception should have been thrown"); - } catch(CancellationException e) { - //expected + } catch (CancellationException e) { + // expected } } { @@ -435,7 +436,7 @@ public class RestClientSingleHostIntegTests extends RestClientTestCase { * Verify that credentials are sent on the first request with preemptive auth enabled (default when provided with credentials). */ public void testPreemptiveAuthEnabled() throws Exception { - final String[] methods = {"POST", "PUT", "GET", "DELETE"}; + final String[] methods = { "POST", "PUT", "GET", "DELETE" }; try (RestClient restClient = createRestClient(true, true)) { for (final String method : methods) { @@ -450,7 +451,7 @@ public class RestClientSingleHostIntegTests extends RestClientTestCase { * Verify that credentials are not sent on the first request with preemptive auth disabled. */ public void testPreemptiveAuthDisabled() throws Exception { - final String[] methods = {"POST", "PUT", "GET", "DELETE"}; + final String[] methods = { "POST", "PUT", "GET", "DELETE" }; try (RestClient restClient = createRestClient(true, false)) { for (final String method : methods) { @@ -465,12 +466,12 @@ public class RestClientSingleHostIntegTests extends RestClientTestCase { * Verify that credentials continue to be sent even if a 401 (Unauthorized) response is received */ public void testAuthCredentialsAreNotClearedOnAuthChallenge() throws Exception { - final String[] methods = {"POST", "PUT", "GET", "DELETE"}; + final String[] methods = { "POST", "PUT", "GET", "DELETE" }; try (RestClient restClient = createRestClient(true, true)) { for (final String method : methods) { Header realmHeader = new BasicHeader("WWW-Authenticate", "Basic realm=\"test\""); - final Response response401 = bodyTest(restClient, method, 401, new Header[]{realmHeader}); + final Response response401 = bodyTest(restClient, method, 401, new Header[] { realmHeader }); assertThat(response401.getHeader("Authorization"), startsWith("Basic")); final Response response200 = bodyTest(restClient, method, 200, new Header[0]); @@ -490,16 +491,18 @@ public class RestClientSingleHostIntegTests extends RestClientTestCase { } else { { Response response = RestClientSingleHostTests.performRequestSyncOrAsync(restClient, new Request("GET", "200")); - //a trailing slash gets automatically added if a pathPrefix is configured + // a trailing slash gets automatically added if a pathPrefix is configured assertEquals(200, response.getStatusLine().getStatusCode()); } { - //pathPrefix is not required to start with '/', will be added automatically - try (RestClient restClient = RestClient.builder( - new HttpHost(httpServer.getAddress().getHostString(), httpServer.getAddress().getPort())) - .setPathPrefix(pathPrefix.substring(1)).build()) { + // pathPrefix is not required to start with '/', will be added automatically + try ( + RestClient restClient = RestClient.builder( + new HttpHost(httpServer.getAddress().getHostString(), httpServer.getAddress().getPort()) + ).setPathPrefix(pathPrefix.substring(1)).build() + ) { Response response = RestClientSingleHostTests.performRequestSyncOrAsync(restClient, new Request("GET", "200")); - //a trailing slash gets automatically added if a pathPrefix is configured + // a trailing slash gets automatically added if a pathPrefix is configured assertEquals(200, response.getStatusLine().getStatusCode()); } } @@ -527,7 +530,7 @@ public class RestClientSingleHostIntegTests extends RestClientTestCase { Response esResponse; try { esResponse = RestClientSingleHostTests.performRequestSyncOrAsync(restClient, request); - } catch(ResponseException e) { + } catch (ResponseException e) { esResponse = e.getResponse(); } assertEquals(method, esResponse.getRequestLine().getMethod()); diff --git a/client/rest/src/test/java/org/opensearch/client/RestClientSingleHostTests.java b/client/rest/src/test/java/org/opensearch/client/RestClientSingleHostTests.java index 7830e23d066..d8ab0dcd0e8 100644 --- a/client/rest/src/test/java/org/opensearch/client/RestClientSingleHostTests.java +++ b/client/rest/src/test/java/org/opensearch/client/RestClientSingleHostTests.java @@ -130,39 +130,52 @@ public class RestClientSingleHostTests extends RestClientTestCase { node = new Node(new HttpHost("localhost", 9200)); failureListener = new HostsTrackingFailureListener(); strictDeprecationMode = randomBoolean(); - restClient = new RestClient(this.httpClient, defaultHeaders, - singletonList(node), null, failureListener, NodeSelector.ANY, strictDeprecationMode, false); + restClient = new RestClient( + this.httpClient, + defaultHeaders, + singletonList(node), + null, + failureListener, + NodeSelector.ANY, + strictDeprecationMode, + false + ); } @SuppressWarnings("unchecked") static CloseableHttpAsyncClient mockHttpClient(final ExecutorService exec) { CloseableHttpAsyncClient httpClient = mock(CloseableHttpAsyncClient.class); - when(httpClient.execute(any(HttpAsyncRequestProducer.class), any(HttpAsyncResponseConsumer.class), - any(HttpClientContext.class), nullable(FutureCallback.class))).thenAnswer((Answer>) invocationOnMock -> { - final HttpAsyncRequestProducer requestProducer = (HttpAsyncRequestProducer) invocationOnMock.getArguments()[0]; - final FutureCallback futureCallback = - (FutureCallback) invocationOnMock.getArguments()[3]; - // Call the callback asynchronous to better simulate how async http client works - return exec.submit(() -> { - if (futureCallback != null) { - try { - HttpResponse httpResponse = responseOrException(requestProducer); - futureCallback.completed(httpResponse); - } catch(Exception e) { - futureCallback.failed(e); - } - return null; + when( + httpClient.execute( + any(HttpAsyncRequestProducer.class), + any(HttpAsyncResponseConsumer.class), + any(HttpClientContext.class), + nullable(FutureCallback.class) + ) + ).thenAnswer((Answer>) invocationOnMock -> { + final HttpAsyncRequestProducer requestProducer = (HttpAsyncRequestProducer) invocationOnMock.getArguments()[0]; + final FutureCallback futureCallback = (FutureCallback) invocationOnMock.getArguments()[3]; + // Call the callback asynchronous to better simulate how async http client works + return exec.submit(() -> { + if (futureCallback != null) { + try { + HttpResponse httpResponse = responseOrException(requestProducer); + futureCallback.completed(httpResponse); + } catch (Exception e) { + futureCallback.failed(e); } - return responseOrException(requestProducer); - }); + return null; + } + return responseOrException(requestProducer); }); + }); return httpClient; } private static HttpResponse responseOrException(HttpAsyncRequestProducer requestProducer) throws Exception { - final HttpUriRequest request = (HttpUriRequest)requestProducer.generateRequest(); + final HttpUriRequest request = (HttpUriRequest) requestProducer.generateRequest(); final HttpHost httpHost = requestProducer.getTarget(); - //return the desired status code or exception depending on the path + // return the desired status code or exception depending on the path switch (request.getURI().getPath()) { case "/soe": throw new SocketTimeoutException(httpHost.toString()); @@ -183,16 +196,15 @@ public class RestClientSingleHostTests extends RestClientTestCase { StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("http", 1, 1), statusCode, ""); final HttpResponse httpResponse = new BasicHttpResponse(statusLine); - //return the same body that was sent + // return the same body that was sent if (request instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); if (entity != null) { - assertTrue("the entity is not repeatable, cannot set it to the response directly", - entity.isRepeatable()); + assertTrue("the entity is not repeatable, cannot set it to the response directly", entity.isRepeatable()); httpResponse.setEntity(entity); } } - //return the same headers that were sent + // return the same headers that were sent httpResponse.setHeaders(request.getAllHeaders()); return httpResponse; } @@ -215,9 +227,13 @@ public class RestClientSingleHostTests extends RestClientTestCase { int times = 0; for (String httpMethod : getHttpMethods()) { HttpUriRequest expectedRequest = performRandomRequest(httpMethod); - verify(httpClient, times(++times)).execute(requestArgumentCaptor.capture(), - any(HttpAsyncResponseConsumer.class), any(HttpClientContext.class), nullable(FutureCallback.class)); - HttpUriRequest actualRequest = (HttpUriRequest)requestArgumentCaptor.getValue().generateRequest(); + verify(httpClient, times(++times)).execute( + requestArgumentCaptor.capture(), + any(HttpAsyncResponseConsumer.class), + any(HttpClientContext.class), + nullable(FutureCallback.class) + ); + HttpUriRequest actualRequest = (HttpUriRequest) requestArgumentCaptor.getValue().generateRequest(); assertEquals(expectedRequest.getURI(), actualRequest.getURI()); assertEquals(expectedRequest.getClass(), actualRequest.getClass()); assertArrayEquals(expectedRequest.getAllHeaders(), actualRequest.getAllHeaders()); @@ -265,7 +281,7 @@ public class RestClientSingleHostTests extends RestClientTestCase { } } } - //error status codes should cause an exception to be thrown + // error status codes should cause an exception to be thrown for (int errorStatusCode : getAllErrorStatusCodes()) { try { Request request = new Request(method, "/" + errorStatusCode); @@ -274,12 +290,12 @@ public class RestClientSingleHostTests extends RestClientTestCase { } Response response = restClient.performRequest(request); if (expectedIgnores.contains(errorStatusCode)) { - //no exception gets thrown although we got an error status code, as it was configured to be ignored + // no exception gets thrown although we got an error status code, as it was configured to be ignored assertEquals(errorStatusCode, response.getStatusLine().getStatusCode()); } else { fail("request should have failed"); } - } catch(ResponseException e) { + } catch (ResponseException e) { if (expectedIgnores.contains(errorStatusCode)) { throw e; } @@ -297,11 +313,11 @@ public class RestClientSingleHostTests extends RestClientTestCase { public void testPerformRequestIOExceptions() throws Exception { for (String method : getHttpMethods()) { - //IOExceptions should be let bubble up + // IOExceptions should be let bubble up try { restClient.performRequest(new Request(method, "/ioe")); fail("request should have failed"); - } catch(IOException e) { + } catch (IOException e) { // And we do all that so the thrown exception has our method in the stacktrace assertExceptionStackContainsCallingMethod(e); } @@ -309,7 +325,7 @@ public class RestClientSingleHostTests extends RestClientTestCase { try { restClient.performRequest(new Request(method, "/coe")); fail("request should have failed"); - } catch(ConnectTimeoutException e) { + } catch (ConnectTimeoutException e) { // And we do all that so the thrown exception has our method in the stacktrace assertExceptionStackContainsCallingMethod(e); } @@ -317,7 +333,7 @@ public class RestClientSingleHostTests extends RestClientTestCase { try { restClient.performRequest(new Request(method, "/soe")); fail("request should have failed"); - } catch(SocketTimeoutException e) { + } catch (SocketTimeoutException e) { // And we do all that so the thrown exception has our method in the stacktrace assertExceptionStackContainsCallingMethod(e); } @@ -325,7 +341,7 @@ public class RestClientSingleHostTests extends RestClientTestCase { try { restClient.performRequest(new Request(method, "/closed")); fail("request should have failed"); - } catch(ConnectionClosedException e) { + } catch (ConnectionClosedException e) { // And we do all that so the thrown exception has our method in the stacktrace assertExceptionStackContainsCallingMethod(e); } @@ -333,7 +349,7 @@ public class RestClientSingleHostTests extends RestClientTestCase { try { restClient.performRequest(new Request(method, "/handshake")); fail("request should have failed"); - } catch(SSLHandshakeException e) { + } catch (SSLHandshakeException e) { // And we do all that so the thrown exception has our method in the stacktrace assertExceptionStackContainsCallingMethod(e); } @@ -389,7 +405,7 @@ public class RestClientSingleHostTests extends RestClientTestCase { try { restClient.performRequest(request); fail("request should have failed"); - } catch(ResponseException e) { + } catch (ResponseException e) { Response response = e.getResponse(); assertThat(response.getStatusLine().getStatusCode(), equalTo(errorStatusCode)); assertThat(EntityUtils.toString(response.getEntity()), equalTo(body)); @@ -403,7 +419,7 @@ public class RestClientSingleHostTests extends RestClientTestCase { try { performRequestSyncOrAsync(restClient, request); fail("request should have failed"); - } catch(UnsupportedOperationException e) { + } catch (UnsupportedOperationException e) { assertThat(e.getMessage(), equalTo(method + " with body is not supported")); } } @@ -426,7 +442,7 @@ public class RestClientSingleHostTests extends RestClientTestCase { Response esResponse; try { esResponse = performRequestSyncOrAsync(restClient, request); - } catch(ResponseException e) { + } catch (ResponseException e) { esResponse = e.getResponse(); } assertThat(esResponse.getStatusLine().getStatusCode(), equalTo(statusCode)); @@ -441,11 +457,10 @@ public class RestClientSingleHostTests extends RestClientTestCase { assertDeprecationWarnings(singletonList(formatWarningWithoutDate(chars)), singletonList(chars)); assertDeprecationWarnings(singletonList(formatWarning(chars)), singletonList(chars)); assertDeprecationWarnings( - Arrays.asList(formatWarning(chars), "another one", "and another"), - Arrays.asList(chars, "another one", "and another")); - assertDeprecationWarnings( - Arrays.asList("ignorable one", "and another"), - Arrays.asList("ignorable one", "and another")); + Arrays.asList(formatWarning(chars), "another one", "and another"), + Arrays.asList(chars, "another one", "and another") + ); + assertDeprecationWarnings(Arrays.asList("ignorable one", "and another"), Arrays.asList("ignorable one", "and another")); assertDeprecationWarnings(singletonList("exact"), singletonList("exact")); assertDeprecationWarnings(Collections.emptyList(), Collections.emptyList()); @@ -559,7 +574,7 @@ public class RestClientSingleHostTests extends RestClientTestCase { } } if (randomBoolean()) { - //randomly add some ignore parameter, which doesn't get sent as part of the request + // randomly add some ignore parameter, which doesn't get sent as part of the request String ignore = Integer.toString(randomFrom(RestClientTestUtil.getAllErrorStatusCodes())); if (randomBoolean()) { ignore += "," + randomFrom(RestClientTestUtil.getAllErrorStatusCodes()); @@ -569,7 +584,7 @@ public class RestClientSingleHostTests extends RestClientTestCase { URI uri = uriBuilder.build(); HttpUriRequest expectedRequest; - switch(method) { + switch (method) { case "DELETE": expectedRequest = new HttpDeleteWithEntity(uri); break; @@ -623,14 +638,14 @@ public class RestClientSingleHostTests extends RestClientTestCase { } try { performRequestSyncOrAsync(restClient, request); - } catch(Exception e) { - //all good + } catch (Exception e) { + // all good } return expectedRequest; } static Response performRequestSyncOrAsync(RestClient restClient, Request request) throws Exception { - //randomize between sync and async methods + // randomize between sync and async methods if (randomBoolean()) { return restClient.performRequest(request); } else { @@ -674,8 +689,7 @@ public class RestClientSingleHostTests extends RestClientTestCase { // 2 is the caller, what we want StackTraceElement myMethod = Thread.currentThread().getStackTrace()[2]; for (StackTraceElement se : t.getStackTrace()) { - if (se.getClassName().equals(myMethod.getClassName()) - && se.getMethodName().equals(myMethod.getMethodName())) { + if (se.getClassName().equals(myMethod.getClassName()) && se.getMethodName().equals(myMethod.getMethodName())) { return; } } diff --git a/client/rest/src/test/java/org/opensearch/client/RestClientTests.java b/client/rest/src/test/java/org/opensearch/client/RestClientTests.java index 4930df8e3c3..169e2dbcfd8 100644 --- a/client/rest/src/test/java/org/opensearch/client/RestClientTests.java +++ b/client/rest/src/test/java/org/opensearch/client/RestClientTests.java @@ -185,10 +185,7 @@ public class RestClientTests extends RestClientTestCase { assertEquals("node cannot be null", e.getMessage()); } try (RestClient restClient = createRestClient()) { - restClient.setNodes(Arrays.asList( - new Node(new HttpHost("localhost", 9200)), - null, - new Node(new HttpHost("localhost", 9201)))); + restClient.setNodes(Arrays.asList(new Node(new HttpHost("localhost", 9200)), null, new Node(new HttpHost("localhost", 9201)))); fail("setNodes should have failed"); } catch (NullPointerException e) { assertEquals("node cannot be null", e.getMessage()); @@ -275,8 +272,8 @@ public class RestClientTests extends RestClientTestCase { */ { String message = "NodeSelector [NONE] rejected all nodes, living [" - + "[host=http://1, version=1], [host=http://2, version=2], " - + "[host=http://3, version=3]] and dead []"; + + "[host=http://1, version=1], [host=http://2, version=2], " + + "[host=http://3, version=3]] and dead []"; assertEquals(message, assertSelectAllRejected(nodeTuple, emptyBlacklist, noNodes)); } @@ -313,8 +310,8 @@ public class RestClientTests extends RestClientTestCase { * their nodes are blacklisted AND blocked. */ String message = "NodeSelector [NONE] rejected all nodes, living [] and dead [" - + "[host=http://1, version=1], [host=http://2, version=2], " - + "[host=http://3, version=3]]"; + + "[host=http://1, version=1], [host=http://2, version=2], " + + "[host=http://3, version=3]]"; assertEquals(message, assertSelectAllRejected(nodeTuple, blacklist, noNodes)); /* @@ -341,16 +338,19 @@ public class RestClientTests extends RestClientTestCase { } } - private void assertSelectLivingHosts(List expectedNodes, NodeTuple> nodeTuple, - Map blacklist, NodeSelector nodeSelector) throws IOException { + private void assertSelectLivingHosts( + List expectedNodes, + NodeTuple> nodeTuple, + Map blacklist, + NodeSelector nodeSelector + ) throws IOException { int iterations = 1000; AtomicInteger lastNodeIndex = new AtomicInteger(0); assertEquals(expectedNodes, RestClient.selectNodes(nodeTuple, blacklist, lastNodeIndex, nodeSelector)); // Calling it again rotates the set of results for (int i = 1; i < iterations; i++) { Collections.rotate(expectedNodes, 1); - assertEquals("iteration " + i, expectedNodes, - RestClient.selectNodes(nodeTuple, blacklist, lastNodeIndex, nodeSelector)); + assertEquals("iteration " + i, expectedNodes, RestClient.selectNodes(nodeTuple, blacklist, lastNodeIndex, nodeSelector)); } } @@ -358,8 +358,11 @@ public class RestClientTests extends RestClientTestCase { * Assert that {@link RestClient#selectNodes} fails on the provided arguments. * @return the message in the exception thrown by the failure */ - private static String assertSelectAllRejected( NodeTuple> nodeTuple, - Map blacklist, NodeSelector nodeSelector) { + private static String assertSelectAllRejected( + NodeTuple> nodeTuple, + Map blacklist, + NodeSelector nodeSelector + ) { try { RestClient.selectNodes(nodeTuple, blacklist, new AtomicInteger(0), nodeSelector); throw new AssertionError("expected selectHosts to fail"); @@ -384,25 +387,25 @@ public class RestClientTests extends RestClientTestCase { } NodeTuple> nodeTuple = new NodeTuple<>(nodes, authCache); - //test the transition from negative to positive values + // test the transition from negative to positive values AtomicInteger lastNodeIndex = new AtomicInteger(-numNodes); assertNodes(nodeTuple, lastNodeIndex, 50); assertEquals(-numNodes + 50, lastNodeIndex.get()); - //test the highest positive values up to MAX_VALUE + // test the highest positive values up to MAX_VALUE lastNodeIndex.set(Integer.MAX_VALUE - numNodes * 10); assertNodes(nodeTuple, lastNodeIndex, numNodes * 10); assertEquals(Integer.MAX_VALUE, lastNodeIndex.get()); - //test the transition from MAX_VALUE to MIN_VALUE - //this is the only time where there is most likely going to be a jump from a node - //to another one that's not necessarily the next one. + // test the transition from MAX_VALUE to MIN_VALUE + // this is the only time where there is most likely going to be a jump from a node + // to another one that's not necessarily the next one. assertEquals(Integer.MIN_VALUE, lastNodeIndex.incrementAndGet()); assertNodes(nodeTuple, lastNodeIndex, 50); assertEquals(Integer.MIN_VALUE + 50, lastNodeIndex.get()); } - public void testIsRunning(){ + public void testIsRunning() { List nodes = Collections.singletonList(new Node(new HttpHost("localhost", 9200))); CloseableHttpAsyncClient client = mock(CloseableHttpAsyncClient.class); RestClient restClient = new RestClient(client, new Header[] {}, nodes, null, null, null, false, false); @@ -422,8 +425,12 @@ public class RestClientTests extends RestClientTestCase { */ int expectedOffset = distance > 0 ? nodeTuple.nodes.size() - distance : Math.abs(distance); for (int i = 0; i < runs; i++) { - Iterable selectedNodes = RestClient.selectNodes(nodeTuple, Collections.emptyMap(), - lastNodeIndex, NodeSelector.ANY); + Iterable selectedNodes = RestClient.selectNodes( + nodeTuple, + Collections.emptyMap(), + lastNodeIndex, + NodeSelector.ANY + ); List expectedNodes = nodeTuple.nodes; int index = 0; for (Node actualNode : selectedNodes) { diff --git a/client/sniffer/src/main/java/org/opensearch/client/sniff/OpenSearchNodesSniffer.java b/client/sniffer/src/main/java/org/opensearch/client/sniff/OpenSearchNodesSniffer.java index 850d152bd10..2829439627d 100644 --- a/client/sniffer/src/main/java/org/opensearch/client/sniff/OpenSearchNodesSniffer.java +++ b/client/sniffer/src/main/java/org/opensearch/client/sniff/OpenSearchNodesSniffer.java @@ -183,12 +183,11 @@ public final class OpenSearchNodesSniffer implements NodesSniffer { URI publishAddressAsURI; // ES7 cname/ip:port format - if(address.contains("/")) { + if (address.contains("/")) { String[] cnameAndURI = address.split("/", 2); publishAddressAsURI = URI.create(scheme + "://" + cnameAndURI[1]); host = cnameAndURI[0]; - } - else { + } else { publishAddressAsURI = URI.create(scheme + "://" + address); host = publishAddressAsURI.getHost(); } @@ -196,8 +195,9 @@ public final class OpenSearchNodesSniffer implements NodesSniffer { } else if (parser.currentToken() == JsonToken.START_ARRAY && "bound_address".equals(parser.getCurrentName())) { while (parser.nextToken() != JsonToken.END_ARRAY) { URI boundAddressAsURI = URI.create(scheme + "://" + parser.getValueAsString()); - boundHosts.add(new HttpHost(boundAddressAsURI.getHost(), boundAddressAsURI.getPort(), - boundAddressAsURI.getScheme())); + boundHosts.add( + new HttpHost(boundAddressAsURI.getHost(), boundAddressAsURI.getPort(), boundAddressAsURI.getScheme()) + ); } } else if (parser.getCurrentToken() == JsonToken.START_OBJECT) { parser.skipChildren(); @@ -234,7 +234,7 @@ public final class OpenSearchNodesSniffer implements NodesSniffer { } } } - //http section is not present if http is not enabled on the node, ignore such nodes + // http section is not present if http is not enabled on the node, ignore such nodes if (publishedHost == null) { logger.debug("skipping node [" + nodeId + "] with http disabled"); return null; @@ -279,11 +279,9 @@ public final class OpenSearchNodesSniffer implements NodesSniffer { } else { assert sawRoles : "didn't see roles for [" + nodeId + "]"; } - assert boundHosts.contains(publishedHost) : - "[" + nodeId + "] doesn't make sense! publishedHost should be in boundHosts"; + assert boundHosts.contains(publishedHost) : "[" + nodeId + "] doesn't make sense! publishedHost should be in boundHosts"; logger.trace("adding node [" + nodeId + "]"); - return new Node(publishedHost, boundHosts, name, version, new Roles(roles), - unmodifiableMap(realAttributes)); + return new Node(publishedHost, boundHosts, name, version, new Roles(roles), unmodifiableMap(realAttributes)); } /** @@ -292,24 +290,22 @@ public final class OpenSearchNodesSniffer implements NodesSniffer { * either of those, or throws an IOException if the attribute * came back in a strange way. */ - private static Boolean v2RoleAttributeValue(Map> attributes, - String name, Boolean defaultValue) throws IOException { + private static Boolean v2RoleAttributeValue(Map> attributes, String name, Boolean defaultValue) + throws IOException { List valueList = attributes.remove(name); if (valueList == null) { return defaultValue; } if (valueList.size() != 1) { - throw new IOException("expected only a single attribute value for [" + name + "] but got " - + valueList); + throw new IOException("expected only a single attribute value for [" + name + "] but got " + valueList); } switch (valueList.get(0)) { - case "true": - return true; - case "false": - return false; - default: - throw new IOException("expected [" + name + "] to be either [true] or [false] but was [" - + valueList.get(0) + "]"); + case "true": + return true; + case "false": + return false; + default: + throw new IOException("expected [" + name + "] to be either [true] or [false] but was [" + valueList.get(0) + "]"); } } diff --git a/client/sniffer/src/main/java/org/opensearch/client/sniff/Sniffer.java b/client/sniffer/src/main/java/org/opensearch/client/sniff/Sniffer.java index 385b265c20d..2a6362c6113 100644 --- a/client/sniffer/src/main/java/org/opensearch/client/sniff/Sniffer.java +++ b/client/sniffer/src/main/java/org/opensearch/client/sniff/Sniffer.java @@ -108,7 +108,7 @@ public class Sniffer implements Closeable { * it will also schedule a new round after sniffAfterFailureDelay ms. */ public void sniffOnFailure() { - //sniffOnFailure does nothing until the initial sniffing round has been completed + // sniffOnFailure does nothing until the initial sniffing round has been completed if (initialized.get()) { /* * If sniffing is already running, there is no point in scheduling another round right after the current one. @@ -127,7 +127,9 @@ public class Sniffer implements Closeable { } enum TaskState { - WAITING, SKIPPED, STARTED + WAITING, + SKIPPED, + STARTED } class Task implements Runnable { @@ -155,12 +157,12 @@ public class Sniffer implements Closeable { } finally { Task task = new Task(sniffIntervalMillis); Future future = scheduler.schedule(task, nextTaskDelay); - //tasks are run by a single threaded executor, so swapping is safe with a simple volatile variable + // tasks are run by a single threaded executor, so swapping is safe with a simple volatile variable ScheduledTask previousTask = nextScheduledTask; nextScheduledTask = new ScheduledTask(task, future); - assert initialized.get() == false || - previousTask.task.isSkipped() || previousTask.task.hasStarted() : "task that we are replacing is neither " + - "cancelled nor has it ever started"; + assert initialized.get() == false + || previousTask.task.isSkipped() + || previousTask.task.hasStarted() : "task that we are replacing is neither " + "cancelled nor has it ever started"; } } diff --git a/client/sniffer/src/test/java/org/opensearch/client/sniff/OpenSearchNodesSnifferParseTests.java b/client/sniffer/src/test/java/org/opensearch/client/sniff/OpenSearchNodesSnifferParseTests.java index 0f6b8ced055..a9ff47eab53 100644 --- a/client/sniffer/src/test/java/org/opensearch/client/sniff/OpenSearchNodesSnifferParseTests.java +++ b/client/sniffer/src/test/java/org/opensearch/client/sniff/OpenSearchNodesSnifferParseTests.java @@ -86,43 +86,50 @@ public class OpenSearchNodesSnifferParseTests extends RestClientTestCase { } public void test2x() throws IOException { - checkFile("2.0.0_nodes_http.json", - node(9200, "m1", "2.0.0", true, false, false), - node(9201, "m2", "2.0.0", true, true, false), - node(9202, "m3", "2.0.0", true, false, false), - node(9203, "d1", "2.0.0", false, true, false), - node(9204, "d2", "2.0.0", false, true, false), - node(9205, "d3", "2.0.0", false, true, false), - node(9206, "c1", "2.0.0", false, false, false), - node(9207, "c2", "2.0.0", false, false, false)); + checkFile( + "2.0.0_nodes_http.json", + node(9200, "m1", "2.0.0", true, false, false), + node(9201, "m2", "2.0.0", true, true, false), + node(9202, "m3", "2.0.0", true, false, false), + node(9203, "d1", "2.0.0", false, true, false), + node(9204, "d2", "2.0.0", false, true, false), + node(9205, "d3", "2.0.0", false, true, false), + node(9206, "c1", "2.0.0", false, false, false), + node(9207, "c2", "2.0.0", false, false, false) + ); } public void test5x() throws IOException { - checkFile("5.0.0_nodes_http.json", - node(9200, "m1", "5.0.0", true, false, true), - node(9201, "m2", "5.0.0", true, true, true), - node(9202, "m3", "5.0.0", true, false, true), - node(9203, "d1", "5.0.0", false, true, true), - node(9204, "d2", "5.0.0", false, true, true), - node(9205, "d3", "5.0.0", false, true, true), - node(9206, "c1", "5.0.0", false, false, true), - node(9207, "c2", "5.0.0", false, false, true)); + checkFile( + "5.0.0_nodes_http.json", + node(9200, "m1", "5.0.0", true, false, true), + node(9201, "m2", "5.0.0", true, true, true), + node(9202, "m3", "5.0.0", true, false, true), + node(9203, "d1", "5.0.0", false, true, true), + node(9204, "d2", "5.0.0", false, true, true), + node(9205, "d3", "5.0.0", false, true, true), + node(9206, "c1", "5.0.0", false, false, true), + node(9207, "c2", "5.0.0", false, false, true) + ); } public void test6x() throws IOException { - checkFile("6.0.0_nodes_http.json", - node(9200, "m1", "6.0.0", true, false, true), - node(9201, "m2", "6.0.0", true, true, true), - node(9202, "m3", "6.0.0", true, false, true), - node(9203, "d1", "6.0.0", false, true, true), - node(9204, "d2", "6.0.0", false, true, true), - node(9205, "d3", "6.0.0", false, true, true), - node(9206, "c1", "6.0.0", false, false, true), - node(9207, "c2", "6.0.0", false, false, true)); + checkFile( + "6.0.0_nodes_http.json", + node(9200, "m1", "6.0.0", true, false, true), + node(9201, "m2", "6.0.0", true, true, true), + node(9202, "m3", "6.0.0", true, false, true), + node(9203, "d1", "6.0.0", false, true, true), + node(9204, "d2", "6.0.0", false, true, true), + node(9205, "d3", "6.0.0", false, true, true), + node(9206, "c1", "6.0.0", false, false, true), + node(9207, "c2", "6.0.0", false, false, true) + ); } public void test7x() throws IOException { - checkFile("7.3.0_nodes_http.json", + checkFile( + "7.3.0_nodes_http.json", node(9200, "m1", "7.3.0", "master", "ingest"), node(9201, "m2", "7.3.0", "master", "data", "ingest"), node(9202, "m3", "7.3.0", "master", "ingest"), @@ -130,7 +137,8 @@ public class OpenSearchNodesSnifferParseTests extends RestClientTestCase { node(9204, "d2", "7.3.0", "data", "ingest"), node(9205, "d3", "7.3.0", "data", "ingest"), node(9206, "c1", "7.3.0", "ingest"), - node(9207, "c2", "7.3.0", "ingest")); + node(9207, "c2", "7.3.0", "ingest") + ); } public void testParsingPublishAddressWithPreES7Format() throws IOException { diff --git a/client/sniffer/src/test/java/org/opensearch/client/sniff/OpenSearchNodesSnifferTests.java b/client/sniffer/src/test/java/org/opensearch/client/sniff/OpenSearchNodesSnifferTests.java index 38ef722d5c3..993844524c2 100644 --- a/client/sniffer/src/test/java/org/opensearch/client/sniff/OpenSearchNodesSnifferTests.java +++ b/client/sniffer/src/test/java/org/opensearch/client/sniff/OpenSearchNodesSnifferTests.java @@ -102,7 +102,7 @@ public class OpenSearchNodesSnifferTests extends RestClientTestCase { try { new OpenSearchNodesSniffer(null, 1, OpenSearchNodesSniffer.Scheme.HTTP); fail("should have failed"); - } catch(NullPointerException e) { + } catch (NullPointerException e) { assertEquals("restClient cannot be null", e.getMessage()); } HttpHost httpHost = new HttpHost(httpServer.getAddress().getHostString(), httpServer.getAddress().getPort()); @@ -114,8 +114,11 @@ public class OpenSearchNodesSnifferTests extends RestClientTestCase { assertEquals(e.getMessage(), "scheme cannot be null"); } try { - new OpenSearchNodesSniffer(restClient, RandomNumbers.randomIntBetween(getRandom(), Integer.MIN_VALUE, 0), - OpenSearchNodesSniffer.Scheme.HTTP); + new OpenSearchNodesSniffer( + restClient, + RandomNumbers.randomIntBetween(getRandom(), Integer.MIN_VALUE, 0), + OpenSearchNodesSniffer.Scheme.HTTP + ); fail("should have failed"); } catch (IllegalArgumentException e) { assertEquals(e.getMessage(), "sniffRequestTimeoutMillis must be greater than 0"); @@ -133,17 +136,22 @@ public class OpenSearchNodesSnifferTests extends RestClientTestCase { fail("sniffNodes should have failed"); } assertEquals(sniffResponse.result, sniffedNodes); - } catch(ResponseException e) { + } catch (ResponseException e) { Response response = e.getResponse(); if (sniffResponse.isFailure) { - final String errorPrefix = "method [GET], host [" + httpHost + "], URI [/_nodes/http?timeout=" + sniffRequestTimeout + final String errorPrefix = "method [GET], host [" + + httpHost + + "], URI [/_nodes/http?timeout=" + + sniffRequestTimeout + "ms], status line [HTTP/1.1"; assertThat(e.getMessage(), startsWith(errorPrefix)); assertThat(e.getMessage(), containsString(Integer.toString(sniffResponse.nodesInfoResponseCode))); assertThat(response.getHost(), equalTo(httpHost)); assertThat(response.getStatusLine().getStatusCode(), equalTo(sniffResponse.nodesInfoResponseCode)); - assertThat(response.getRequestLine().toString(), - equalTo("GET /_nodes/http?timeout=" + sniffRequestTimeout + "ms HTTP/1.1")); + assertThat( + response.getRequestLine().toString(), + equalTo("GET /_nodes/http?timeout=" + sniffRequestTimeout + "ms HTTP/1.1") + ); } else { fail("sniffNodes should have succeeded: " + response.getStatusLine()); } @@ -235,10 +243,14 @@ public class OpenSearchNodesSnifferTests extends RestClientTestCase { nodeRoles.add("ingest"); } - Node node = new Node(publishHost, boundHosts, randomAsciiAlphanumOfLength(5), - randomAsciiAlphanumOfLength(5), - new Node.Roles(nodeRoles), - attributes); + Node node = new Node( + publishHost, + boundHosts, + randomAsciiAlphanumOfLength(5), + randomAsciiAlphanumOfLength(5), + new Node.Roles(nodeRoles), + attributes + ); generator.writeObjectFieldStart(nodeId); if (getRandom().nextBoolean()) { @@ -271,7 +283,7 @@ public class OpenSearchNodesSnifferTests extends RestClientTestCase { generator.writeEndObject(); } - List roles = Arrays.asList(new String[] {"master", "data", "ingest"}); + List roles = Arrays.asList(new String[] { "master", "data", "ingest" }); Collections.shuffle(roles, getRandom()); generator.writeArrayFieldStart("roles"); for (String role : roles) { diff --git a/client/sniffer/src/test/java/org/opensearch/client/sniff/SniffOnFailureListenerTests.java b/client/sniffer/src/test/java/org/opensearch/client/sniff/SniffOnFailureListenerTests.java index 6403551d593..e4d1058282f 100644 --- a/client/sniffer/src/test/java/org/opensearch/client/sniff/SniffOnFailureListenerTests.java +++ b/client/sniffer/src/test/java/org/opensearch/client/sniff/SniffOnFailureListenerTests.java @@ -48,14 +48,14 @@ public class SniffOnFailureListenerTests extends RestClientTestCase { try { listener.onFailure(null); fail("should have failed"); - } catch(IllegalStateException e) { + } catch (IllegalStateException e) { assertEquals("sniffer was not set, unable to sniff on failure", e.getMessage()); } try { listener.setSniffer(null); fail("should have failed"); - } catch(NullPointerException e) { + } catch (NullPointerException e) { assertEquals("sniffer must not be null", e.getMessage()); } @@ -65,7 +65,7 @@ public class SniffOnFailureListenerTests extends RestClientTestCase { try { listener.setSniffer(sniffer); fail("should have failed"); - } catch(IllegalStateException e) { + } catch (IllegalStateException e) { assertEquals("sniffer can only be set once", e.getMessage()); } listener.onFailure(new Node(new HttpHost("localhost", 9200))); diff --git a/client/sniffer/src/test/java/org/opensearch/client/sniff/SnifferBuilderTests.java b/client/sniffer/src/test/java/org/opensearch/client/sniff/SnifferBuilderTests.java index a5a23616973..25a3162e238 100644 --- a/client/sniffer/src/test/java/org/opensearch/client/sniff/SnifferBuilderTests.java +++ b/client/sniffer/src/test/java/org/opensearch/client/sniff/SnifferBuilderTests.java @@ -54,33 +54,31 @@ public class SnifferBuilderTests extends RestClientTestCase { try { Sniffer.builder(null).build(); fail("should have failed"); - } catch(NullPointerException e) { + } catch (NullPointerException e) { assertEquals("restClient cannot be null", e.getMessage()); } try { Sniffer.builder(client).setSniffIntervalMillis(RandomNumbers.randomIntBetween(getRandom(), Integer.MIN_VALUE, 0)); fail("should have failed"); - } catch(IllegalArgumentException e) { + } catch (IllegalArgumentException e) { assertEquals("sniffIntervalMillis must be greater than 0", e.getMessage()); } try { Sniffer.builder(client).setSniffAfterFailureDelayMillis(RandomNumbers.randomIntBetween(getRandom(), Integer.MIN_VALUE, 0)); fail("should have failed"); - } catch(IllegalArgumentException e) { + } catch (IllegalArgumentException e) { assertEquals("sniffAfterFailureDelayMillis must be greater than 0", e.getMessage()); } - try { Sniffer.builder(client).setNodesSniffer(null); fail("should have failed"); - } catch(NullPointerException e) { + } catch (NullPointerException e) { assertEquals("nodesSniffer cannot be null", e.getMessage()); } - try (Sniffer sniffer = Sniffer.builder(client).build()) { assertNotNull(sniffer); } diff --git a/client/sniffer/src/test/java/org/opensearch/client/sniff/SnifferTests.java b/client/sniffer/src/test/java/org/opensearch/client/sniff/SnifferTests.java index 871ba76256e..41a2c111967 100644 --- a/client/sniffer/src/test/java/org/opensearch/client/sniff/SnifferTests.java +++ b/client/sniffer/src/test/java/org/opensearch/client/sniff/SnifferTests.java @@ -104,7 +104,7 @@ public class SnifferTests extends RestClientTestCase { }; CountingNodesSniffer nodesSniffer = new CountingNodesSniffer(); int iters = randomIntBetween(5, 30); - try (Sniffer sniffer = new Sniffer(restClient, nodesSniffer, noOpScheduler, 1000L, -1)){ + try (Sniffer sniffer = new Sniffer(restClient, nodesSniffer, noOpScheduler, 1000L, -1)) { { assertEquals(1, restClient.getNodes().size()); Node node = restClient.getNodes().get(0); @@ -131,7 +131,7 @@ public class SnifferTests extends RestClientTestCase { assertEquals(expectedNodes, restClient.getNodes()); lastNodes = restClient.getNodes(); } - } catch(IOException e) { + } catch (IOException e) { if (nodesSniffer.failures.get() > failures) { failures++; assertEquals("communication breakdown", e.getMessage()); @@ -171,11 +171,11 @@ public class SnifferTests extends RestClientTestCase { assertEquals(sniffInterval, task.nextTaskDelay); int numberOfRuns = runs.getAndDecrement(); if (numberOfRuns == iters) { - //the first call is to schedule the first sniff round from the Sniffer constructor, with delay O + // the first call is to schedule the first sniff round from the Sniffer constructor, with delay O assertEquals(0L, delayMillis); assertEquals(sniffInterval, task.nextTaskDelay); } else { - //all of the subsequent times "schedule" is called with delay set to the configured sniff interval + // all of the subsequent times "schedule" is called with delay set to the configured sniff interval assertEquals(sniffInterval, delayMillis); assertEquals(sniffInterval, task.nextTaskDelay); if (numberOfRuns == 0) { @@ -183,7 +183,7 @@ public class SnifferTests extends RestClientTestCase { return null; } } - //we submit rather than scheduling to make the test quick and not depend on time + // we submit rather than scheduling to make the test quick and not depend on time Future future = executor.submit(task); futures.add(future); if (numberOfRuns == 1) { @@ -195,15 +195,15 @@ public class SnifferTests extends RestClientTestCase { @Override public void shutdown() { - //the executor is closed externally, shutdown is tested separately + // the executor is closed externally, shutdown is tested separately } }; try { new Sniffer(restClient, nodesSniffer, scheduler, sniffInterval, sniffAfterFailureDelay); assertTrue("timeout waiting for sniffing rounds to be completed", completionLatch.await(1000, TimeUnit.MILLISECONDS)); assertEquals(iters, futures.size()); - //the last future is the only one that may not be completed yet, as the count down happens - //while scheduling the next round which is still part of the execution of the runnable itself. + // the last future is the only one that may not be completed yet, as the count down happens + // while scheduling the next round which is still part of the execution of the runnable itself. assertTrue(lastTask.get().hasStarted()); lastFuture.get().get(); for (Future future : futures) { @@ -236,7 +236,7 @@ public class SnifferTests extends RestClientTestCase { @Override public Future schedule(Sniffer.Task task, long delayMillis) { if (initialized.compareAndSet(false, true)) { - //run from the same thread so the sniffer gets for sure initialized and the scheduled task gets cancelled on close + // run from the same thread so the sniffer gets for sure initialized and the scheduled task gets cancelled on close task.run(); } return future; @@ -272,8 +272,7 @@ public class SnifferTests extends RestClientTestCase { } @Override - public void shutdown() { - } + public void shutdown() {} }; Sniffer sniffer = new Sniffer(restClient, nodesSniffer, scheduler, sniffInterval, sniffAfterFailureDelay); @@ -320,8 +319,8 @@ public class SnifferTests extends RestClientTestCase { try { task.run(); } finally { - //we need to make sure that the sniffer is initialized, so the sniffOnFailure - //call does what it needs to do. Otherwise nothing happens until initialized. + // we need to make sure that the sniffer is initialized, so the sniffOnFailure + // call does what it needs to do. Otherwise nothing happens until initialized. initializingLatch.countDown(); } } @@ -362,8 +361,7 @@ public class SnifferTests extends RestClientTestCase { } @Override - public void shutdown() { - } + public void shutdown() {} }; final Sniffer sniffer = new Sniffer(restClient, nodesSniffer, scheduler, sniffInterval, sniffAfterFailureDelay); assertTrue("timeout waiting for sniffer to get initialized", initializingLatch.await(1000, TimeUnit.MILLISECONDS)); @@ -371,8 +369,8 @@ public class SnifferTests extends RestClientTestCase { ExecutorService onFailureExecutor = Executors.newFixedThreadPool(randomIntBetween(5, 20)); Set> onFailureFutures = new CopyOnWriteArraySet<>(); try { - //with tasks executing quickly one after each other, it is very likely that the onFailure round gets skipped - //as another round is already running. We retry till enough runs get through as that's what we want to test. + // with tasks executing quickly one after each other, it is very likely that the onFailure round gets skipped + // as another round is already running. We retry till enough runs get through as that's what we want to test. while (onFailureTasks.size() < minNumOnFailureRounds) { onFailureFutures.add(onFailureExecutor.submit(new Runnable() { @Override @@ -443,13 +441,12 @@ public class SnifferTests extends RestClientTestCase { try { task.future.get(); fail("cancellation exception should have been thrown"); - } catch(CancellationException ignore) { - } + } catch (CancellationException ignore) {} return false; } else { try { assertNull(task.future.get()); - } catch(CancellationException ignore) { + } catch (CancellationException ignore) { assertTrue(task.future.isCancelled()); } assertTrue(task.future.isDone()); @@ -468,8 +465,7 @@ public class SnifferTests extends RestClientTestCase { } @Override - public void shutdown() { - } + public void shutdown() {} }; Sniffer sniffer = new Sniffer(restClient, nodesSniffer, noOpScheduler, 0L, 0L); ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); @@ -488,32 +484,32 @@ public class SnifferTests extends RestClientTestCase { boolean skip = scheduledTask.skip(); try { assertNull(future.get()); - } catch(CancellationException ignore) { + } catch (CancellationException ignore) { assertTrue(future.isCancelled()); } if (skip) { - //the task was either cancelled before starting, in which case it will never start (thanks to Future#cancel), - //or skipped, in which case it will run but do nothing (thanks to Task#skip). - //Here we want to make sure that whenever skip returns true, the task either won't run or it won't do anything, - //otherwise we may end up with parallel sniffing tracks given that each task schedules the following one. We need to + // the task was either cancelled before starting, in which case it will never start (thanks to Future#cancel), + // or skipped, in which case it will run but do nothing (thanks to Task#skip). + // Here we want to make sure that whenever skip returns true, the task either won't run or it won't do anything, + // otherwise we may end up with parallel sniffing tracks given that each task schedules the following one. We need to // make sure that onFailure takes scheduling over while at the same time ordinary rounds don't go on. assertFalse(task.hasStarted()); assertTrue(task.isSkipped()); assertTrue(future.isCancelled()); assertTrue(future.isDone()); } else { - //if a future is cancelled when its execution has already started, future#get throws CancellationException before - //completion. The execution continues though so we use a latch to try and wait for the task to be completed. - //Here we want to make sure that whenever skip returns false, the task will be completed, otherwise we may be - //missing to schedule the following round, which means no sniffing will ever happen again besides on failure sniffing. + // if a future is cancelled when its execution has already started, future#get throws CancellationException before + // completion. The execution continues though so we use a latch to try and wait for the task to be completed. + // Here we want to make sure that whenever skip returns false, the task will be completed, otherwise we may be + // missing to schedule the following round, which means no sniffing will ever happen again besides on failure sniffing. assertTrue(wrapper.await()); - //the future may or may not be cancelled but the task has for sure started and completed + // the future may or may not be cancelled but the task has for sure started and completed assertTrue(task.toString(), task.hasStarted()); assertFalse(task.isSkipped()); assertTrue(future.isDone()); } - //subsequent cancel calls return false for sure + // subsequent cancel calls return false for sure int cancelCalls = randomIntBetween(1, 10); for (int j = 0; j < cancelCalls; j++) { assertFalse(scheduledTask.skip()); @@ -569,7 +565,7 @@ public class SnifferTests extends RestClientTestCase { int run = runs.incrementAndGet(); if (rarely()) { failures.incrementAndGet(); - //check that if communication breaks, sniffer keeps on working + // check that if communication breaks, sniffer keeps on working throw new IOException("communication breakdown"); } if (rarely()) { @@ -609,13 +605,14 @@ public class SnifferTests extends RestClientTestCase { ScheduledExecutorService scheduledExecutorService = mock(ScheduledExecutorService.class); final ScheduledFuture mockedFuture = mock(ScheduledFuture.class); - when(scheduledExecutorService.schedule(any(Runnable.class), any(Long.class), any(TimeUnit.class))) - .then(new Answer>() { - @Override - public ScheduledFuture answer(InvocationOnMock invocationOnMock) { - return mockedFuture; - } - }); + when(scheduledExecutorService.schedule(any(Runnable.class), any(Long.class), any(TimeUnit.class))).then( + new Answer>() { + @Override + public ScheduledFuture answer(InvocationOnMock invocationOnMock) { + return mockedFuture; + } + } + ); DefaultScheduler scheduler = new DefaultScheduler(scheduledExecutorService); long delay = randomLongBetween(1, Long.MAX_VALUE); Future future = scheduler.schedule(task, delay); diff --git a/client/test/src/main/java/org/opensearch/client/RestClientTestCase.java b/client/test/src/main/java/org/opensearch/client/RestClientTestCase.java index 128ebb3adb2..2b3e867929e 100644 --- a/client/test/src/main/java/org/opensearch/client/RestClientTestCase.java +++ b/client/test/src/main/java/org/opensearch/client/RestClientTestCase.java @@ -56,13 +56,11 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -@TestMethodProviders({ - JUnit3MethodProvider.class -}) -@SeedDecorators({MixWithSuiteName.class}) // See LUCENE-3995 for rationale. +@TestMethodProviders({ JUnit3MethodProvider.class }) +@SeedDecorators({ MixWithSuiteName.class }) // See LUCENE-3995 for rationale. @ThreadLeakScope(ThreadLeakScope.Scope.SUITE) @ThreadLeakGroup(ThreadLeakGroup.Group.MAIN) -@ThreadLeakAction({ThreadLeakAction.Action.WARN, ThreadLeakAction.Action.INTERRUPT}) +@ThreadLeakAction({ ThreadLeakAction.Action.WARN, ThreadLeakAction.Action.INTERRUPT }) @ThreadLeakZombies(ThreadLeakZombies.Consequence.IGNORE_REMAINING_TESTS) @ThreadLeakLingering(linger = 5000) // 5 sec lingering @TimeoutSuite(millis = 2 * 60 * 60 * 1000) @@ -78,8 +76,12 @@ public abstract class RestClientTestCase extends RandomizedTest { * @param ignoreHeaders header keys to be ignored as they are not part of default nor request headers, yet they * will be part of the actual ones */ - protected static void assertHeaders(final Header[] defaultHeaders, final Header[] requestHeaders, - final Header[] actualHeaders, final Set ignoreHeaders) { + protected static void assertHeaders( + final Header[] defaultHeaders, + final Header[] requestHeaders, + final Header[] actualHeaders, + final Set ignoreHeaders + ) { final Map> expectedHeaders = new HashMap<>(); final Set requestHeaderKeys = new HashSet<>(); for (final Header header : requestHeaders) { diff --git a/client/test/src/main/java/org/opensearch/client/RestClientTestUtil.java b/client/test/src/main/java/org/opensearch/client/RestClientTestUtil.java index 7ca831aefc4..aeba9bde4bf 100644 --- a/client/test/src/main/java/org/opensearch/client/RestClientTestUtil.java +++ b/client/test/src/main/java/org/opensearch/client/RestClientTestUtil.java @@ -45,7 +45,7 @@ import java.util.Random; final class RestClientTestUtil { - private static final String[] HTTP_METHODS = new String[]{"DELETE", "HEAD", "GET", "OPTIONS", "PATCH", "POST", "PUT", "TRACE"}; + private static final String[] HTTP_METHODS = new String[] { "DELETE", "HEAD", "GET", "OPTIONS", "PATCH", "POST", "PUT", "TRACE" }; private static final List ALL_STATUS_CODES; private static final List OK_STATUS_CODES = Arrays.asList(200, 201); private static final List ALL_ERROR_STATUS_CODES; @@ -109,7 +109,7 @@ final class RestClientTestUtil { final Header[] headers = new Header[numHeaders]; for (int i = 0; i < numHeaders; i++) { String headerName = baseName; - //randomly exercise the code path that supports multiple headers with same key + // randomly exercise the code path that supports multiple headers with same key if (random.nextBoolean()) { headerName = headerName + i; } diff --git a/client/transport/src/main/java/org/opensearch/transport/client/PreBuiltTransportClient.java b/client/transport/src/main/java/org/opensearch/transport/client/PreBuiltTransportClient.java index 006003e4722..2584e5453de 100644 --- a/client/transport/src/main/java/org/opensearch/transport/client/PreBuiltTransportClient.java +++ b/client/transport/src/main/java/org/opensearch/transport/client/PreBuiltTransportClient.java @@ -62,7 +62,7 @@ import java.util.concurrent.TimeUnit; * * @deprecated {@link TransportClient} is deprecated in favour of the High Level REST client. */ -@SuppressWarnings({"unchecked","varargs"}) +@SuppressWarnings({ "unchecked", "varargs" }) @Deprecated public class PreBuiltTransportClient extends TransportClient { @@ -98,14 +98,9 @@ public class PreBuiltTransportClient extends TransportClient { } } - private static final Collection> PRE_INSTALLED_PLUGINS = - Collections.unmodifiableList( - Arrays.asList( - Netty4Plugin.class, - ReindexPlugin.class, - PercolatorPlugin.class, - MustachePlugin.class, - ParentJoinPlugin.class)); + private static final Collection> PRE_INSTALLED_PLUGINS = Collections.unmodifiableList( + Arrays.asList(Netty4Plugin.class, ReindexPlugin.class, PercolatorPlugin.class, MustachePlugin.class, ParentJoinPlugin.class) + ); /** * Creates a new transport client with pre-installed plugins. @@ -138,7 +133,8 @@ public class PreBuiltTransportClient extends TransportClient { public PreBuiltTransportClient( Settings settings, Collection> plugins, - HostFailureListener hostFailureListener) { + HostFailureListener hostFailureListener + ) { super(settings, Settings.EMPTY, addPlugins(plugins, PRE_INSTALLED_PLUGINS), hostFailureListener); } diff --git a/client/transport/src/test/java/org/opensearch/transport/client/PreBuiltTransportClientTests.java b/client/transport/src/test/java/org/opensearch/transport/client/PreBuiltTransportClientTests.java index c3137c604f7..8cf0eaaaa5b 100644 --- a/client/transport/src/test/java/org/opensearch/transport/client/PreBuiltTransportClientTests.java +++ b/client/transport/src/test/java/org/opensearch/transport/client/PreBuiltTransportClientTests.java @@ -63,15 +63,20 @@ public class PreBuiltTransportClientTests extends RandomizedTest { @Test public void testInstallPluginTwice() { - for (Class plugin : - Arrays.asList(ParentJoinPlugin.class, ReindexPlugin.class, PercolatorPlugin.class, - MustachePlugin.class)) { + for (Class plugin : Arrays.asList( + ParentJoinPlugin.class, + ReindexPlugin.class, + PercolatorPlugin.class, + MustachePlugin.class + )) { try { new PreBuiltTransportClient(Settings.EMPTY, plugin); fail("exception expected"); } catch (IllegalArgumentException ex) { - assertTrue("Expected message to start with [plugin already exists: ] but was instead [" + ex.getMessage() + "]", - ex.getMessage().startsWith("plugin already exists: ")); + assertTrue( + "Expected message to start with [plugin already exists: ] but was instead [" + ex.getMessage() + "]", + ex.getMessage().startsWith("plugin already exists: ") + ); } } } diff --git a/gradle/formatting.gradle b/gradle/formatting.gradle index b29bc634155..a1f8f9af162 100644 --- a/gradle/formatting.gradle +++ b/gradle/formatting.gradle @@ -57,13 +57,6 @@ import org.opensearch.gradle.BuildPlugin // Do not add new sub-projects here! def projectPathsToExclude = [ - ':client:benchmark', - ':client:client-benchmark-noop-api-plugin', - ':client:rest', - ':client:rest-high-level', - ':client:sniffer', - ':client:test', - ':client:transport', ':example-plugins:custom-settings', ':example-plugins:custom-significance-heuristic', ':example-plugins:custom-suggester',