From 660d9f75a9416e66e73342f8f0e81832c40beebe Mon Sep 17 00:00:00 2001 From: Martijn van Groningen Date: Thu, 31 Mar 2022 13:00:57 +0200 Subject: [PATCH] Remove HLRC IndicesClient and related classes. (#85492) Relates to #83423 --- .../client/ClusterRequestConverters.java | 129 -- .../elasticsearch/client/IndicesClient.java | 2006 ----------------- .../client/IndicesRequestConverters.java | 663 ------ .../client/RequestConverters.java | 13 - .../client/RestHighLevelClient.java | 10 - .../client/indices/AnalyzeRequest.java | 329 --- .../client/indices/AnalyzeResponse.java | 177 -- .../client/indices/CloseIndexRequest.java | 104 - .../client/indices/CloseIndexResponse.java | 217 -- .../ComponentTemplatesExistRequest.java | 29 - .../ComposableIndexTemplateExistRequest.java | 29 - .../indices/CreateDataStreamRequest.java | 27 - .../client/indices/CreateIndexRequest.java | 353 --- .../client/indices/CreateIndexResponse.java | 66 - .../client/indices/DataStream.java | 215 -- .../indices/DataStreamsStatsRequest.java | 24 - .../indices/DataStreamsStatsResponse.java | 225 -- .../client/indices/DeleteAliasRequest.java | 30 - .../DeleteComponentTemplateRequest.java | 24 - .../DeleteComposableIndexTemplateRequest.java | 24 - .../indices/DeleteDataStreamRequest.java | 27 - .../client/indices/DetailAnalyzeResponse.java | 209 -- .../client/indices/FreezeIndexRequest.java | 85 - .../indices/GetComponentTemplatesRequest.java | 69 - .../GetComponentTemplatesResponse.java | 98 - .../GetComposableIndexTemplateRequest.java | 69 - .../GetComposableIndexTemplatesResponse.java | 98 - .../client/indices/GetDataStreamRequest.java | 24 - .../client/indices/GetDataStreamResponse.java | 69 - .../indices/GetFieldMappingsRequest.java | 64 - .../indices/GetFieldMappingsResponse.java | 178 -- .../client/indices/GetIndexRequest.java | 122 - .../client/indices/GetIndexResponse.java | 232 -- .../indices/GetIndexTemplatesRequest.java | 88 - .../indices/GetIndexTemplatesResponse.java | 73 - .../client/indices/GetMappingsRequest.java | 63 - .../client/indices/GetMappingsResponse.java | 59 - .../client/indices/IndexTemplateMetadata.java | 263 --- .../indices/IndexTemplatesExistRequest.java | 39 - .../indices/PutComponentTemplateRequest.java | 89 - .../PutComposableIndexTemplateRequest.java | 89 - .../indices/PutIndexTemplateRequest.java | 423 ---- .../client/indices/PutMappingRequest.java | 141 -- .../indices/ReloadAnalyzersRequest.java | 59 - .../indices/ReloadAnalyzersResponse.java | 103 - .../client/indices/ResizeRequest.java | 171 -- .../client/indices/ResizeResponse.java | 68 - .../indices/SimulateIndexTemplateRequest.java | 66 - .../SimulateIndexTemplateResponse.java | 126 -- .../client/indices/UnfreezeIndexRequest.java | 86 - .../indices/rollover/RolloverRequest.java | 152 -- .../indices/rollover/RolloverResponse.java | 135 -- .../transform/PreviewTransformResponse.java | 10 - .../upgrades/SearchStatesIT.java | 62 +- .../upgrades/QueryBuilderBWCIT.java | 14 +- .../org/elasticsearch/search/CCSDuelIT.java | 20 +- .../cluster/remote/test/RemoteClustersIT.java | 29 +- .../test/rest/ESRestTestCase.java | 84 +- .../xpack/search/AsyncSearchSecurityIT.java | 32 +- .../org/elasticsearch/xpack/ccr/ChainIT.java | 4 +- .../xpack/ccr/FollowIndexIT.java | 16 +- .../xpack/ccr/FollowIndexSecurityIT.java | 10 +- .../xpack/ccr/ESCCRRestTestCase.java | 14 - .../elasticsearch/test/eql/DataLoader.java | 7 +- .../test/eql/EqlRestTestCase.java | 8 +- .../RemoteClusterAwareEqlRestTestCase.java | 2 +- .../xpack/eql/AsyncEqlSecurityIT.java | 22 +- .../xpack/ilm/CCRIndexLifecycleIT.java | 2 +- .../xpack/security/PermissionsIT.java | 9 +- ...stractSearchableSnapshotsRestTestCase.java | 5 - .../security/authc/TokenAuthIntegTests.java | 6 +- .../qa/jdbc/ResultSetMetaDataTestCase.java | 2 +- .../xpack/sql/qa/jdbc/ResultSetTestCase.java | 58 +- .../sql/qa/multi_node/RestSqlMultinodeIT.java | 6 +- .../qa/security/RestSqlSecurityAsyncIT.java | 10 +- .../xpack/sql/qa/security/UserFunctionIT.java | 4 +- .../sql/qa/jdbc/JdbcIntegrationTestCase.java | 2 +- .../xpack/sql/qa/jdbc/SysColumnsTestCase.java | 2 +- .../sql/qa/rest/BaseRestSqlTestCase.java | 4 +- .../xpack/sql/qa/rest/RestSqlTestCase.java | 4 +- .../sql/qa/rest/RestSqlUsageTestCase.java | 5 +- .../elasticsearch/multi_node/RollupIT.java | 49 +- .../xpack/security/ReindexWithSecurityIT.java | 17 +- .../oldrepos/OldRepositoryAccessIT.java | 52 +- .../upgrades/CcrRollingUpgradeIT.java | 10 - .../upgrades/MlTrainedModelsUpgradeIT.java | 4 +- .../upgrades/TransformSurvivesUpgradeIT.java | 4 +- .../SmokeTestMonitoringWithSecurityIT.java | 15 +- 88 files changed, 271 insertions(+), 8664 deletions(-) delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/ClusterRequestConverters.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/IndicesClient.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/IndicesRequestConverters.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/AnalyzeRequest.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/AnalyzeResponse.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/CloseIndexRequest.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/CloseIndexResponse.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/ComponentTemplatesExistRequest.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/ComposableIndexTemplateExistRequest.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/CreateDataStreamRequest.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/CreateIndexRequest.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/CreateIndexResponse.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/DataStream.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/DataStreamsStatsRequest.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/DataStreamsStatsResponse.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/DeleteAliasRequest.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/DeleteComponentTemplateRequest.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/DeleteComposableIndexTemplateRequest.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/DeleteDataStreamRequest.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/DetailAnalyzeResponse.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/FreezeIndexRequest.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetComponentTemplatesRequest.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetComponentTemplatesResponse.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetComposableIndexTemplateRequest.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetComposableIndexTemplatesResponse.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetDataStreamRequest.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetDataStreamResponse.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetFieldMappingsRequest.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetFieldMappingsResponse.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetIndexRequest.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetIndexResponse.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetIndexTemplatesRequest.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetIndexTemplatesResponse.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetMappingsRequest.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetMappingsResponse.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/IndexTemplateMetadata.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/IndexTemplatesExistRequest.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/PutComponentTemplateRequest.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/PutComposableIndexTemplateRequest.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/PutIndexTemplateRequest.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/PutMappingRequest.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/ReloadAnalyzersRequest.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/ReloadAnalyzersResponse.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/ResizeRequest.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/ResizeResponse.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/SimulateIndexTemplateRequest.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/SimulateIndexTemplateResponse.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/UnfreezeIndexRequest.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/rollover/RolloverRequest.java delete mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/indices/rollover/RolloverResponse.java diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/ClusterRequestConverters.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/ClusterRequestConverters.java deleted file mode 100644 index 36d09cfab6f2..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/ClusterRequestConverters.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -package org.elasticsearch.client; - -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpHead; -import org.apache.http.client.methods.HttpPut; -import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest; -import org.elasticsearch.action.admin.cluster.settings.ClusterGetSettingsRequest; -import org.elasticsearch.action.admin.cluster.settings.ClusterUpdateSettingsRequest; -import org.elasticsearch.action.support.ActiveShardCount; -import org.elasticsearch.client.cluster.RemoteInfoRequest; -import org.elasticsearch.client.indices.ComponentTemplatesExistRequest; -import org.elasticsearch.client.indices.DeleteComponentTemplateRequest; -import org.elasticsearch.client.indices.GetComponentTemplatesRequest; -import org.elasticsearch.client.indices.PutComponentTemplateRequest; -import org.elasticsearch.common.Strings; - -import java.io.IOException; - -final class ClusterRequestConverters { - - private ClusterRequestConverters() {} - - static Request clusterPutSettings(ClusterUpdateSettingsRequest clusterUpdateSettingsRequest) throws IOException { - Request request = new Request(HttpPut.METHOD_NAME, "/_cluster/settings"); - - RequestConverters.Params parameters = new RequestConverters.Params(); - parameters.withTimeout(clusterUpdateSettingsRequest.timeout()); - parameters.withMasterTimeout(clusterUpdateSettingsRequest.masterNodeTimeout()); - request.addParameters(parameters.asMap()); - request.setEntity(RequestConverters.createEntity(clusterUpdateSettingsRequest, RequestConverters.REQUEST_BODY_CONTENT_TYPE)); - return request; - } - - static Request clusterGetSettings(ClusterGetSettingsRequest clusterGetSettingsRequest) throws IOException { - Request request = new Request(HttpGet.METHOD_NAME, "/_cluster/settings"); - RequestConverters.Params parameters = new RequestConverters.Params(); - parameters.withLocal(clusterGetSettingsRequest.local()); - parameters.withIncludeDefaults(clusterGetSettingsRequest.includeDefaults()); - parameters.withMasterTimeout(clusterGetSettingsRequest.masterNodeTimeout()); - request.addParameters(parameters.asMap()); - return request; - } - - static Request clusterHealth(ClusterHealthRequest healthRequest) { - String[] indices = healthRequest.indices() == null ? Strings.EMPTY_ARRAY : healthRequest.indices(); - 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()) - .withWaitForNoRelocatingShards(healthRequest.waitForNoRelocatingShards()) - .withWaitForNoInitializingShards(healthRequest.waitForNoInitializingShards()) - .withWaitForActiveShards(healthRequest.waitForActiveShards(), ActiveShardCount.NONE) - .withWaitForNodes(healthRequest.waitForNodes()) - .withWaitForEvents(healthRequest.waitForEvents()) - .withTimeout(healthRequest.timeout()) - .withMasterTimeout(healthRequest.masterNodeTimeout()) - .withLocal(healthRequest.local()) - .withLevel(healthRequest.level()); - request.addParameters(params.asMap()); - return request; - } - - static Request remoteInfo(RemoteInfoRequest remoteInfoRequest) { - return new Request(HttpGet.METHOD_NAME, "/_remote/info"); - } - - static Request putComponentTemplate(PutComponentTemplateRequest putComponentTemplateRequest) throws IOException { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_component_template") - .addPathPart(putComponentTemplateRequest.name()) - .build(); - Request request = new Request(HttpPut.METHOD_NAME, endpoint); - RequestConverters.Params params = new RequestConverters.Params(); - params.withMasterTimeout(putComponentTemplateRequest.masterNodeTimeout()); - if (putComponentTemplateRequest.create()) { - params.putParam("create", Boolean.TRUE.toString()); - } - if (Strings.hasText(putComponentTemplateRequest.cause())) { - params.putParam("cause", putComponentTemplateRequest.cause()); - } - request.addParameters(params.asMap()); - request.setEntity(RequestConverters.createEntity(putComponentTemplateRequest, RequestConverters.REQUEST_BODY_CONTENT_TYPE)); - return request; - } - - 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); - final RequestConverters.Params params = new RequestConverters.Params(); - params.withLocal(getComponentTemplatesRequest.isLocal()); - params.withMasterTimeout(getComponentTemplatesRequest.getMasterNodeTimeout()); - request.addParameters(params.asMap()); - return request; - } - - static Request componentTemplatesExist(ComponentTemplatesExistRequest componentTemplatesRequest) { - final String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_component_template") - .addPathPart(componentTemplatesRequest.name()) - .build(); - final Request request = new Request(HttpHead.METHOD_NAME, endpoint); - final RequestConverters.Params params = new RequestConverters.Params(); - params.withLocal(componentTemplatesRequest.isLocal()); - params.withMasterTimeout(componentTemplatesRequest.getMasterNodeTimeout()); - request.addParameters(params.asMap()); - return request; - } - - static Request deleteComponentTemplate(DeleteComponentTemplateRequest deleteComponentTemplateRequest) { - String name = deleteComponentTemplateRequest.getName(); - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_component_template").addPathPart(name).build(); - Request request = new Request(HttpDelete.METHOD_NAME, endpoint); - RequestConverters.Params params = new RequestConverters.Params(); - params.withMasterTimeout(deleteComponentTemplateRequest.masterNodeTimeout()); - request.addParameters(params.asMap()); - return request; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/IndicesClient.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/IndicesClient.java deleted file mode 100644 index afb876eda139..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/IndicesClient.java +++ /dev/null @@ -1,2006 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -package org.elasticsearch.client; - -import org.elasticsearch.action.ActionListener; -import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest; -import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest; -import org.elasticsearch.action.admin.indices.cache.clear.ClearIndicesCacheRequest; -import org.elasticsearch.action.admin.indices.cache.clear.ClearIndicesCacheResponse; -import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; -import org.elasticsearch.action.admin.indices.flush.FlushRequest; -import org.elasticsearch.action.admin.indices.flush.FlushResponse; -import org.elasticsearch.action.admin.indices.forcemerge.ForceMergeRequest; -import org.elasticsearch.action.admin.indices.forcemerge.ForceMergeResponse; -import org.elasticsearch.action.admin.indices.open.OpenIndexRequest; -import org.elasticsearch.action.admin.indices.open.OpenIndexResponse; -import org.elasticsearch.action.admin.indices.refresh.RefreshRequest; -import org.elasticsearch.action.admin.indices.refresh.RefreshResponse; -import org.elasticsearch.action.admin.indices.settings.get.GetSettingsRequest; -import org.elasticsearch.action.admin.indices.settings.get.GetSettingsResponse; -import org.elasticsearch.action.admin.indices.settings.put.UpdateSettingsRequest; -import org.elasticsearch.action.admin.indices.template.delete.DeleteIndexTemplateRequest; -import org.elasticsearch.action.admin.indices.validate.query.ValidateQueryRequest; -import org.elasticsearch.action.admin.indices.validate.query.ValidateQueryResponse; -import org.elasticsearch.action.support.master.AcknowledgedResponse; -import org.elasticsearch.client.core.ShardsAcknowledgedResponse; -import org.elasticsearch.client.indices.AnalyzeRequest; -import org.elasticsearch.client.indices.AnalyzeResponse; -import org.elasticsearch.client.indices.CloseIndexRequest; -import org.elasticsearch.client.indices.CloseIndexResponse; -import org.elasticsearch.client.indices.ComposableIndexTemplateExistRequest; -import org.elasticsearch.client.indices.CreateDataStreamRequest; -import org.elasticsearch.client.indices.CreateIndexRequest; -import org.elasticsearch.client.indices.CreateIndexResponse; -import org.elasticsearch.client.indices.DataStreamsStatsRequest; -import org.elasticsearch.client.indices.DataStreamsStatsResponse; -import org.elasticsearch.client.indices.DeleteAliasRequest; -import org.elasticsearch.client.indices.DeleteComposableIndexTemplateRequest; -import org.elasticsearch.client.indices.DeleteDataStreamRequest; -import org.elasticsearch.client.indices.FreezeIndexRequest; -import org.elasticsearch.client.indices.GetComposableIndexTemplateRequest; -import org.elasticsearch.client.indices.GetComposableIndexTemplatesResponse; -import org.elasticsearch.client.indices.GetDataStreamRequest; -import org.elasticsearch.client.indices.GetDataStreamResponse; -import org.elasticsearch.client.indices.GetFieldMappingsRequest; -import org.elasticsearch.client.indices.GetFieldMappingsResponse; -import org.elasticsearch.client.indices.GetIndexRequest; -import org.elasticsearch.client.indices.GetIndexResponse; -import org.elasticsearch.client.indices.GetIndexTemplatesRequest; -import org.elasticsearch.client.indices.GetIndexTemplatesResponse; -import org.elasticsearch.client.indices.GetMappingsRequest; -import org.elasticsearch.client.indices.GetMappingsResponse; -import org.elasticsearch.client.indices.IndexTemplatesExistRequest; -import org.elasticsearch.client.indices.PutComposableIndexTemplateRequest; -import org.elasticsearch.client.indices.PutIndexTemplateRequest; -import org.elasticsearch.client.indices.PutMappingRequest; -import org.elasticsearch.client.indices.ReloadAnalyzersRequest; -import org.elasticsearch.client.indices.ReloadAnalyzersResponse; -import org.elasticsearch.client.indices.ResizeRequest; -import org.elasticsearch.client.indices.ResizeResponse; -import org.elasticsearch.client.indices.SimulateIndexTemplateRequest; -import org.elasticsearch.client.indices.SimulateIndexTemplateResponse; -import org.elasticsearch.client.indices.UnfreezeIndexRequest; -import org.elasticsearch.client.indices.rollover.RolloverRequest; -import org.elasticsearch.client.indices.rollover.RolloverResponse; -import org.elasticsearch.rest.RestStatus; - -import java.io.IOException; -import java.util.Collections; - -import static java.util.Collections.emptySet; -import static java.util.Collections.singleton; - -/** - * A wrapper for the {@link RestHighLevelClient} that provides methods for accessing the Indices API. - *

- * See Indices API on elastic.co - * - * @deprecated The High Level Rest Client is deprecated in favor of the - * - * Elasticsearch Java API Client - */ -@Deprecated(since = "7.16.0", forRemoval = true) -@SuppressWarnings("removal") -public final class IndicesClient { - private final RestHighLevelClient restHighLevelClient; - - IndicesClient(RestHighLevelClient restHighLevelClient) { - this.restHighLevelClient = restHighLevelClient; - } - - /** - * Deletes an index using the Delete Index API. - * See - * Delete Index API on elastic.co - * @param deleteIndexRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @return the response - * @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() - ); - } - - /** - * Asynchronously deletes an index using the Delete Index API. - * See - * Delete Index API on elastic.co - * @param deleteIndexRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @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() - ); - } - - /** - * Creates an index using the Create Index API. - * See - * Create Index API on elastic.co - * @param createIndexRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @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() - ); - } - - /** - * Asynchronously creates an index using the Create Index API. - * See - * Create Index API on elastic.co - * @param createIndexRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @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() - ); - } - - /** - * Creates a data stream using the Create Data Stream API. - * See - * Data Streams API on elastic.co - * - * @param createDataStreamRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be - * customized - * @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() - ); - } - - /** - * Asynchronously creates a data stream using the Create Data Stream API. - * See - * Data Streams API on elastic.co - * - * @param createDataStreamRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be - * customized - * @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() - ); - } - - /** - * Deletes a data stream using the Delete Data Stream API. - * See - * Data Streams API on elastic.co - * - * @param deleteDataStreamRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be - * customized - * @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() - ); - } - - /** - * Asynchronously deletes a data stream using the Delete Data Stream API. - * See - * Data Streams API on elastic.co - * - * @param deleteDataStreamRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be - * customized - * @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() - ); - } - - /** - * Gets one or more data streams using the Get Data Stream API. - * See Data Streams API on - * elastic.co - * - * @param dataStreamRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @return the response - * @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() - ); - } - - /** - * Asynchronously gets one or more data streams using the Get Data Stream API. - * See Data Streams API on - * elastic.co - * - * @param dataStreamRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @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() - ); - } - - /** - * Gets statistics about one or more data streams using the Get Data Streams Stats API. - * See Data Streams API on - * elastic.co - * - * @param dataStreamsStatsRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be - * customized - * @return the response - * @throws IOException in case there is a problem sending the request or parsing back the response - */ - public DataStreamsStatsResponse dataStreamsStats(DataStreamsStatsRequest dataStreamsStatsRequest, RequestOptions options) - throws IOException { - return restHighLevelClient.performRequestAndParseEntity( - dataStreamsStatsRequest, - IndicesRequestConverters::dataStreamsStats, - options, - DataStreamsStatsResponse::fromXContent, - emptySet() - ); - } - - /** - * Asynchronously gets statistics about one or more data streams using the Get Data Streams Stats API. - * See Data Streams API on - * elastic.co - * - * @param dataStreamsStatsRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be - * customized - * @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() - ); - } - - /** - * Updates the mappings on an index using the Put Mapping API. - * See - * Put Mapping API on elastic.co - * @param putMappingRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @return the response - * @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() - ); - } - - /** - * Asynchronously updates the mappings on an index using the Put Mapping API. - * See - * Put Mapping API on elastic.co - * @param putMappingRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @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() - ); - } - - /** - * Retrieves the mappings on an index or indices using the Get Mapping API. - * See - * Get Mapping API on elastic.co - * @param getMappingsRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @return the response - * @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, - IndicesRequestConverters::getMappings, - options, - GetMappingsResponse::fromXContent, - emptySet() - ); - } - - /** - * Asynchronously retrieves the mappings on an index on indices using the Get Mapping API. - * See - * Get Mapping API on elastic.co - * @param getMappingsRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @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, - IndicesRequestConverters::getMappings, - options, - GetMappingsResponse::fromXContent, - listener, - emptySet() - ); - } - - /** - * Retrieves the field mappings on an index or indices using the Get Field Mapping API. - * See - * Get Field Mapping API on elastic.co - * @param getFieldMappingsRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @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() - ); - } - - /** - * Asynchronously retrieves the field mappings on an index or indices using the Get Field Mapping API. - * See - * Get Field Mapping API on elastic.co - * @param getFieldMappingsRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @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 - ) { - return restHighLevelClient.performRequestAsyncAndParseEntity( - getFieldMappingsRequest, - IndicesRequestConverters::getFieldMapping, - options, - GetFieldMappingsResponse::fromXContent, - listener, - emptySet() - ); - } - - /** - * Updates aliases using the Index Aliases API. - * See - * Index Aliases API on elastic.co - * @param indicesAliasesRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @return the response - * @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() - ); - } - - /** - * Asynchronously updates aliases using the Index Aliases API. - * See - * Index Aliases API on elastic.co - * @param indicesAliasesRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @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() - ); - } - - /** - * Opens an index using the Open Index API. - * See - * Open Index API on elastic.co - * @param openIndexRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @return the response - * @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() - ); - } - - /** - * Asynchronously opens an index using the Open Index API. - * See - * Open Index API on elastic.co - * @param openIndexRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @param listener the listener to be notified upon request completion - * @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() - ); - } - - /** - * Closes an index using the Close Index API. - * See - * Close Index API on elastic.co - * @param closeIndexRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @return the response - * @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() - ); - } - - /** - * Asynchronously closes an index using the Close Index API. - * See - * Close Index API on elastic.co - * @param closeIndexRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @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() - ); - } - - /** - * Checks if one or more aliases exist using the Aliases Exist API. - * See - * Indices Aliases API on elastic.co - * @param getAliasesRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @return the response - * @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() - ); - } - - /** - * Asynchronously checks if one or more aliases exist using the Aliases Exist API. - * See - * Indices Aliases API on elastic.co - * @param getAliasesRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @param listener the listener to be notified upon request completion - * @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() - ); - } - - /** - * Refresh one or more indices using the Refresh API. - * See Refresh API on elastic.co - * @param refreshRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @return the response - * @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() - ); - } - - /** - * Asynchronously refresh one or more indices using the Refresh API. - * See Refresh API on elastic.co - * @param refreshRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @param listener the listener to be notified upon request completion - * @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() - ); - } - - /** - * Flush one or more indices using the Flush API. - * See Flush API on elastic.co - * @param flushRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @return the response - * @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() - ); - } - - /** - * Asynchronously flush one or more indices using the Flush API. - * See Flush API on elastic.co - * @param flushRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @param listener the listener to be notified upon request completion - * @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() - ); - } - - /** - * Retrieve the settings of one or more indices. - * See - * Indices Get Settings API on elastic.co - * @param getSettingsRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @return the response - * @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() - ); - } - - /** - * Asynchronously retrieve the settings of one or more indices. - * See - * Indices Get Settings API on elastic.co - * @param getSettingsRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @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() - ); - } - - /** - * Retrieve information about one or more indexes - * See - * Indices Get Index API on elastic.co - * @param getIndexRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @return the response - * @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() - ); - } - - /** - * Retrieve information about one or more indexes - * See - * Indices Get Index API on elastic.co - * @param getIndexRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @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() - ); - } - - /** - * Force merge one or more indices using the Force Merge API. - * See - * Force Merge API on elastic.co - * @param forceMergeRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @return the response - * @throws IOException in case there is a problem sending the request or parsing back the response - * @deprecated use {@link #forcemerge(ForceMergeRequest, RequestOptions)} instead - */ - @Deprecated - public ForceMergeResponse forceMerge(ForceMergeRequest forceMergeRequest, RequestOptions options) throws IOException { - return forcemerge(forceMergeRequest, options); - } - - /** - * Force merge one or more indices using the Force Merge API. - * See - * Force Merge API on elastic.co - * @param forceMergeRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @return the response - * @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() - ); - } - - /** - * Asynchronously force merge one or more indices using the Force Merge API. - * See - * Force Merge API on elastic.co - * @param forceMergeRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @param listener the listener to be notified upon request completion - * @deprecated use {@link #forcemergeAsync(ForceMergeRequest, RequestOptions, ActionListener)} instead - * @return cancellable that may be used to cancel the request - */ - @Deprecated - public Cancellable forceMergeAsync( - ForceMergeRequest forceMergeRequest, - RequestOptions options, - ActionListener listener - ) { - return forcemergeAsync(forceMergeRequest, options, listener); - } - - /** - * Asynchronously force merge one or more indices using the Force Merge API. - * See - * Force Merge API on elastic.co - * @param forceMergeRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @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() - ); - } - - /** - * Clears the cache of one or more indices using the Clear Cache API. - * See - * Clear Cache API on elastic.co - * @param clearIndicesCacheRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @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() - ); - } - - /** - * Asynchronously clears the cache of one or more indices using the Clear Cache API. - * See - * Clear Cache API on elastic.co - * @param clearIndicesCacheRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @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() - ); - } - - /** - * Checks if the index (indices) exists or not. - * See - * Indices Exists API on elastic.co - * @param request the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @return the response - * @throws IOException in case there is a problem sending the request - */ - public boolean exists(GetIndexRequest request, RequestOptions options) throws IOException { - return restHighLevelClient.performRequest( - request, - IndicesRequestConverters::indicesExist, - options, - RestHighLevelClient::convertExistsResponse, - Collections.emptySet() - ); - } - - /** - * Asynchronously checks if the index (indices) exists or not. - * See - * Indices Exists API on elastic.co - * @param request the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @param listener the listener to be notified upon request completion - * @return cancellable that may be used to cancel the request - */ - public Cancellable existsAsync(GetIndexRequest request, RequestOptions options, ActionListener listener) { - return restHighLevelClient.performRequestAsync( - request, - IndicesRequestConverters::indicesExist, - options, - RestHighLevelClient::convertExistsResponse, - listener, - Collections.emptySet() - ); - } - - /** - * Shrinks an index using the Shrink Index API. - * See - * Shrink Index API on elastic.co - * @param resizeRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @return the response - * @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() - ); - } - - /** - * Shrinks an index using the Shrink Index API. - * See - * Shrink Index API on elastic.co - * @param resizeRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @return the response - * @throws IOException in case there is a problem sending the request or parsing back the response - * @deprecated use {@link #shrink(ResizeRequest, RequestOptions)} - */ - @Deprecated - public org.elasticsearch.action.admin.indices.shrink.ResizeResponse shrink( - org.elasticsearch.action.admin.indices.shrink.ResizeRequest resizeRequest, - RequestOptions options - ) throws IOException { - return restHighLevelClient.performRequestAndParseEntity( - resizeRequest, - IndicesRequestConverters::shrink, - options, - org.elasticsearch.action.admin.indices.shrink.ResizeResponse::fromXContent, - emptySet() - ); - } - - /** - * Asynchronously shrinks an index using the Shrink index API. - * See - * Shrink Index API on elastic.co - * @param resizeRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @param listener the listener to be notified upon request completion - * @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() - ); - } - - /** - * Asynchronously shrinks an index using the Shrink index API. - * See - * Shrink Index API on elastic.co - * @param resizeRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @param listener the listener to be notified upon request completion - * @return cancellable that may be used to cancel the request - * @deprecated use {@link #shrinkAsync(ResizeRequest, RequestOptions, ActionListener)} - */ - @Deprecated - public Cancellable shrinkAsync( - org.elasticsearch.action.admin.indices.shrink.ResizeRequest resizeRequest, - RequestOptions options, - ActionListener listener - ) { - return restHighLevelClient.performRequestAsyncAndParseEntity( - resizeRequest, - IndicesRequestConverters::shrink, - options, - org.elasticsearch.action.admin.indices.shrink.ResizeResponse::fromXContent, - listener, - emptySet() - ); - } - - /** - * Splits an index using the Split Index API. - * See - * Split Index API on elastic.co - * @param resizeRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @return the response - * @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() - ); - } - - /** - * Splits an index using the Split Index API. - * See - * Split Index API on elastic.co - * @param resizeRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @return the response - * @throws IOException in case there is a problem sending the request or parsing back the response - * @deprecated use {@link #split(ResizeRequest, RequestOptions)} - */ - @Deprecated - public org.elasticsearch.action.admin.indices.shrink.ResizeResponse split( - org.elasticsearch.action.admin.indices.shrink.ResizeRequest resizeRequest, - RequestOptions options - ) throws IOException { - return restHighLevelClient.performRequestAndParseEntity( - resizeRequest, - IndicesRequestConverters::split, - options, - org.elasticsearch.action.admin.indices.shrink.ResizeResponse::fromXContent, - emptySet() - ); - } - - /** - * Asynchronously splits an index using the Split Index API. - * See - * Split Index API on elastic.co - * @param resizeRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @param listener the listener to be notified upon request completion - * @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() - ); - } - - /** - * Asynchronously splits an index using the Split Index API. - * See - * Split Index API on elastic.co - * @param resizeRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @param listener the listener to be notified upon request completion - * @return cancellable that may be used to cancel the request - * @deprecated use {@link #splitAsync(ResizeRequest, RequestOptions, ActionListener)} - */ - @Deprecated - public Cancellable splitAsync( - org.elasticsearch.action.admin.indices.shrink.ResizeRequest resizeRequest, - RequestOptions options, - ActionListener listener - ) { - return restHighLevelClient.performRequestAsyncAndParseEntity( - resizeRequest, - IndicesRequestConverters::split, - options, - org.elasticsearch.action.admin.indices.shrink.ResizeResponse::fromXContent, - listener, - emptySet() - ); - } - - /** - * Clones an index using the Clone Index API. - * See - * Clone Index API on elastic.co - * @param resizeRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @return the response - * @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() - ); - } - - /** - * Clones an index using the Clone Index API. - * See - * Clone Index API on elastic.co - * @param resizeRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @return the response - * @throws IOException in case there is a problem sending the request or parsing back the response - * @deprecated use {@link #clone(ResizeRequest, RequestOptions)} - */ - @Deprecated - public org.elasticsearch.action.admin.indices.shrink.ResizeResponse clone( - org.elasticsearch.action.admin.indices.shrink.ResizeRequest resizeRequest, - RequestOptions options - ) throws IOException { - return restHighLevelClient.performRequestAndParseEntity( - resizeRequest, - IndicesRequestConverters::clone, - options, - org.elasticsearch.action.admin.indices.shrink.ResizeResponse::fromXContent, - emptySet() - ); - } - - /** - * Asynchronously clones an index using the Clone Index API. - * See - * Clone Index API on elastic.co - * @param resizeRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @param listener the listener to be notified upon request completion - * @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() - ); - } - - /** - * Asynchronously clones an index using the Clone Index API. - * See - * Clone Index API on elastic.co - * @param resizeRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @param listener the listener to be notified upon request completion - * @return cancellable that may be used to cancel the request - * @deprecated use {@link #cloneAsync(ResizeRequest, RequestOptions, ActionListener)} - */ - @Deprecated - public Cancellable cloneAsync( - org.elasticsearch.action.admin.indices.shrink.ResizeRequest resizeRequest, - RequestOptions options, - ActionListener listener - ) { - return restHighLevelClient.performRequestAsyncAndParseEntity( - resizeRequest, - IndicesRequestConverters::clone, - options, - org.elasticsearch.action.admin.indices.shrink.ResizeResponse::fromXContent, - listener, - emptySet() - ); - } - - /** - * Rolls over an index using the Rollover Index API. - * See - * Rollover Index API on elastic.co - * @param rolloverRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @return the response - * @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() - ); - } - - /** - * Asynchronously rolls over an index using the Rollover Index API. - * See - * Rollover Index API on elastic.co - * @param rolloverRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @param listener the listener to be notified upon request completion - * @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() - ); - } - - /** - * Gets one or more aliases using the Get Index Aliases API. - * See Indices Aliases API on - * elastic.co - * @param getAliasesRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @return the response - * @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()) - ); - } - - /** - * Asynchronously gets one or more aliases using the Get Index Aliases API. - * See Indices Aliases API on - * elastic.co - * @param getAliasesRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @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()) - ); - } - - /** - * Updates specific index level settings using the Update Indices Settings API. - * See Update Indices Settings - * API on elastic.co - * @param updateSettingsRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @return the response - * @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() - ); - } - - /** - * Asynchronously updates specific index level settings using the Update Indices Settings API. - * See Update Indices Settings - * API on elastic.co - * @param updateSettingsRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @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() - ); - } - - /** - * Puts an index template using the Index Templates API. - * See Index Templates API - * on elastic.co - * @param putIndexTemplateRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @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() - ); - } - - /** - * Asynchronously puts an index template using the Index Templates API. - * See Index Templates API - * on elastic.co - * @param putIndexTemplateRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @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() - ); - } - - /** - * Puts an index template using the Index Templates API. - * See Index Templates API - * on elastic.co - * @param putIndexTemplateRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @return the response - * @throws IOException in case there is a problem sending the request or parsing back the response - */ - public AcknowledgedResponse putIndexTemplate(PutComposableIndexTemplateRequest putIndexTemplateRequest, RequestOptions options) - throws IOException { - return restHighLevelClient.performRequestAndParseEntity( - putIndexTemplateRequest, - IndicesRequestConverters::putIndexTemplate, - options, - AcknowledgedResponse::fromXContent, - emptySet() - ); - } - - /** - * Asynchronously puts an index template using the Index Templates API. - * See Index Templates API - * on elastic.co - * @param putIndexTemplateRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @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() - ); - } - - /** - * Simulates matching index name against the existing index templates in the system. - * See Index Templates API - * on elastic.co - * - * @param simulateIndexTemplateRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be - * customized - * @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() - ); - } - - /** - * Asynchronously simulates matching index name against the existing index templates in the system. - * See Index Templates API - * on elastic.co - * - * @param simulateIndexTemplateRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be - * customized - * @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() - ); - } - - /** - * Validate a potentially expensive query without executing it. - *

- * See Validate Query API - * on elastic.co - * @param validateQueryRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @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() - ); - } - - /** - * Asynchronously validate a potentially expensive query without executing it. - *

- * See Validate Query API - * on elastic.co - * @param validateQueryRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @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() - ); - } - - /** - * Gets index templates using the Index Templates API - * See Index Templates API - * on elastic.co - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @param getIndexTemplatesRequest the request - * @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() - ); - } - - /** - * Asynchronously gets index templates using the Index Templates API - * See Index Templates API - * on elastic.co - * @param getIndexTemplatesRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @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() - ); - } - - /** - * Gets index templates using the Index Templates API - * See Index Templates API - * on elastic.co - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @param getIndexTemplatesRequest the request - * @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, - IndicesRequestConverters::getTemplates, - options, - GetIndexTemplatesResponse::fromXContent, - emptySet() - ); - } - - /** - * Asynchronously gets index templates using the Index Templates API - * See Index Templates API - * on elastic.co - * @param getIndexTemplatesRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @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, - IndicesRequestConverters::getTemplates, - options, - GetIndexTemplatesResponse::fromXContent, - listener, - emptySet() - ); - } - - /** - * Uses the Index Templates API to determine if index templates exist - * - * @param indexTemplatesRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @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() - ); - } - - /** - * Uses the Index Templates API to determine if index templates exist - * @param indexTemplatesExistRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @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 - ) { - - return restHighLevelClient.performRequestAsync( - indexTemplatesExistRequest, - IndicesRequestConverters::templatesExist, - options, - RestHighLevelClient::convertExistsResponse, - listener, - emptySet() - ); - } - - /** - * Uses the Index Templates API to determine if index templates exist - * - * @param indexTemplatesRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @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() - ); - } - - /** - * Uses the Index Templates API to determine if index templates exist - * @param indexTemplatesExistRequest the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @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 - ) { - - return restHighLevelClient.performRequestAsync( - indexTemplatesExistRequest, - IndicesRequestConverters::templatesExist, - options, - RestHighLevelClient::convertExistsResponse, - listener, - emptySet() - ); - } - - /** - * Calls the analyze API - * - * See Analyze API on elastic.co - * - * @param request the request - * @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() - ); - } - - /** - * Asynchronously calls the analyze API - * - * See Analyze API on elastic.co - * @param request the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @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() - ); - } - - /** - * Synchronously calls the _freeze API - * - * @param request the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - */ - public ShardsAcknowledgedResponse freeze(FreezeIndexRequest request, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity( - request, - IndicesRequestConverters::freezeIndex, - options, - ShardsAcknowledgedResponse::fromXContent, - emptySet() - ); - } - - /** - * Asynchronously calls the _freeze API - * @param request the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @param listener the listener to be notified upon request completion - * @return cancellable that may be used to cancel the request - */ - public Cancellable freezeAsync( - FreezeIndexRequest request, - RequestOptions options, - ActionListener listener - ) { - return restHighLevelClient.performRequestAsyncAndParseEntity( - request, - IndicesRequestConverters::freezeIndex, - options, - ShardsAcknowledgedResponse::fromXContent, - listener, - emptySet() - ); - } - - /** - * Synchronously calls the _unfreeze API - * - * @param request the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - */ - public ShardsAcknowledgedResponse unfreeze(UnfreezeIndexRequest request, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity( - request, - IndicesRequestConverters::unfreezeIndex, - options, - ShardsAcknowledgedResponse::fromXContent, - emptySet() - ); - } - - /** - * Asynchronously calls the _unfreeze API - * @param request the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @param listener the listener to be notified upon request completion - * @return cancellable that may be used to cancel the request - */ - public Cancellable unfreezeAsync( - UnfreezeIndexRequest request, - RequestOptions options, - ActionListener listener - ) { - return restHighLevelClient.performRequestAsyncAndParseEntity( - request, - IndicesRequestConverters::unfreezeIndex, - options, - ShardsAcknowledgedResponse::fromXContent, - listener, - emptySet() - ); - } - - /** - * Delete an index template using the Index Templates API - * See Index Templates API - * on elastic.co - * - * @param request the request - * @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 deleteTemplate(DeleteIndexTemplateRequest request, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity( - request, - IndicesRequestConverters::deleteTemplate, - options, - AcknowledgedResponse::fromXContent, - emptySet() - ); - } - - /** - * Asynchronously delete an index template using the Index Templates API - * See Index Templates API - * on elastic.co - * @param request the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @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() - ); - } - - /** - * Delete an index template using the Index Templates API - * See Index Templates API - * on elastic.co - * - * @param request the request - * @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() - ); - } - - /** - * Asynchronously delete an index template using the Index Templates API - * See Index Templates API - * on elastic.co - * @param request the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @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() - ); - } - - /** - * Synchronously calls the _reload_search_analyzers API - * - * @param request the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - */ - public ReloadAnalyzersResponse reloadAnalyzers(ReloadAnalyzersRequest request, RequestOptions options) throws IOException { - return restHighLevelClient.performRequestAndParseEntity( - request, - IndicesRequestConverters::reloadAnalyzers, - options, - ReloadAnalyzersResponse::fromXContent, - emptySet() - ); - } - - /** - * Asynchronously calls the _reload_search_analyzers API - * @param request the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @param listener the listener to be notified upon request completion - * @return cancellable that may be used to cancel the request - */ - public Cancellable reloadAnalyzersAsync( - ReloadAnalyzersRequest request, - RequestOptions options, - ActionListener listener - ) { - return restHighLevelClient.performRequestAsyncAndParseEntity( - request, - IndicesRequestConverters::reloadAnalyzers, - options, - ReloadAnalyzersResponse::fromXContent, - listener, - emptySet() - ); - } - - /** - * Synchronously calls the delete alias api - * @param request the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - */ - public org.elasticsearch.client.core.AcknowledgedResponse deleteAlias(DeleteAliasRequest request, RequestOptions options) - throws IOException { - return restHighLevelClient.performRequestAndParseEntity( - request, - IndicesRequestConverters::deleteAlias, - options, - org.elasticsearch.client.core.AcknowledgedResponse::fromXContent, - emptySet() - ); - } - - /** - * Asynchronously calls the delete alias api - * @param request the request - * @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized - * @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.elasticsearch.client.core.AcknowledgedResponse::fromXContent, - listener, - emptySet() - ); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/IndicesRequestConverters.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/IndicesRequestConverters.java deleted file mode 100644 index f08a458083dc..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/IndicesRequestConverters.java +++ /dev/null @@ -1,663 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -package org.elasticsearch.client; - -import org.apache.http.client.methods.HttpDelete; -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.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest; -import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest; -import org.elasticsearch.action.admin.indices.cache.clear.ClearIndicesCacheRequest; -import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; -import org.elasticsearch.action.admin.indices.flush.FlushRequest; -import org.elasticsearch.action.admin.indices.forcemerge.ForceMergeRequest; -import org.elasticsearch.action.admin.indices.open.OpenIndexRequest; -import org.elasticsearch.action.admin.indices.refresh.RefreshRequest; -import org.elasticsearch.action.admin.indices.settings.get.GetSettingsRequest; -import org.elasticsearch.action.admin.indices.settings.put.UpdateSettingsRequest; -import org.elasticsearch.action.admin.indices.shrink.ResizeType; -import org.elasticsearch.action.admin.indices.template.delete.DeleteIndexTemplateRequest; -import org.elasticsearch.action.admin.indices.validate.query.ValidateQueryRequest; -import org.elasticsearch.action.support.broadcast.BroadcastRequest; -import org.elasticsearch.client.indices.AnalyzeRequest; -import org.elasticsearch.client.indices.CloseIndexRequest; -import org.elasticsearch.client.indices.ComposableIndexTemplateExistRequest; -import org.elasticsearch.client.indices.CreateDataStreamRequest; -import org.elasticsearch.client.indices.CreateIndexRequest; -import org.elasticsearch.client.indices.DataStreamsStatsRequest; -import org.elasticsearch.client.indices.DeleteAliasRequest; -import org.elasticsearch.client.indices.DeleteComposableIndexTemplateRequest; -import org.elasticsearch.client.indices.DeleteDataStreamRequest; -import org.elasticsearch.client.indices.FreezeIndexRequest; -import org.elasticsearch.client.indices.GetComposableIndexTemplateRequest; -import org.elasticsearch.client.indices.GetDataStreamRequest; -import org.elasticsearch.client.indices.GetFieldMappingsRequest; -import org.elasticsearch.client.indices.GetIndexRequest; -import org.elasticsearch.client.indices.GetIndexTemplatesRequest; -import org.elasticsearch.client.indices.GetMappingsRequest; -import org.elasticsearch.client.indices.IndexTemplatesExistRequest; -import org.elasticsearch.client.indices.PutComposableIndexTemplateRequest; -import org.elasticsearch.client.indices.PutIndexTemplateRequest; -import org.elasticsearch.client.indices.PutMappingRequest; -import org.elasticsearch.client.indices.ReloadAnalyzersRequest; -import org.elasticsearch.client.indices.ResizeRequest; -import org.elasticsearch.client.indices.SimulateIndexTemplateRequest; -import org.elasticsearch.client.indices.UnfreezeIndexRequest; -import org.elasticsearch.client.indices.rollover.RolloverRequest; -import org.elasticsearch.cluster.metadata.IndexMetadata; -import org.elasticsearch.common.Strings; - -import java.io.IOException; -import java.util.Locale; - -final class IndicesRequestConverters { - - private IndicesRequestConverters() {} - - static Request putDataStream(CreateDataStreamRequest createDataStreamRequest) { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_data_stream") - .addPathPart(createDataStreamRequest.getName()) - .build(); - Request request = new Request(HttpPut.METHOD_NAME, endpoint); - return request; - } - - static Request deleteDataStream(DeleteDataStreamRequest deleteDataStreamRequest) { - String name = deleteDataStreamRequest.getName(); - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_data_stream").addPathPart(name).build(); - Request request = new Request(HttpDelete.METHOD_NAME, endpoint); - return request; - } - - static Request getDataStreams(GetDataStreamRequest dataStreamRequest) { - final String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_data_stream") - .addPathPart(dataStreamRequest.getName()) - .build(); - return new Request(HttpGet.METHOD_NAME, endpoint); - } - - static Request dataStreamsStats(DataStreamsStatsRequest dataStreamsStatsRequest) { - String[] expressions = dataStreamsStatsRequest.indices() == null ? Strings.EMPTY_ARRAY : dataStreamsStatsRequest.indices(); - final String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_data_stream") - .addCommaSeparatedPathParts(expressions) - .addPathPartAsIs("_stats") - .build(); - return new Request(HttpGet.METHOD_NAME, endpoint); - } - - static Request deleteIndex(DeleteIndexRequest deleteIndexRequest) { - String endpoint = RequestConverters.endpoint(deleteIndexRequest.indices()); - Request request = new Request(HttpDelete.METHOD_NAME, endpoint); - - RequestConverters.Params parameters = new RequestConverters.Params(); - parameters.withTimeout(deleteIndexRequest.timeout()); - parameters.withMasterTimeout(deleteIndexRequest.masterNodeTimeout()); - if (DeleteIndexRequest.DEFAULT_INDICES_OPTIONS.equals(deleteIndexRequest.indicesOptions()) == false) { - parameters.withIndicesOptions(deleteIndexRequest.indicesOptions()); - } - request.addParameters(parameters.asMap()); - return request; - } - - static Request openIndex(OpenIndexRequest openIndexRequest) { - String endpoint = RequestConverters.endpoint(openIndexRequest.indices(), "_open"); - Request request = new Request(HttpPost.METHOD_NAME, endpoint); - - RequestConverters.Params parameters = new RequestConverters.Params(); - parameters.withTimeout(openIndexRequest.timeout()); - parameters.withMasterTimeout(openIndexRequest.masterNodeTimeout()); - parameters.withWaitForActiveShards(openIndexRequest.waitForActiveShards()); - if (OpenIndexRequest.DEFAULT_INDICES_OPTIONS.equals(openIndexRequest.indicesOptions()) == false) { - parameters.withIndicesOptions(openIndexRequest.indicesOptions()); - } - request.addParameters(parameters.asMap()); - return request; - } - - static Request closeIndex(CloseIndexRequest closeIndexRequest) { - String endpoint = RequestConverters.endpoint(closeIndexRequest.indices(), "_close"); - Request request = new Request(HttpPost.METHOD_NAME, endpoint); - - RequestConverters.Params parameters = new RequestConverters.Params(); - parameters.withTimeout(closeIndexRequest.timeout()); - parameters.withMasterTimeout(closeIndexRequest.masterNodeTimeout()); - if (CloseIndexRequest.DEFAULT_INDICES_OPTIONS.equals(closeIndexRequest.indicesOptions()) == false) { - parameters.withIndicesOptions(closeIndexRequest.indicesOptions()); - } - parameters.withWaitForActiveShards(closeIndexRequest.waitForActiveShards()); - request.addParameters(parameters.asMap()); - return request; - } - - static Request createIndex(CreateIndexRequest createIndexRequest) throws IOException { - String endpoint = new RequestConverters.EndpointBuilder().addPathPart(createIndexRequest.index()).build(); - Request request = new Request(HttpPut.METHOD_NAME, endpoint); - - RequestConverters.Params parameters = new RequestConverters.Params(); - parameters.withTimeout(createIndexRequest.timeout()); - parameters.withMasterTimeout(createIndexRequest.masterNodeTimeout()); - parameters.withWaitForActiveShards(createIndexRequest.waitForActiveShards()); - request.addParameters(parameters.asMap()); - request.setEntity(RequestConverters.createEntity(createIndexRequest, RequestConverters.REQUEST_BODY_CONTENT_TYPE)); - return request; - } - - static Request updateAliases(IndicesAliasesRequest indicesAliasesRequest) throws IOException { - Request request = new Request(HttpPost.METHOD_NAME, "/_aliases"); - - RequestConverters.Params parameters = new RequestConverters.Params(); - parameters.withTimeout(indicesAliasesRequest.timeout()); - parameters.withMasterTimeout(indicesAliasesRequest.masterNodeTimeout()); - request.addParameters(parameters.asMap()); - request.setEntity(RequestConverters.createEntity(indicesAliasesRequest, RequestConverters.REQUEST_BODY_CONTENT_TYPE)); - return request; - } - - static Request putMapping(PutMappingRequest putMappingRequest) throws IOException { - Request request = new Request(HttpPut.METHOD_NAME, RequestConverters.endpoint(putMappingRequest.indices(), "_mapping")); - - RequestConverters.Params parameters = new RequestConverters.Params(); - parameters.withTimeout(putMappingRequest.timeout()); - parameters.withMasterTimeout(putMappingRequest.masterNodeTimeout()); - if (PutMappingRequest.DEFAULT_INDICES_OPTIONS.equals(putMappingRequest.indicesOptions()) == false) { - parameters.withIndicesOptions(putMappingRequest.indicesOptions()); - } - request.addParameters(parameters.asMap()); - request.setEntity(RequestConverters.createEntity(putMappingRequest, RequestConverters.REQUEST_BODY_CONTENT_TYPE)); - return request; - } - - static Request getMappings(GetMappingsRequest getMappingsRequest) { - String[] indices = getMappingsRequest.indices() == null ? Strings.EMPTY_ARRAY : getMappingsRequest.indices(); - - Request request = new Request(HttpGet.METHOD_NAME, RequestConverters.endpoint(indices, "_mapping")); - - RequestConverters.Params parameters = new RequestConverters.Params(); - parameters.withMasterTimeout(getMappingsRequest.masterNodeTimeout()); - parameters.withIndicesOptions(getMappingsRequest.indicesOptions()); - parameters.withLocal(getMappingsRequest.local()); - request.addParameters(parameters.asMap()); - return request; - } - - static Request getFieldMapping(GetFieldMappingsRequest getFieldMappingsRequest) { - 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) - .addPathPartAsIs("_mapping") - .addPathPartAsIs("field") - .addCommaSeparatedPathParts(fields) - .build(); - - Request request = new Request(HttpGet.METHOD_NAME, endpoint); - - RequestConverters.Params parameters = new RequestConverters.Params(); - parameters.withIndicesOptions(getFieldMappingsRequest.indicesOptions()); - parameters.withIncludeDefaults(getFieldMappingsRequest.includeDefaults()); - request.addParameters(parameters.asMap()); - return request; - } - - static Request refresh(RefreshRequest refreshRequest) { - String[] indices = refreshRequest.indices() == null ? Strings.EMPTY_ARRAY : refreshRequest.indices(); - Request request = new Request(HttpPost.METHOD_NAME, RequestConverters.endpoint(indices, "_refresh")); - - RequestConverters.Params parameters = new RequestConverters.Params(); - if (BroadcastRequest.DEFAULT_INDICES_OPTIONS.equals(refreshRequest.indicesOptions()) == false) { - parameters.withIndicesOptions(refreshRequest.indicesOptions()); - } - request.addParameters(parameters.asMap()); - return request; - } - - static Request flush(FlushRequest flushRequest) { - String[] indices = flushRequest.indices() == null ? Strings.EMPTY_ARRAY : flushRequest.indices(); - Request request = new Request(HttpPost.METHOD_NAME, RequestConverters.endpoint(indices, "_flush")); - - RequestConverters.Params parameters = new RequestConverters.Params(); - if (BroadcastRequest.DEFAULT_INDICES_OPTIONS.equals(flushRequest.indicesOptions()) == false) { - parameters.withIndicesOptions(flushRequest.indicesOptions()); - } - parameters.putParam("wait_if_ongoing", Boolean.toString(flushRequest.waitIfOngoing())); - parameters.putParam("force", Boolean.toString(flushRequest.force())); - request.addParameters(parameters.asMap()); - return request; - } - - static Request forceMerge(ForceMergeRequest forceMergeRequest) { - String[] indices = forceMergeRequest.indices() == null ? Strings.EMPTY_ARRAY : forceMergeRequest.indices(); - Request request = new Request(HttpPost.METHOD_NAME, RequestConverters.endpoint(indices, "_forcemerge")); - - RequestConverters.Params parameters = new RequestConverters.Params(); - if (BroadcastRequest.DEFAULT_INDICES_OPTIONS.equals(forceMergeRequest.indicesOptions()) == false) { - parameters.withIndicesOptions(forceMergeRequest.indicesOptions()); - } - parameters.putParam("max_num_segments", Integer.toString(forceMergeRequest.maxNumSegments())); - parameters.putParam("only_expunge_deletes", Boolean.toString(forceMergeRequest.onlyExpungeDeletes())); - parameters.putParam("flush", Boolean.toString(forceMergeRequest.flush())); - request.addParameters(parameters.asMap()); - return request; - } - - static Request clearCache(ClearIndicesCacheRequest clearIndicesCacheRequest) { - 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(); - if (BroadcastRequest.DEFAULT_INDICES_OPTIONS.equals(clearIndicesCacheRequest.indicesOptions()) == false) { - parameters.withIndicesOptions(clearIndicesCacheRequest.indicesOptions()); - } - parameters.putParam("query", Boolean.toString(clearIndicesCacheRequest.queryCache())); - parameters.putParam("fielddata", Boolean.toString(clearIndicesCacheRequest.fieldDataCache())); - parameters.putParam("request", Boolean.toString(clearIndicesCacheRequest.requestCache())); - parameters.putParam("fields", String.join(",", clearIndicesCacheRequest.fields())); - request.addParameters(parameters.asMap()); - return request; - } - - static Request existsAlias(GetAliasesRequest getAliasesRequest) { - 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(); - String[] aliases = getAliasesRequest.aliases() == null ? Strings.EMPTY_ARRAY : getAliasesRequest.aliases(); - - Request request = new Request(HttpHead.METHOD_NAME, RequestConverters.endpoint(indices, "_alias", aliases)); - - RequestConverters.Params params = new RequestConverters.Params(); - if (GetAliasesRequest.DEFAULT_INDICES_OPTIONS.equals(getAliasesRequest.indicesOptions()) == false) { - params.withIndicesOptions(getAliasesRequest.indicesOptions()); - } - params.withLocal(getAliasesRequest.local()); - request.addParameters(params.asMap()); - return request; - } - - static Request split(ResizeRequest resizeRequest) throws IOException { - if (IndexMetadata.INDEX_NUMBER_OF_SHARDS_SETTING.exists(resizeRequest.getSettings()) == false) { - throw new IllegalArgumentException("index.number_of_shards is required for split operations"); - } - return resize(resizeRequest, ResizeType.SPLIT); - } - - @Deprecated - static Request split(org.elasticsearch.action.admin.indices.shrink.ResizeRequest resizeRequest) throws IOException { - if (resizeRequest.getResizeType() != ResizeType.SPLIT) { - throw new IllegalArgumentException("Wrong resize type [" + resizeRequest.getResizeType() + "] for indices split request"); - } - return resize(resizeRequest); - } - - static Request shrink(ResizeRequest resizeRequest) throws IOException { - return resize(resizeRequest, ResizeType.SHRINK); - } - - @Deprecated - static Request shrink(org.elasticsearch.action.admin.indices.shrink.ResizeRequest resizeRequest) throws IOException { - if (resizeRequest.getResizeType() != ResizeType.SHRINK) { - throw new IllegalArgumentException("Wrong resize type [" + resizeRequest.getResizeType() + "] for indices shrink request"); - } - return resize(resizeRequest); - } - - static Request clone(ResizeRequest resizeRequest) throws IOException { - return resize(resizeRequest, ResizeType.CLONE); - } - - @Deprecated - static Request clone(org.elasticsearch.action.admin.indices.shrink.ResizeRequest resizeRequest) throws IOException { - if (resizeRequest.getResizeType() != ResizeType.CLONE) { - throw new IllegalArgumentException("Wrong resize type [" + resizeRequest.getResizeType() + "] for indices clone request"); - } - return resize(resizeRequest); - } - - 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(); - Request request = new Request(HttpPut.METHOD_NAME, endpoint); - - RequestConverters.Params params = new RequestConverters.Params(); - params.withTimeout(resizeRequest.timeout()); - params.withMasterTimeout(resizeRequest.masterNodeTimeout()); - params.withWaitForActiveShards(resizeRequest.getWaitForActiveShards()); - request.addParameters(params.asMap()); - request.setEntity(RequestConverters.createEntity(resizeRequest, RequestConverters.REQUEST_BODY_CONTENT_TYPE)); - return request; - } - - @Deprecated - private static Request resize(org.elasticsearch.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(); - Request request = new Request(HttpPut.METHOD_NAME, endpoint); - - RequestConverters.Params params = new RequestConverters.Params(); - params.withTimeout(resizeRequest.timeout()); - params.withMasterTimeout(resizeRequest.masterNodeTimeout()); - params.withWaitForActiveShards(resizeRequest.getTargetIndexRequest().waitForActiveShards()); - request.addParameters(params.asMap()); - request.setEntity(RequestConverters.createEntity(resizeRequest, RequestConverters.REQUEST_BODY_CONTENT_TYPE)); - return request; - } - - static Request rollover(RolloverRequest rolloverRequest) throws IOException { - 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(); - params.withTimeout(rolloverRequest.timeout()); - params.withMasterTimeout(rolloverRequest.masterNodeTimeout()); - params.withWaitForActiveShards(rolloverRequest.getCreateIndexRequest().waitForActiveShards()); - if (rolloverRequest.isDryRun()) { - params.putParam("dry_run", Boolean.TRUE.toString()); - } - request.addParameters(params.asMap()); - request.setEntity(RequestConverters.createEntity(rolloverRequest, RequestConverters.REQUEST_BODY_CONTENT_TYPE)); - return request; - } - - static Request getSettings(GetSettingsRequest getSettingsRequest) { - String[] indices = getSettingsRequest.indices() == null ? Strings.EMPTY_ARRAY : getSettingsRequest.indices(); - String[] names = getSettingsRequest.names() == null ? Strings.EMPTY_ARRAY : getSettingsRequest.names(); - - String endpoint = RequestConverters.endpoint(indices, "_settings", names); - Request request = new Request(HttpGet.METHOD_NAME, endpoint); - - RequestConverters.Params params = new RequestConverters.Params(); - if (GetSettingsRequest.DEFAULT_INDICES_OPTIONS.equals(getSettingsRequest.indicesOptions()) == false) { - params.withIndicesOptions(getSettingsRequest.indicesOptions()); - } - params.withLocal(getSettingsRequest.local()); - params.withIncludeDefaults(getSettingsRequest.includeDefaults()); - params.withMasterTimeout(getSettingsRequest.masterNodeTimeout()); - request.addParameters(params.asMap()); - return request; - } - - static Request getIndex(GetIndexRequest getIndexRequest) { - String[] indices = getIndexRequest.indices() == null ? Strings.EMPTY_ARRAY : getIndexRequest.indices(); - - String endpoint = RequestConverters.endpoint(indices); - Request request = new Request(HttpGet.METHOD_NAME, endpoint); - - RequestConverters.Params params = new RequestConverters.Params(); - if (GetIndexRequest.DEFAULT_INDICES_OPTIONS.equals(getIndexRequest.indicesOptions()) == false) { - params.withIndicesOptions(getIndexRequest.indicesOptions()); - } - params.withLocal(getIndexRequest.local()); - params.withIncludeDefaults(getIndexRequest.includeDefaults()); - params.withHuman(getIndexRequest.humanReadable()); - params.withMasterTimeout(getIndexRequest.masterNodeTimeout()); - request.addParameters(params.asMap()); - return request; - } - - static Request indicesExist(GetIndexRequest getIndexRequest) { - if (getIndexRequest.indices() == null || getIndexRequest.indices().length == 0) { - throw new IllegalArgumentException("indices are mandatory"); - } - String endpoint = RequestConverters.endpoint(getIndexRequest.indices(), ""); - Request request = new Request(HttpHead.METHOD_NAME, endpoint); - - RequestConverters.Params params = new RequestConverters.Params(); - params.withLocal(getIndexRequest.local()); - params.withHuman(getIndexRequest.humanReadable()); - if (GetIndexRequest.DEFAULT_INDICES_OPTIONS.equals(getIndexRequest.indicesOptions()) == false) { - params.withIndicesOptions(getIndexRequest.indicesOptions()); - } - params.withIncludeDefaults(getIndexRequest.includeDefaults()); - request.addParameters(params.asMap()); - return request; - } - - static Request indexPutSettings(UpdateSettingsRequest updateSettingsRequest) throws IOException { - String[] indices = updateSettingsRequest.indices() == null ? Strings.EMPTY_ARRAY : updateSettingsRequest.indices(); - Request request = new Request(HttpPut.METHOD_NAME, RequestConverters.endpoint(indices, "_settings")); - - RequestConverters.Params parameters = new RequestConverters.Params(); - parameters.withTimeout(updateSettingsRequest.timeout()); - parameters.withMasterTimeout(updateSettingsRequest.masterNodeTimeout()); - if (UpdateSettingsRequest.DEFAULT_INDICES_OPTIONS.equals(updateSettingsRequest.indicesOptions()) == false) { - parameters.withIndicesOptions(updateSettingsRequest.indicesOptions()); - } - parameters.withPreserveExisting(updateSettingsRequest.isPreserveExisting()); - request.addParameters(parameters.asMap()); - request.setEntity(RequestConverters.createEntity(updateSettingsRequest, RequestConverters.REQUEST_BODY_CONTENT_TYPE)); - return request; - } - - static Request putTemplate(PutIndexTemplateRequest putIndexTemplateRequest) throws IOException { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_template") - .addPathPart(putIndexTemplateRequest.name()) - .build(); - Request request = new Request(HttpPut.METHOD_NAME, endpoint); - RequestConverters.Params params = new RequestConverters.Params(); - params.withMasterTimeout(putIndexTemplateRequest.masterNodeTimeout()); - if (putIndexTemplateRequest.create()) { - params.putParam("create", Boolean.TRUE.toString()); - } - if (Strings.hasText(putIndexTemplateRequest.cause())) { - params.putParam("cause", putIndexTemplateRequest.cause()); - } - request.addParameters(params.asMap()); - request.setEntity(RequestConverters.createEntity(putIndexTemplateRequest, RequestConverters.REQUEST_BODY_CONTENT_TYPE)); - return request; - } - - static Request putIndexTemplate(PutComposableIndexTemplateRequest putIndexTemplateRequest) throws IOException { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_index_template") - .addPathPart(putIndexTemplateRequest.name()) - .build(); - Request request = new Request(HttpPut.METHOD_NAME, endpoint); - RequestConverters.Params params = new RequestConverters.Params(); - params.withMasterTimeout(putIndexTemplateRequest.masterNodeTimeout()); - if (putIndexTemplateRequest.create()) { - params.putParam("create", Boolean.TRUE.toString()); - } - if (Strings.hasText(putIndexTemplateRequest.cause())) { - params.putParam("cause", putIndexTemplateRequest.cause()); - } - request.addParameters(params.asMap()); - request.setEntity(RequestConverters.createEntity(putIndexTemplateRequest, RequestConverters.REQUEST_BODY_CONTENT_TYPE)); - return request; - } - - static Request simulateIndexTemplate(SimulateIndexTemplateRequest simulateIndexTemplateRequest) throws IOException { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_index_template", "_simulate_index") - .addPathPart(simulateIndexTemplateRequest.indexName()) - .build(); - Request request = new Request(HttpPost.METHOD_NAME, endpoint); - RequestConverters.Params params = new RequestConverters.Params(); - params.withMasterTimeout(simulateIndexTemplateRequest.masterNodeTimeout()); - PutComposableIndexTemplateRequest putComposableIndexTemplateRequest = simulateIndexTemplateRequest.indexTemplateV2Request(); - if (putComposableIndexTemplateRequest != null) { - if (putComposableIndexTemplateRequest.create()) { - params.putParam("create", Boolean.TRUE.toString()); - } - if (Strings.hasText(putComposableIndexTemplateRequest.cause())) { - params.putParam("cause", putComposableIndexTemplateRequest.cause()); - } - request.setEntity( - RequestConverters.createEntity(putComposableIndexTemplateRequest, RequestConverters.REQUEST_BODY_CONTENT_TYPE) - ); - } - request.addParameters(params.asMap()); - return request; - } - - static Request validateQuery(ValidateQueryRequest validateQueryRequest) throws IOException { - String[] indices = validateQueryRequest.indices() == null ? Strings.EMPTY_ARRAY : validateQueryRequest.indices(); - String endpoint = RequestConverters.endpoint(indices, "_validate/query"); - Request request = new Request(HttpGet.METHOD_NAME, endpoint); - RequestConverters.Params params = new RequestConverters.Params(); - if (ValidateQueryRequest.DEFAULT_INDICES_OPTIONS.equals(validateQueryRequest.indicesOptions()) == false) { - params.withIndicesOptions(validateQueryRequest.indicesOptions()); - } - params.putParam("explain", Boolean.toString(validateQueryRequest.explain())); - params.putParam("all_shards", Boolean.toString(validateQueryRequest.allShards())); - params.putParam("rewrite", Boolean.toString(validateQueryRequest.rewrite())); - request.addParameters(params.asMap()); - request.setEntity(RequestConverters.createEntity(validateQueryRequest, RequestConverters.REQUEST_BODY_CONTENT_TYPE)); - return request; - } - - static Request getAlias(GetAliasesRequest getAliasesRequest) { - String[] indices = getAliasesRequest.indices() == null ? Strings.EMPTY_ARRAY : getAliasesRequest.indices(); - String[] aliases = getAliasesRequest.aliases() == null ? Strings.EMPTY_ARRAY : getAliasesRequest.aliases(); - String endpoint = RequestConverters.endpoint(indices, "_alias", aliases); - Request request = new Request(HttpGet.METHOD_NAME, endpoint); - RequestConverters.Params params = new RequestConverters.Params(); - if (GetAliasesRequest.DEFAULT_INDICES_OPTIONS.equals(getAliasesRequest.indicesOptions()) == false) { - params.withIndicesOptions(getAliasesRequest.indicesOptions()); - } - params.withLocal(getAliasesRequest.local()); - request.addParameters(params.asMap()); - return request; - } - - static Request getTemplates(GetIndexTemplatesRequest getIndexTemplatesRequest) { - final String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_template") - .addCommaSeparatedPathParts(getIndexTemplatesRequest.names()) - .build(); - final Request request = new Request(HttpGet.METHOD_NAME, endpoint); - final RequestConverters.Params params = new RequestConverters.Params(); - params.withLocal(getIndexTemplatesRequest.isLocal()); - params.withMasterTimeout(getIndexTemplatesRequest.getMasterNodeTimeout()); - request.addParameters(params.asMap()); - return request; - } - - static Request getIndexTemplates(GetComposableIndexTemplateRequest getIndexTemplatesRequest) { - final String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_index_template") - .addPathPart(getIndexTemplatesRequest.name()) - .build(); - final Request request = new Request(HttpGet.METHOD_NAME, endpoint); - final RequestConverters.Params params = new RequestConverters.Params(); - params.withLocal(getIndexTemplatesRequest.isLocal()); - params.withMasterTimeout(getIndexTemplatesRequest.getMasterNodeTimeout()); - request.addParameters(params.asMap()); - return request; - } - - static Request templatesExist(IndexTemplatesExistRequest indexTemplatesExistRequest) { - final String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_template") - .addCommaSeparatedPathParts(indexTemplatesExistRequest.names()) - .build(); - final Request request = new Request(HttpHead.METHOD_NAME, endpoint); - final RequestConverters.Params params = new RequestConverters.Params(); - params.withLocal(indexTemplatesExistRequest.isLocal()); - params.withMasterTimeout(indexTemplatesExistRequest.getMasterNodeTimeout()); - request.addParameters(params.asMap()); - return request; - } - - static Request templatesExist(ComposableIndexTemplateExistRequest indexTemplatesExistRequest) { - final String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_index_template") - .addPathPart(indexTemplatesExistRequest.name()) - .build(); - final Request request = new Request(HttpHead.METHOD_NAME, endpoint); - final RequestConverters.Params params = new RequestConverters.Params(); - params.withLocal(indexTemplatesExistRequest.isLocal()); - params.withMasterTimeout(indexTemplatesExistRequest.getMasterNodeTimeout()); - request.addParameters(params.asMap()); - return request; - } - - static Request analyze(AnalyzeRequest request) throws IOException { - RequestConverters.EndpointBuilder builder = new RequestConverters.EndpointBuilder(); - String index = request.index(); - if (index != null) { - builder.addPathPart(index); - } - builder.addPathPartAsIs("_analyze"); - Request req = new Request(HttpGet.METHOD_NAME, builder.build()); - req.setEntity(RequestConverters.createEntity(request, RequestConverters.REQUEST_BODY_CONTENT_TYPE)); - return req; - } - - static Request freezeIndex(FreezeIndexRequest freezeIndexRequest) { - String endpoint = RequestConverters.endpoint(freezeIndexRequest.getIndices(), "_freeze"); - Request request = new Request(HttpPost.METHOD_NAME, endpoint); - RequestConverters.Params parameters = new RequestConverters.Params(); - parameters.withTimeout(freezeIndexRequest.timeout()); - parameters.withMasterTimeout(freezeIndexRequest.masterNodeTimeout()); - parameters.withIndicesOptions(freezeIndexRequest.indicesOptions()); - parameters.withWaitForActiveShards(freezeIndexRequest.getWaitForActiveShards()); - request.addParameters(parameters.asMap()); - return request; - } - - static Request unfreezeIndex(UnfreezeIndexRequest unfreezeIndexRequest) { - String endpoint = RequestConverters.endpoint(unfreezeIndexRequest.getIndices(), "_unfreeze"); - Request request = new Request(HttpPost.METHOD_NAME, endpoint); - RequestConverters.Params parameters = new RequestConverters.Params(); - parameters.withTimeout(unfreezeIndexRequest.timeout()); - parameters.withMasterTimeout(unfreezeIndexRequest.masterNodeTimeout()); - parameters.withIndicesOptions(unfreezeIndexRequest.indicesOptions()); - parameters.withWaitForActiveShards(unfreezeIndexRequest.getWaitForActiveShards()); - request.addParameters(parameters.asMap()); - return request; - } - - static Request deleteTemplate(DeleteIndexTemplateRequest deleteIndexTemplateRequest) { - String name = deleteIndexTemplateRequest.name(); - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_template").addPathPart(name).build(); - Request request = new Request(HttpDelete.METHOD_NAME, endpoint); - RequestConverters.Params params = new RequestConverters.Params(); - params.withMasterTimeout(deleteIndexTemplateRequest.masterNodeTimeout()); - request.addParameters(params.asMap()); - return request; - } - - static Request deleteIndexTemplate(DeleteComposableIndexTemplateRequest deleteIndexTemplateRequest) { - String name = deleteIndexTemplateRequest.getName(); - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_index_template").addPathPart(name).build(); - Request request = new Request(HttpDelete.METHOD_NAME, endpoint); - RequestConverters.Params params = new RequestConverters.Params(); - params.withMasterTimeout(deleteIndexTemplateRequest.masterNodeTimeout()); - request.addParameters(params.asMap()); - return request; - } - - static Request reloadAnalyzers(ReloadAnalyzersRequest reloadAnalyzersRequest) { - String endpoint = RequestConverters.endpoint(reloadAnalyzersRequest.getIndices(), "_reload_search_analyzers"); - Request request = new Request(HttpPost.METHOD_NAME, endpoint); - RequestConverters.Params parameters = new RequestConverters.Params(); - if (ReloadAnalyzersRequest.DEFAULT_INDICES_OPTIONS.equals(reloadAnalyzersRequest.indicesOptions()) == false) { - parameters.withIndicesOptions(reloadAnalyzersRequest.indicesOptions()); - } - request.addParameters(parameters.asMap()); - return request; - } - - static Request deleteAlias(DeleteAliasRequest deleteAliasRequest) { - String endpoint = new RequestConverters.EndpointBuilder().addPathPart(deleteAliasRequest.getIndex()) - .addPathPartAsIs("_alias") - .addPathPart(deleteAliasRequest.getAlias()) - .build(); - Request request = new Request(HttpDelete.METHOD_NAME, endpoint); - RequestConverters.Params parameters = new RequestConverters.Params(); - parameters.withTimeout(deleteAliasRequest.timeout()); - parameters.withMasterTimeout(deleteAliasRequest.masterNodeTimeout()); - request.addParameters(parameters.asMap()); - return request; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/RequestConverters.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/RequestConverters.java index fdd6bbaebcdd..b90304f167be 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/RequestConverters.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/RequestConverters.java @@ -43,7 +43,6 @@ import org.elasticsearch.client.core.CountRequest; import org.elasticsearch.client.core.GetSourceRequest; import org.elasticsearch.client.core.MultiTermVectorsRequest; import org.elasticsearch.client.core.TermVectorsRequest; -import org.elasticsearch.client.indices.AnalyzeRequest; import org.elasticsearch.client.internal.Requests; import org.elasticsearch.client.security.RefreshPolicy; import org.elasticsearch.client.tasks.TaskId; @@ -725,18 +724,6 @@ final class RequestConverters { return request; } - static Request analyze(AnalyzeRequest request) throws IOException { - EndpointBuilder builder = new EndpointBuilder(); - String index = request.index(); - if (index != null) { - builder.addPathPart(index); - } - builder.addPathPartAsIs("_analyze"); - Request req = new Request(HttpGet.METHOD_NAME, builder.build()); - req.setEntity(createEntity(request, REQUEST_BODY_CONTENT_TYPE)); - return req; - } - static Request termVectors(TermVectorsRequest tvrequest) throws IOException { String endpoint; if (tvrequest.getType() != null) { diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/RestHighLevelClient.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/RestHighLevelClient.java index 079e6b894c13..35a2319dfec0 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/RestHighLevelClient.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/RestHighLevelClient.java @@ -273,7 +273,6 @@ public class RestHighLevelClient implements Closeable { /** Do not access directly but through getVersionValidationFuture() */ private volatile ListenableFuture> versionValidationFuture; - private final IndicesClient indicesClient = new IndicesClient(this); private final SnapshotClient snapshotClient = new SnapshotClient(this); private final SecurityClient securityClient = new SecurityClient(this); private final TransformClient transformClient = new TransformClient(this); @@ -349,15 +348,6 @@ public class RestHighLevelClient implements Closeable { doClose.accept(client); } - /** - * Provides an {@link IndicesClient} which can be used to access the Indices API. - * - * See Indices API on elastic.co - */ - public final IndicesClient indices() { - return indicesClient; - } - /** * Provides a {@link SnapshotClient} which can be used to access the Snapshot API. * diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/AnalyzeRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/AnalyzeRequest.java deleted file mode 100644 index a6b8c16016f8..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/AnalyzeRequest.java +++ /dev/null @@ -1,329 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -package org.elasticsearch.client.indices; - -import org.elasticsearch.client.Validatable; -import org.elasticsearch.common.Strings; -import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.xcontent.ToXContentFragment; -import org.elasticsearch.xcontent.ToXContentObject; -import org.elasticsearch.xcontent.XContentBuilder; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -/** - * A request to analyze text - */ -public class AnalyzeRequest implements Validatable, ToXContentObject { - - private String index; - - private String[] text; - - private String analyzer; - - private NameOrDefinition tokenizer; - - private final List tokenFilters = new ArrayList<>(); - - private final List charFilters = new ArrayList<>(); - - private String field; - - private boolean explain = false; - - private String[] attributes = Strings.EMPTY_ARRAY; - - private String normalizer; - - /** - * Analyzes text using a global analyzer - */ - public static AnalyzeRequest withGlobalAnalyzer(String analyzer, String... text) { - return new AnalyzeRequest(null, analyzer, null, null, text); - } - - /** - * Analyzes text using a custom analyzer built from global components - */ - public static CustomAnalyzerBuilder buildCustomAnalyzer(String tokenizer) { - return new CustomAnalyzerBuilder(null, new NameOrDefinition(tokenizer)); - } - - /** - * Analyzes text using a custom analyzer built from global components - */ - public static CustomAnalyzerBuilder buildCustomAnalyzer(Map tokenizerSettings) { - return new CustomAnalyzerBuilder(null, new NameOrDefinition(tokenizerSettings)); - } - - /** - * Analyzes text using a custom analyzer built from components defined on an index - */ - public static CustomAnalyzerBuilder buildCustomAnalyzer(String index, String tokenizer) { - return new CustomAnalyzerBuilder(index, new NameOrDefinition(tokenizer)); - } - - /** - * Analyzes text using a custom analyzer built from components defined on an index - */ - public static CustomAnalyzerBuilder buildCustomAnalyzer(String index, Map tokenizerSettings) { - return new CustomAnalyzerBuilder(index, new NameOrDefinition(tokenizerSettings)); - } - - /** - * Analyzes text using a named analyzer on an index - */ - public static AnalyzeRequest withIndexAnalyzer(String index, String analyzer, String... text) { - return new AnalyzeRequest(index, analyzer, null, null, text); - } - - /** - * Analyzes text using the analyzer defined on a specific field within an index - */ - public static AnalyzeRequest withField(String index, String field, String... text) { - return new AnalyzeRequest(index, null, null, field, text); - } - - /** - * Analyzes text using a named normalizer on an index - */ - public static AnalyzeRequest withNormalizer(String index, String normalizer, String... text) { - return new AnalyzeRequest(index, null, normalizer, null, text); - } - - /** - * Analyzes text using a custom normalizer built from global components - */ - public static CustomAnalyzerBuilder buildCustomNormalizer() { - return new CustomAnalyzerBuilder(null, null); - } - - /** - * Analyzes text using a custom normalizer built from components defined on an index - */ - public static CustomAnalyzerBuilder buildCustomNormalizer(String index) { - return new CustomAnalyzerBuilder(index, null); - } - - /** - * Helper class to build custom analyzer definitions - */ - public static class CustomAnalyzerBuilder { - - final NameOrDefinition tokenizer; - final String index; - List charFilters = new ArrayList<>(); - List tokenFilters = new ArrayList<>(); - - CustomAnalyzerBuilder(String index, NameOrDefinition tokenizer) { - this.tokenizer = tokenizer; - this.index = index; - } - - public CustomAnalyzerBuilder addCharFilter(String name) { - charFilters.add(new NameOrDefinition(name)); - return this; - } - - public CustomAnalyzerBuilder addCharFilter(Map settings) { - charFilters.add(new NameOrDefinition(settings)); - return this; - } - - public CustomAnalyzerBuilder addTokenFilter(String name) { - tokenFilters.add(new NameOrDefinition(name)); - return this; - } - - public CustomAnalyzerBuilder addTokenFilter(Map settings) { - tokenFilters.add(new NameOrDefinition(settings)); - return this; - } - - public AnalyzeRequest build(String... text) { - return new AnalyzeRequest(index, tokenizer, charFilters, tokenFilters, text); - } - } - - private AnalyzeRequest(String index, String analyzer, String normalizer, String field, String... text) { - this.index = index; - this.analyzer = analyzer; - this.normalizer = normalizer; - this.field = field; - this.text = text; - } - - private AnalyzeRequest( - String index, - NameOrDefinition tokenizer, - List charFilters, - List tokenFilters, - String... text - ) { - this.index = index; - this.analyzer = null; - this.normalizer = null; - this.field = null; - this.tokenizer = tokenizer; - this.charFilters.addAll(charFilters); - this.tokenFilters.addAll(tokenFilters); - this.text = text; - } - - static class NameOrDefinition implements ToXContentFragment { - // exactly one of these two members is not null - public final String name; - public final Settings definition; - - NameOrDefinition(String name) { - this.name = Objects.requireNonNull(name); - this.definition = null; - } - - NameOrDefinition(Settings settings) { - this.name = null; - this.definition = Objects.requireNonNull(settings); - } - - NameOrDefinition(Map definition) { - this.name = null; - Objects.requireNonNull(definition); - this.definition = Settings.builder().loadFromMap(definition).build(); - } - - @Override - public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - if (definition == null) { - return builder.value(name); - } - builder.startObject(); - definition.toXContent(builder, params); - builder.endObject(); - return builder; - } - - } - - /** - * Returns the index that the request should be executed against, or {@code null} if - * no index is specified - */ - public String index() { - return this.index; - } - - /** - * Returns the text to be analyzed - */ - public String[] text() { - return this.text; - } - - /** - * Returns the named analyzer used for analysis, if defined - */ - public String analyzer() { - return this.analyzer; - } - - /** - * Returns the named tokenizer used for analysis, if defined - */ - public String normalizer() { - return this.normalizer; - } - - /** - * Returns a custom Tokenizer used for analysis, if defined - */ - public NameOrDefinition tokenizer() { - return this.tokenizer; - } - - /** - * Returns the custom token filters used for analysis, if defined - */ - public List tokenFilters() { - return this.tokenFilters; - } - - /** - * Returns the custom character filters used for analysis, if defined - */ - public List charFilters() { - return this.charFilters; - } - - /** - * Returns the field to take an Analyzer from, if defined - */ - public String field() { - return this.field; - } - - /** - * Set whether or not detailed explanations of analysis should be returned - */ - public AnalyzeRequest explain(boolean explain) { - this.explain = explain; - return this; - } - - public boolean explain() { - return this.explain; - } - - public AnalyzeRequest attributes(String... attributes) { - if (attributes == null) { - throw new IllegalArgumentException("attributes must not be null"); - } - this.attributes = attributes; - return this; - } - - public String[] attributes() { - return this.attributes; - } - - @Override - public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(); - builder.field("text", text); - if (Strings.isNullOrEmpty(analyzer) == false) { - builder.field("analyzer", analyzer); - } - if (tokenizer != null) { - builder.field("tokenizer", tokenizer); - } - if (tokenFilters.size() > 0) { - builder.field("filter", tokenFilters); - } - if (charFilters.size() > 0) { - builder.field("char_filter", charFilters); - } - if (Strings.isNullOrEmpty(field) == false) { - builder.field("field", field); - } - if (explain) { - builder.field("explain", true); - } - if (attributes.length > 0) { - builder.field("attributes", attributes); - } - if (Strings.isNullOrEmpty(normalizer) == false) { - builder.field("normalizer", normalizer); - } - return builder.endObject(); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/AnalyzeResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/AnalyzeResponse.java deleted file mode 100644 index 101550f9ff44..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/AnalyzeResponse.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -package org.elasticsearch.client.indices; - -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -import static org.elasticsearch.xcontent.ConstructingObjectParser.optionalConstructorArg; - -public class AnalyzeResponse { - - private static final String TOKENS = "tokens"; - private static final String DETAIL = "detail"; - - public static class AnalyzeToken { - private String term; - private int startOffset; - private int endOffset; - private int position; - private int positionLength = 1; - private String type; - private final Map attributes = new HashMap<>(); - - @Override - public boolean equals(Object o) { - 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); - } - - @Override - public int hashCode() { - return Objects.hash(term, startOffset, endOffset, position, positionLength, attributes, type); - } - - public String getTerm() { - return this.term; - } - - private void setTerm(String term) { - this.term = term; - } - - public int getStartOffset() { - return this.startOffset; - } - - private void setStartOffset(int startOffset) { - this.startOffset = startOffset; - } - - public int getEndOffset() { - return this.endOffset; - } - - private void setEndOffset(int endOffset) { - this.endOffset = endOffset; - } - - public int getPosition() { - return this.position; - } - - private void setPosition(int position) { - this.position = position; - } - - public int getPositionLength() { - return this.positionLength; - } - - private void setPositionLength(int positionLength) { - this.positionLength = positionLength; - } - - public String getType() { - return this.type; - } - - private void setType(String type) { - this.type = type; - } - - public Map getAttributes() { - return this.attributes; - } - - private void setAttribute(String key, Object value) { - this.attributes.put(key, value); - } - - 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")); - PARSER.declareInt(AnalyzeToken::setPosition, new ParseField("position")); - PARSER.declareInt(AnalyzeToken::setStartOffset, new ParseField("start_offset")); - PARSER.declareInt(AnalyzeToken::setEndOffset, new ParseField("end_offset")); - PARSER.declareInt(AnalyzeToken::setPositionLength, new ParseField("positionLength")); - } - - public static AnalyzeToken fromXContent(XContentParser parser) throws IOException { - return PARSER.parse(parser, null); - } - } - - private final DetailAnalyzeResponse detail; - private final List tokens; - - private AnalyzeResponse(List tokens, DetailAnalyzeResponse detail) { - this.tokens = tokens; - this.detail = detail; - } - - public List getTokens() { - return this.tokens; - } - - public DetailAnalyzeResponse detail() { - return this.detail; - } - - @SuppressWarnings("unchecked") - 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)); - PARSER.declareObject(optionalConstructorArg(), DetailAnalyzeResponse.PARSER, new ParseField(DETAIL)); - } - - public static AnalyzeResponse fromXContent(XContentParser parser) throws IOException { - return PARSER.parse(parser, null); - } - - @Override - public boolean equals(Object o) { - 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); - } - - @Override - public int hashCode() { - return Objects.hash(detail, tokens); - } - -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/CloseIndexRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/CloseIndexRequest.java deleted file mode 100644 index 4a889c3b9aa1..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/CloseIndexRequest.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -package org.elasticsearch.client.indices; - -import org.elasticsearch.action.admin.indices.open.OpenIndexResponse; -import org.elasticsearch.action.support.ActiveShardCount; -import org.elasticsearch.action.support.IndicesOptions; -import org.elasticsearch.client.TimedRequest; -import org.elasticsearch.client.Validatable; -import org.elasticsearch.client.ValidationException; - -import java.util.Optional; - -/** - * A request to close an index. - */ -public class CloseIndexRequest extends TimedRequest implements Validatable { - - public static final IndicesOptions DEFAULT_INDICES_OPTIONS = IndicesOptions.strictExpandOpen(); - - private String[] indices; - private IndicesOptions indicesOptions = DEFAULT_INDICES_OPTIONS; - private ActiveShardCount waitForActiveShards = ActiveShardCount.DEFAULT; - - /** - * Creates a new close index request - * - * @param indices the indices to close - */ - public CloseIndexRequest(String... indices) { - this.indices = indices; - } - - /** - * Returns the indices to close - */ - public String[] indices() { - return indices; - } - - /** - * Specifies what type of requested indices to ignore and how to deal with wildcard expressions. - * For example indices that don't exist. - * - * @return the current behaviour when it comes to index names and wildcard indices expressions - */ - public IndicesOptions indicesOptions() { - return indicesOptions; - } - - /** - * Specifies what type of requested indices to ignore and how to deal with wildcard expressions. - * For example indices that don't exist. - * - * @param indicesOptions the desired behaviour regarding indices to ignore and wildcard indices expressions - */ - public CloseIndexRequest indicesOptions(IndicesOptions indicesOptions) { - this.indicesOptions = indicesOptions; - return this; - } - - /** - * Returns the wait for active shard count or null if the default should be used - */ - public ActiveShardCount waitForActiveShards() { - return waitForActiveShards; - } - - /** - * Sets the number of shard copies that should be active for indices opening to return. - * Defaults to {@link ActiveShardCount#DEFAULT}, which will wait for one shard copy - * (the primary) to become active. Set this value to {@link ActiveShardCount#ALL} to - * wait for all shards (primary and all replicas) to be active before returning. - * Otherwise, use {@link ActiveShardCount#from(int)} to set this value to any - * non-negative integer, up to the number of copies per shard (number of replicas + 1), - * to wait for the desired amount of shard copies to become active before returning. - * Indices opening will only wait up until the timeout value for the number of shard copies - * to be active before returning. Check {@link OpenIndexResponse#isShardsAcknowledged()} to - * determine if the requisite shard copies were all started before returning or timing out. - * - * @param waitForActiveShards number of active shard copies to wait on - */ - public CloseIndexRequest waitForActiveShards(ActiveShardCount waitForActiveShards) { - this.waitForActiveShards = waitForActiveShards; - return this; - } - - @Override - public Optional validate() { - if (indices == null || indices.length == 0) { - ValidationException validationException = new ValidationException(); - validationException.addValidationError("index is missing"); - return Optional.of(validationException); - } else { - return Optional.empty(); - } - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/CloseIndexResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/CloseIndexResponse.java deleted file mode 100644 index 8c9719fbe3df..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/CloseIndexResponse.java +++ /dev/null @@ -1,217 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ -package org.elasticsearch.client.indices; - -import org.elasticsearch.ElasticsearchException; -import org.elasticsearch.action.support.DefaultShardOperationFailedException; -import org.elasticsearch.action.support.master.ShardsAcknowledgedResponse; -import org.elasticsearch.common.xcontent.XContentParserUtils; -import org.elasticsearch.core.Nullable; -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentParser; - -import java.util.List; -import java.util.Objects; - -import static java.util.Collections.emptyList; -import static java.util.Collections.unmodifiableList; -import static org.elasticsearch.xcontent.ConstructingObjectParser.optionalConstructorArg; -import static org.elasticsearch.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); - } - ); - - static { - declareAcknowledgedField(PARSER); - PARSER.declareField(optionalConstructorArg(), (parser, context) -> parser.booleanValue(), SHARDS_ACKNOWLEDGED, ValueType.BOOLEAN); - PARSER.declareNamedObjects(optionalConstructorArg(), (p, c, name) -> IndexResult.fromXContent(p, name), new ParseField("indices")); - } - - private final List indices; - - public CloseIndexResponse(final boolean acknowledged, final boolean shardsAcknowledged, final List indices) { - super(acknowledged, shardsAcknowledged); - this.indices = unmodifiableList(Objects.requireNonNull(indices)); - } - - public List getIndices() { - return indices; - } - - public static CloseIndexResponse fromXContent(final XContentParser parser) { - return PARSER.apply(parser, null); - } - - public static class IndexResult { - - @SuppressWarnings("unchecked") - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "index_result", - true, - (args, index) -> { - Exception exception = (Exception) args[1]; - if (exception != null) { - assert (boolean) args[0] == false; - return new IndexResult(index, exception); - } - ShardResult[] shardResults = args[2] != null ? ((List) args[2]).toArray(new ShardResult[0]) : null; - if (shardResults != null) { - assert (boolean) args[0] == false; - return new IndexResult(index, shardResults); - } - assert (boolean) args[0]; - return new IndexResult(index); - } - ); - static { - PARSER.declareBoolean(optionalConstructorArg(), new ParseField("closed")); - PARSER.declareObject(optionalConstructorArg(), (p, c) -> { - XContentParserUtils.ensureExpectedToken(XContentParser.Token.START_OBJECT, p.currentToken(), p); - XContentParserUtils.ensureExpectedToken(XContentParser.Token.FIELD_NAME, p.nextToken(), p); - Exception e = ElasticsearchException.failureFromXContent(p); - 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") - ); - } - - private final String index; - private final @Nullable Exception exception; - private final @Nullable ShardResult[] shards; - - IndexResult(final String index) { - this(index, null, null); - } - - IndexResult(final String index, final Exception failure) { - this(index, Objects.requireNonNull(failure), null); - } - - IndexResult(final String index, final ShardResult[] shards) { - this(index, null, Objects.requireNonNull(shards)); - } - - private IndexResult(final String index, @Nullable final Exception exception, @Nullable final ShardResult[] shards) { - this.index = Objects.requireNonNull(index); - this.exception = exception; - this.shards = shards; - } - - public String getIndex() { - return index; - } - - public @Nullable Exception getException() { - return exception; - } - - public @Nullable ShardResult[] getShards() { - return shards; - } - - public boolean hasFailures() { - if (exception != null) { - return true; - } - if (shards != null) { - for (ShardResult shard : shards) { - if (shard.hasFailures()) { - return true; - } - } - } - return false; - } - - static IndexResult fromXContent(final XContentParser parser, final String name) { - return PARSER.apply(parser, name); - } - } - - public static class ShardResult { - - @SuppressWarnings("unchecked") - 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")); - } - - private final int id; - private final Failure[] failures; - - ShardResult(final int id, final Failure[] failures) { - this.id = id; - this.failures = failures; - } - - public boolean hasFailures() { - return failures != null && failures.length > 0; - } - - public int getId() { - return id; - } - - public Failure[] getFailures() { - return failures; - } - - static ShardResult fromXContent(final XContentParser parser, final String id) { - return PARSER.apply(parser, id); - } - - 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 { - declareFields(PARSER); - PARSER.declareStringOrNull(optionalConstructorArg(), new ParseField("node")); - } - - private @Nullable String nodeId; - - Failure(final String index, final int shardId, final Throwable reason, final String nodeId) { - super(index, shardId, reason); - this.nodeId = nodeId; - } - - public String getNodeId() { - return nodeId; - } - } - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/ComponentTemplatesExistRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/ComponentTemplatesExistRequest.java deleted file mode 100644 index f52ba5530458..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/ComponentTemplatesExistRequest.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -package org.elasticsearch.client.indices; - -import org.elasticsearch.common.Strings; - -/** - * A request to check for the existence of component templates - */ -public class ComponentTemplatesExistRequest extends GetComponentTemplatesRequest { - - /** - * Create a request to check for the existence of component template. Name must be provided - * - * @param name the name of template to check for the existence of - */ - public ComponentTemplatesExistRequest(String name) { - super(name); - if (Strings.isNullOrEmpty(name)) { - throw new IllegalArgumentException("must provide component template name"); - } - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/ComposableIndexTemplateExistRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/ComposableIndexTemplateExistRequest.java deleted file mode 100644 index bcabf4c2921a..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/ComposableIndexTemplateExistRequest.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -package org.elasticsearch.client.indices; - -import org.elasticsearch.common.Strings; - -/** - * A request to check for the existence of index templates - */ -public class ComposableIndexTemplateExistRequest extends GetComponentTemplatesRequest { - - /** - * Create a request to check for the existence of index template. Name must be provided - * - * @param name the name of template to check for the existence of - */ - public ComposableIndexTemplateExistRequest(String name) { - super(name); - if (Strings.isNullOrEmpty(name)) { - throw new IllegalArgumentException("must provide index template name"); - } - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/CreateDataStreamRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/CreateDataStreamRequest.java deleted file mode 100644 index 55957ec2faef..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/CreateDataStreamRequest.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -package org.elasticsearch.client.indices; - -import org.elasticsearch.client.Validatable; - -public class CreateDataStreamRequest implements Validatable { - - private final String name; - - public CreateDataStreamRequest(String name) { - if (name == null) { - throw new IllegalArgumentException("The data stream name cannot be null."); - } - this.name = name; - } - - public String getName() { - return name; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/CreateIndexRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/CreateIndexRequest.java deleted file mode 100644 index 594f23234c7d..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/CreateIndexRequest.java +++ /dev/null @@ -1,353 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -package org.elasticsearch.client.indices; - -import org.elasticsearch.ElasticsearchGenerationException; -import org.elasticsearch.ElasticsearchParseException; -import org.elasticsearch.action.admin.indices.alias.Alias; -import org.elasticsearch.action.support.ActiveShardCount; -import org.elasticsearch.client.TimedRequest; -import org.elasticsearch.client.Validatable; -import org.elasticsearch.common.Strings; -import org.elasticsearch.common.bytes.BytesArray; -import org.elasticsearch.common.bytes.BytesReference; -import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.common.xcontent.XContentHelper; -import org.elasticsearch.xcontent.DeprecationHandler; -import org.elasticsearch.xcontent.NamedXContentRegistry; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.ToXContentObject; -import org.elasticsearch.xcontent.XContentBuilder; -import org.elasticsearch.xcontent.XContentFactory; -import org.elasticsearch.xcontent.XContentParser; -import org.elasticsearch.xcontent.XContentType; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Collection; -import java.util.HashSet; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -/** - * A request to create an index. - */ -public class CreateIndexRequest extends TimedRequest implements Validatable, ToXContentObject { - static final ParseField MAPPINGS = new ParseField("mappings"); - static final ParseField SETTINGS = new ParseField("settings"); - static final ParseField ALIASES = new ParseField("aliases"); - - private final String index; - private Settings settings = Settings.EMPTY; - - private BytesReference mappings; - private XContentType mappingsXContentType; - - private final Set aliases = new HashSet<>(); - - private ActiveShardCount waitForActiveShards = ActiveShardCount.DEFAULT; - - /** - * Constructs a new request to create an index with the specified name. - */ - public CreateIndexRequest(String index) { - if (index == null) { - throw new IllegalArgumentException("The index name cannot be null."); - } - this.index = index; - } - - /** - * The name of the index to create. - */ - public String index() { - return index; - } - - /** - * The settings to create the index with. - */ - public Settings settings() { - return settings; - } - - /** - * The settings to create the index with. - */ - public CreateIndexRequest settings(Settings.Builder settings) { - this.settings = settings.build(); - return this; - } - - /** - * The settings to create the index with. - */ - public CreateIndexRequest settings(Settings settings) { - this.settings = settings; - return this; - } - - /** - * The settings to create the index with (either json or yaml format) - */ - public CreateIndexRequest settings(String source, XContentType xContentType) { - this.settings = Settings.builder().loadFromSource(source, xContentType).build(); - return this; - } - - /** - * Allows to set the settings using a json builder. - */ - public CreateIndexRequest settings(XContentBuilder builder) { - settings(Strings.toString(builder), builder.contentType()); - return this; - } - - /** - * The settings to create the index with (either json/yaml/properties format) - */ - public CreateIndexRequest settings(Map source) { - this.settings = Settings.builder().loadFromMap(source).build(); - return this; - } - - public BytesReference mappings() { - return mappings; - } - - public XContentType mappingsXContentType() { - return mappingsXContentType; - } - - /** - * Adds mapping that will be added when the index gets created. - * - * Note that the definition should *not* be nested under a type name. - * - * @param source The mapping source - * @param xContentType The content type of the source - */ - public CreateIndexRequest mapping(String source, XContentType xContentType) { - return mapping(new BytesArray(source), xContentType); - } - - /** - * Adds mapping that will be added when the index gets created. - * - * Note that the definition should *not* be nested under a type name. - * - * @param source The mapping source - */ - public CreateIndexRequest mapping(XContentBuilder source) { - return mapping(BytesReference.bytes(source), source.contentType()); - } - - /** - * Adds mapping that will be added when the index gets created. - * - * Note that the definition should *not* be nested under a type name. - * - * @param source The mapping source - */ - public CreateIndexRequest mapping(Map source) { - try { - XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON); - builder.map(source); - return mapping(BytesReference.bytes(builder), builder.contentType()); - } catch (IOException e) { - throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e); - } - } - - /** - * Adds mapping that will be added when the index gets created. - * - * Note that the definition should *not* be nested under a type name. - * - * @param source The mapping source - * @param xContentType the content type of the mapping source - */ - public CreateIndexRequest mapping(BytesReference source, XContentType xContentType) { - Objects.requireNonNull(xContentType); - mappings = source; - mappingsXContentType = xContentType; - return this; - } - - public Set aliases() { - return this.aliases; - } - - /** - * Sets the aliases that will be associated with the index when it gets created - */ - public CreateIndexRequest aliases(Map source) { - try { - XContentBuilder builder = XContentFactory.jsonBuilder(); - builder.map(source); - return aliases(BytesReference.bytes(builder), builder.contentType()); - } catch (IOException e) { - throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e); - } - } - - /** - * Sets the aliases that will be associated with the index when it gets created - */ - public CreateIndexRequest aliases(XContentBuilder source) { - return aliases(BytesReference.bytes(source), source.contentType()); - } - - /** - * Sets the aliases that will be associated with the index when it gets created - */ - public CreateIndexRequest aliases(String source, XContentType contentType) { - return aliases(new BytesArray(source), contentType); - } - - /** - * Sets the aliases that will be associated with the index when it gets created - */ - 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 - parser.nextToken(); - while ((parser.nextToken()) != XContentParser.Token.END_OBJECT) { - alias(Alias.fromXContent(parser)); - } - return this; - } catch (IOException e) { - throw new ElasticsearchParseException("Failed to parse aliases", e); - } - } - - /** - * Adds an alias that will be associated with the index when it gets created - */ - public CreateIndexRequest alias(Alias alias) { - this.aliases.add(alias); - return this; - } - - /** - * Adds aliases that will be associated with the index when it gets created - */ - public CreateIndexRequest aliases(Collection aliases) { - this.aliases.addAll(aliases); - return this; - } - - /** - * Sets the settings and mappings as a single source. - * - * Note that the mapping definition should *not* be nested under a type name. - */ - public CreateIndexRequest source(String source, XContentType xContentType) { - return source(new BytesArray(source), xContentType); - } - - /** - * Sets the settings and mappings as a single source. - * - * Note that the mapping definition should *not* be nested under a type name. - */ - public CreateIndexRequest source(XContentBuilder source) { - return source(BytesReference.bytes(source), source.contentType()); - } - - /** - * Sets the settings and mappings as a single source. - * - * Note that the mapping definition should *not* be nested under a type name. - */ - public CreateIndexRequest source(BytesReference source, XContentType xContentType) { - Objects.requireNonNull(xContentType); - source(XContentHelper.convertToMap(source, false, xContentType).v2()); - return this; - } - - /** - * Sets the settings and mappings as a single source. - * - * Note that the mapping definition should *not* be nested under a type name. - */ - @SuppressWarnings("unchecked") - public CreateIndexRequest source(Map source) { - DeprecationHandler deprecationHandler = DeprecationHandler.THROW_UNSUPPORTED_OPERATION; - for (Map.Entry entry : source.entrySet()) { - String name = entry.getKey(); - if (SETTINGS.match(name, deprecationHandler)) { - settings((Map) entry.getValue()); - } else if (MAPPINGS.match(name, deprecationHandler)) { - mapping((Map) entry.getValue()); - } else if (ALIASES.match(name, deprecationHandler)) { - aliases((Map) entry.getValue()); - } - } - return this; - } - - public ActiveShardCount waitForActiveShards() { - return waitForActiveShards; - } - - /** - * Sets the number of shard copies that should be active for index creation to return. - * Defaults to {@link ActiveShardCount#DEFAULT}, which will wait for one shard copy - * (the primary) to become active. Set this value to {@link ActiveShardCount#ALL} to - * wait for all shards (primary and all replicas) to be active before returning. - * Otherwise, use {@link ActiveShardCount#from(int)} to set this value to any - * non-negative integer, up to the number of copies per shard (number of replicas + 1), - * to wait for the desired amount of shard copies to become active before returning. - * Index creation will only wait up until the timeout value for the number of shard copies - * to be active before returning. Check {@link CreateIndexResponse#isShardsAcknowledged()} to - * determine if the requisite shard copies were all started before returning or timing out. - * - * @param waitForActiveShards number of active shard copies to wait on - */ - public CreateIndexRequest waitForActiveShards(ActiveShardCount waitForActiveShards) { - this.waitForActiveShards = waitForActiveShards; - return this; - } - - public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(); - innerToXContent(builder, params); - builder.endObject(); - return builder; - } - - public XContentBuilder innerToXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(SETTINGS.getPreferredName()); - settings.toXContent(builder, params); - builder.endObject(); - - if (mappings != null) { - try (InputStream stream = mappings.streamInput()) { - builder.rawField(MAPPINGS.getPreferredName(), stream, mappingsXContentType); - } - } - - builder.startObject(ALIASES.getPreferredName()); - for (Alias alias : aliases) { - alias.toXContent(builder, params); - } - builder.endObject(); - return builder; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/CreateIndexResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/CreateIndexResponse.java deleted file mode 100644 index 95d8e1143c06..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/CreateIndexResponse.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -package org.elasticsearch.client.indices; - -import org.elasticsearch.action.support.master.ShardsAcknowledgedResponse; -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentParser; - -import java.util.Objects; - -import static org.elasticsearch.xcontent.ConstructingObjectParser.constructorArg; - -/** - * A response for a create index action. - */ -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]) - ); - - static { - declareAcknowledgedAndShardsAcknowledgedFields(PARSER); - PARSER.declareField(constructorArg(), (parser, context) -> parser.textOrNull(), INDEX, ObjectParser.ValueType.STRING_OR_NULL); - } - - private String index; - - public CreateIndexResponse(boolean acknowledged, boolean shardsAcknowledged, String index) { - super(acknowledged, shardsAcknowledged); - this.index = index; - } - - public String index() { - return index; - } - - public static CreateIndexResponse fromXContent(XContentParser parser) { - return PARSER.apply(parser, null); - } - - @Override - public boolean equals(Object o) { - if (super.equals(o)) { - CreateIndexResponse that = (CreateIndexResponse) o; - return Objects.equals(index, that.index); - } - return false; - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), index); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/DataStream.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/DataStream.java deleted file mode 100644 index 78450a58d50a..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/DataStream.java +++ /dev/null @@ -1,215 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ -package org.elasticsearch.client.indices; - -import org.elasticsearch.cluster.health.ClusterHealthStatus; -import org.elasticsearch.core.Nullable; -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.stream.Collectors; - -public final class DataStream { - - private final String name; - private final String timeStampField; - private final List indices; - private final long generation; - private final boolean hidden; - private final boolean system; - ClusterHealthStatus dataStreamStatus; - @Nullable - String indexTemplate; - @Nullable - String ilmPolicyName; - @Nullable - private final Map metadata; - private final boolean allowCustomRouting; - private final boolean replicated; - - public DataStream( - String name, - String timeStampField, - List indices, - long generation, - ClusterHealthStatus dataStreamStatus, - @Nullable String indexTemplate, - @Nullable String ilmPolicyName, - @Nullable Map metadata, - boolean hidden, - boolean system, - boolean allowCustomRouting, - boolean replicated - ) { - this.name = name; - this.timeStampField = timeStampField; - this.indices = indices; - this.generation = generation; - this.dataStreamStatus = dataStreamStatus; - this.indexTemplate = indexTemplate; - this.ilmPolicyName = ilmPolicyName; - this.metadata = metadata; - this.hidden = hidden; - this.system = system; - this.allowCustomRouting = allowCustomRouting; - this.replicated = replicated; - } - - public String getName() { - return name; - } - - public String getTimeStampField() { - return timeStampField; - } - - public List getIndices() { - return indices; - } - - public long getGeneration() { - return generation; - } - - public ClusterHealthStatus getDataStreamStatus() { - return dataStreamStatus; - } - - public String getIndexTemplate() { - return indexTemplate; - } - - public String getIlmPolicyName() { - return ilmPolicyName; - } - - public Map getMetadata() { - return metadata; - } - - public boolean isHidden() { - return hidden; - } - - public boolean isSystem() { - return system; - } - - public boolean allowsCustomRouting() { - return allowCustomRouting; - } - - public boolean isReplicated() { - return replicated; - } - - public static final ParseField NAME_FIELD = new ParseField("name"); - public static final ParseField TIMESTAMP_FIELD_FIELD = new ParseField("timestamp_field"); - public static final ParseField INDICES_FIELD = new ParseField("indices"); - public static final ParseField GENERATION_FIELD = new ParseField("generation"); - public static final ParseField STATUS_FIELD = new ParseField("status"); - public static final ParseField INDEX_TEMPLATE_FIELD = new ParseField("template"); - public static final ParseField ILM_POLICY_FIELD = new ParseField("ilm_policy"); - public static final ParseField METADATA_FIELD = new ParseField("_meta"); - public static final ParseField HIDDEN_FIELD = new ParseField("hidden"); - public static final ParseField SYSTEM_FIELD = new ParseField("system"); - public static final ParseField ALLOW_CUSTOM_ROUTING = new ParseField("allow_custom_routing"); - public static final ParseField REPLICATED = new ParseField("replicated"); - - @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]; - String ilmPolicy = (String) args[6]; - Map metadata = (Map) args[7]; - boolean hidden = args[8] != null && (boolean) args[8]; - boolean system = args[9] != null && (boolean) args[9]; - boolean allowCustomRouting = args[10] != null && (boolean) args[10]; - boolean replicated = args[11] != null && (boolean) args[11]; - return new DataStream( - dataStreamName, - timeStampField, - indices, - generation, - status, - indexTemplate, - ilmPolicy, - metadata, - hidden, - system, - allowCustomRouting, - replicated - ); - }); - - static { - PARSER.declareString(ConstructingObjectParser.constructorArg(), NAME_FIELD); - PARSER.declareObject(ConstructingObjectParser.constructorArg(), (p, c) -> p.map(), TIMESTAMP_FIELD_FIELD); - PARSER.declareObjectArray(ConstructingObjectParser.constructorArg(), (p, c) -> p.mapStrings(), INDICES_FIELD); - PARSER.declareLong(ConstructingObjectParser.constructorArg(), GENERATION_FIELD); - PARSER.declareString(ConstructingObjectParser.constructorArg(), STATUS_FIELD); - PARSER.declareString(ConstructingObjectParser.optionalConstructorArg(), INDEX_TEMPLATE_FIELD); - PARSER.declareString(ConstructingObjectParser.optionalConstructorArg(), ILM_POLICY_FIELD); - PARSER.declareObject(ConstructingObjectParser.optionalConstructorArg(), (p, c) -> p.map(), METADATA_FIELD); - PARSER.declareBoolean(ConstructingObjectParser.optionalConstructorArg(), HIDDEN_FIELD); - PARSER.declareBoolean(ConstructingObjectParser.optionalConstructorArg(), SYSTEM_FIELD); - PARSER.declareBoolean(ConstructingObjectParser.optionalConstructorArg(), ALLOW_CUSTOM_ROUTING); - PARSER.declareBoolean(ConstructingObjectParser.optionalConstructorArg(), REPLICATED); - } - - public static DataStream fromXContent(XContentParser parser) throws IOException { - return PARSER.parse(parser, null); - } - - @Override - public boolean equals(Object o) { - 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 - && hidden == that.hidden - && system == that.system - && Objects.equals(indexTemplate, that.indexTemplate) - && Objects.equals(ilmPolicyName, that.ilmPolicyName) - && Objects.equals(metadata, that.metadata) - && allowCustomRouting == that.allowCustomRouting - && replicated == that.replicated; - } - - @Override - public int hashCode() { - return Objects.hash( - name, - timeStampField, - indices, - generation, - dataStreamStatus, - indexTemplate, - ilmPolicyName, - metadata, - hidden, - system, - allowCustomRouting, - replicated - ); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/DataStreamsStatsRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/DataStreamsStatsRequest.java deleted file mode 100644 index 68f3c3479743..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/DataStreamsStatsRequest.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -package org.elasticsearch.client.indices; - -import org.elasticsearch.client.Validatable; - -public class DataStreamsStatsRequest implements Validatable { - - private final String[] indices; - - public DataStreamsStatsRequest(String... indices) { - this.indices = indices; - } - - public String[] indices() { - return indices; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/DataStreamsStatsResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/DataStreamsStatsResponse.java deleted file mode 100644 index 1fa24a0b256b..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/DataStreamsStatsResponse.java +++ /dev/null @@ -1,225 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -package org.elasticsearch.client.indices; - -import org.elasticsearch.client.core.BroadcastResponse; -import org.elasticsearch.common.unit.ByteSizeValue; -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -import static org.elasticsearch.xcontent.ConstructingObjectParser.constructorArg; - -public class DataStreamsStatsResponse extends BroadcastResponse { - - private final int dataStreamCount; - private final int backingIndices; - private final ByteSizeValue totalStoreSize; - private final Map dataStreams; - - protected DataStreamsStatsResponse( - Shards shards, - int dataStreamCount, - int backingIndices, - ByteSizeValue totalStoreSize, - Map dataStreams - ) { - super(shards); - this.dataStreamCount = dataStreamCount; - this.backingIndices = backingIndices; - this.totalStoreSize = totalStoreSize; - this.dataStreams = dataStreams; - } - - private static final ParseField DATA_STREAM_COUNT = new ParseField("data_stream_count"); - private static final ParseField BACKING_INDICES = new ParseField("backing_indices"); - private static final ParseField TOTAL_STORE_SIZE_BYTES = new ParseField("total_store_size_bytes"); - private static final ParseField DATA_STREAMS = new ParseField("data_streams"); - private static final ParseField DATA_STREAM = new ParseField("data_stream"); - private static final ParseField STORE_SIZE_BYTES = new ParseField("store_size_bytes"); - private static final ParseField MAXIMUM_TIMESTAMP = new ParseField("maximum_timestamp"); - - @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); - } - 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); - } - ); - - 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.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.declareLong(constructorArg(), MAXIMUM_TIMESTAMP); - } - - public static DataStreamsStatsResponse fromXContent(final XContentParser parser) throws IOException { - return PARSER.apply(parser, null); - } - - public int getDataStreamCount() { - return dataStreamCount; - } - - public int getBackingIndices() { - return backingIndices; - } - - public ByteSizeValue getTotalStoreSize() { - return totalStoreSize; - } - - public Map getDataStreams() { - return dataStreams; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null || getClass() != obj.getClass()) { - return false; - } - DataStreamsStatsResponse that = (DataStreamsStatsResponse) obj; - return dataStreamCount == that.dataStreamCount - && backingIndices == that.backingIndices - && Objects.equals(totalStoreSize, that.totalStoreSize) - && Objects.equals(dataStreams, that.dataStreams); - } - - @Override - public int hashCode() { - return Objects.hash(dataStreamCount, backingIndices, totalStoreSize, dataStreams); - } - - @Override - public String toString() { - return "DataStreamsStatsResponse{" - + "dataStreamCount=" - + dataStreamCount - + ", backingIndices=" - + backingIndices - + ", totalStoreSize=" - + totalStoreSize - + ", dataStreams=" - + dataStreams - + '}'; - } - - public static class DataStreamStats { - - private final String dataStream; - private final int backingIndices; - private final ByteSizeValue storeSize; - private final long maximumTimestamp; - - public DataStreamStats(String dataStream, int backingIndices, ByteSizeValue storeSize, long maximumTimestamp) { - this.dataStream = dataStream; - this.backingIndices = backingIndices; - this.storeSize = storeSize; - this.maximumTimestamp = maximumTimestamp; - } - - public String getDataStream() { - return dataStream; - } - - public int getBackingIndices() { - return backingIndices; - } - - public ByteSizeValue getStoreSize() { - return storeSize; - } - - public long getMaximumTimestamp() { - return maximumTimestamp; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null || getClass() != obj.getClass()) { - return false; - } - DataStreamStats that = (DataStreamStats) obj; - return backingIndices == that.backingIndices - && maximumTimestamp == that.maximumTimestamp - && Objects.equals(dataStream, that.dataStream) - && Objects.equals(storeSize, that.storeSize); - } - - @Override - public int hashCode() { - return Objects.hash(dataStream, backingIndices, storeSize, maximumTimestamp); - } - - @Override - public String toString() { - return "DataStreamStats{" - + "dataStream='" - + dataStream - + '\'' - + ", backingIndices=" - + backingIndices - + ", storeSize=" - + storeSize - + ", maximumTimestamp=" - + maximumTimestamp - + '}'; - } - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/DeleteAliasRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/DeleteAliasRequest.java deleted file mode 100644 index 8fd70c8183ee..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/DeleteAliasRequest.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -package org.elasticsearch.client.indices; - -import org.elasticsearch.client.TimedRequest; - -public class DeleteAliasRequest extends TimedRequest { - - private final String index; - private final String alias; - - public DeleteAliasRequest(String index, String alias) { - this.index = index; - this.alias = alias; - } - - public String getIndex() { - return index; - } - - public String getAlias() { - return alias; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/DeleteComponentTemplateRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/DeleteComponentTemplateRequest.java deleted file mode 100644 index 1a974e7b6af9..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/DeleteComponentTemplateRequest.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -package org.elasticsearch.client.indices; - -import org.elasticsearch.client.TimedRequest; - -public class DeleteComponentTemplateRequest extends TimedRequest { - - private final String name; - - public DeleteComponentTemplateRequest(String name) { - this.name = name; - } - - public String getName() { - return name; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/DeleteComposableIndexTemplateRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/DeleteComposableIndexTemplateRequest.java deleted file mode 100644 index 506c198676c4..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/DeleteComposableIndexTemplateRequest.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -package org.elasticsearch.client.indices; - -import org.elasticsearch.client.TimedRequest; - -public class DeleteComposableIndexTemplateRequest extends TimedRequest { - - private final String name; - - public DeleteComposableIndexTemplateRequest(String name) { - this.name = name; - } - - public String getName() { - return name; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/DeleteDataStreamRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/DeleteDataStreamRequest.java deleted file mode 100644 index a7eb0022b210..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/DeleteDataStreamRequest.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -package org.elasticsearch.client.indices; - -import org.elasticsearch.client.Validatable; - -public class DeleteDataStreamRequest implements Validatable { - - private final String name; - - public DeleteDataStreamRequest(String name) { - if (name == null) { - throw new IllegalArgumentException("The data stream name cannot be null."); - } - this.name = name; - } - - public String getName() { - return name; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/DetailAnalyzeResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/DetailAnalyzeResponse.java deleted file mode 100644 index 0a76137b3a76..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/DetailAnalyzeResponse.java +++ /dev/null @@ -1,209 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -package org.elasticsearch.client.indices; - -import org.elasticsearch.common.Strings; -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; - -import static org.elasticsearch.xcontent.ConstructingObjectParser.constructorArg; -import static org.elasticsearch.xcontent.ConstructingObjectParser.optionalConstructorArg; - -public class DetailAnalyzeResponse { - - private final boolean customAnalyzer; - private final AnalyzeTokenList analyzer; - private final CharFilteredText[] charfilters; - private final AnalyzeTokenList tokenizer; - private final AnalyzeTokenList[] 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.tokenizer = tokenizer; - this.tokenfilters = tokenfilters == null ? null : tokenfilters.toArray(new AnalyzeTokenList[] {}); - } - - public AnalyzeTokenList analyzer() { - return this.analyzer; - } - - public CharFilteredText[] charfilters() { - return this.charfilters; - } - - public AnalyzeTokenList tokenizer() { - return tokenizer; - } - - public AnalyzeTokenList[] tokenfilters() { - return tokenfilters; - } - - @Override - public boolean equals(Object o) { - 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); - } - - @Override - public int hashCode() { - int result = Objects.hash(customAnalyzer, analyzer, tokenizer); - result = 31 * result + Arrays.hashCode(charfilters); - result = 31 * result + Arrays.hashCode(tokenfilters); - return result; - } - - @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 { - PARSER.declareBoolean(constructorArg(), new ParseField("custom_analyzer")); - PARSER.declareObject(optionalConstructorArg(), AnalyzeTokenList.PARSER, new ParseField("analyzer")); - PARSER.declareObjectArray(optionalConstructorArg(), CharFilteredText.PARSER, new ParseField("charfilters")); - PARSER.declareObject(optionalConstructorArg(), AnalyzeTokenList.PARSER, new ParseField("tokenizer")); - PARSER.declareObjectArray(optionalConstructorArg(), AnalyzeTokenList.PARSER, new ParseField("tokenfilters")); - } - - public static DetailAnalyzeResponse fromXContent(XContentParser parser) throws IOException { - return PARSER.parse(parser, null); - } - - public static class AnalyzeTokenList { - private final String name; - private final AnalyzeResponse.AnalyzeToken[] tokens; - - @Override - public boolean equals(Object o) { - 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); - } - - @Override - public int hashCode() { - int result = Objects.hash(name); - result = 31 * result + Arrays.hashCode(tokens); - return result; - } - - public AnalyzeTokenList(String name, List tokens) { - this.name = name; - this.tokens = tokens.toArray(new AnalyzeResponse.AnalyzeToken[] {}); - } - - public String getName() { - return name; - } - - public AnalyzeResponse.AnalyzeToken[] getTokens() { - return tokens; - } - - @SuppressWarnings("unchecked") - 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")); - } - - public static AnalyzeTokenList fromXContent(XContentParser parser) throws IOException { - return PARSER.parse(parser, null); - } - - } - - public static class CharFilteredText { - private final String name; - private final String[] texts; - - CharFilteredText(String name, String[] texts) { - this.name = name; - if (texts != null) { - this.texts = texts; - } else { - this.texts = Strings.EMPTY_ARRAY; - } - } - - public String getName() { - return name; - } - - public String[] getTexts() { - return texts; - } - - @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])) - ); - - static { - PARSER.declareString(constructorArg(), new ParseField("name")); - PARSER.declareStringArray(constructorArg(), new ParseField("filtered_text")); - } - - public static CharFilteredText fromXContent(XContentParser parser) throws IOException { - return PARSER.parse(parser, null); - } - - @Override - public boolean equals(Object o) { - 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); - } - - @Override - public int hashCode() { - int result = Objects.hash(name); - result = 31 * result + Arrays.hashCode(texts); - return result; - } - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/FreezeIndexRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/FreezeIndexRequest.java deleted file mode 100644 index 59fee301fba2..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/FreezeIndexRequest.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ -package org.elasticsearch.client.indices; - -import org.elasticsearch.action.admin.indices.open.OpenIndexResponse; -import org.elasticsearch.action.support.ActiveShardCount; -import org.elasticsearch.action.support.IndicesOptions; -import org.elasticsearch.client.TimedRequest; - -import java.util.Objects; - -/** - * Request for the _freeze index API - */ -public final class FreezeIndexRequest extends TimedRequest { - - private final String[] indices; - private IndicesOptions indicesOptions; - private ActiveShardCount waitForActiveShards; - - /** - * Creates a new freeze index request - * @param indices the index to freeze - */ - public FreezeIndexRequest(String... indices) { - this.indices = Objects.requireNonNull(indices); - } - - /** - * Returns the indices to freeze - */ - public String[] getIndices() { - return indices; - } - - /** - * Specifies what type of requested indices to ignore and how to deal with wildcard expressions. - * For example indices that don't exist. - * - * @return the current behaviour when it comes to index names and wildcard indices expressions - */ - public IndicesOptions indicesOptions() { - return indicesOptions; - } - - /** - * Specifies what type of requested indices to ignore and how to deal with wildcard expressions. - * For example indices that don't exist. - * - * @param indicesOptions the desired behaviour regarding indices to ignore and wildcard indices expressions - */ - public void setIndicesOptions(IndicesOptions indicesOptions) { - this.indicesOptions = indicesOptions; - } - - /** - * Returns the wait for active shard count or null if the default should be used - */ - public ActiveShardCount getWaitForActiveShards() { - return waitForActiveShards; - } - - /** - * Sets the number of shard copies that should be active for indices opening to return. - * Defaults to {@link ActiveShardCount#DEFAULT}, which will wait for one shard copy - * (the primary) to become active. Set this value to {@link ActiveShardCount#ALL} to - * wait for all shards (primary and all replicas) to be active before returning. - * Otherwise, use {@link ActiveShardCount#from(int)} to set this value to any - * non-negative integer, up to the number of copies per shard (number of replicas + 1), - * to wait for the desired amount of shard copies to become active before returning. - * Indices opening will only wait up until the timeout value for the number of shard copies - * to be active before returning. Check {@link OpenIndexResponse#isShardsAcknowledged()} to - * determine if the requisite shard copies were all started before returning or timing out. - * - * @param waitForActiveShards number of active shard copies to wait on - */ - public void setWaitForActiveShards(ActiveShardCount waitForActiveShards) { - this.waitForActiveShards = waitForActiveShards; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetComponentTemplatesRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetComponentTemplatesRequest.java deleted file mode 100644 index 4ea38bc7f11a..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetComponentTemplatesRequest.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -package org.elasticsearch.client.indices; - -import org.elasticsearch.client.TimedRequest; -import org.elasticsearch.client.Validatable; -import org.elasticsearch.core.Nullable; -import org.elasticsearch.core.TimeValue; - -/** - * A request to read the content of component templates - */ -public class GetComponentTemplatesRequest implements Validatable { - - private final String name; - - private TimeValue masterNodeTimeout = TimedRequest.DEFAULT_MASTER_NODE_TIMEOUT; - private boolean local = false; - - /** - * Create a request to read the content of component template. If no template name is provided, all templates will - * be read - * - * @param name the name of template to read - */ - public GetComponentTemplatesRequest(String name) { - this.name = name; - } - - /** - * @return the name of component template this request is requesting - */ - public String name() { - return name; - } - - /** - * @return the timeout for waiting for the master node to respond - */ - public TimeValue getMasterNodeTimeout() { - return masterNodeTimeout; - } - - public void setMasterNodeTimeout(@Nullable TimeValue masterNodeTimeout) { - this.masterNodeTimeout = masterNodeTimeout; - } - - public void setMasterNodeTimeout(String masterNodeTimeout) { - final TimeValue timeValue = TimeValue.parseTimeValue(masterNodeTimeout, getClass().getSimpleName() + ".masterNodeTimeout"); - setMasterNodeTimeout(timeValue); - } - - /** - * @return true if this request is to read from the local cluster state, rather than the master node - false otherwise - */ - public boolean isLocal() { - return local; - } - - public void setLocal(boolean local) { - this.local = local; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetComponentTemplatesResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetComponentTemplatesResponse.java deleted file mode 100644 index ffb34a71643e..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetComponentTemplatesResponse.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ -package org.elasticsearch.client.indices; - -import org.elasticsearch.cluster.metadata.ComponentTemplate; -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.stream.Collectors; - -public class GetComponentTemplatesResponse { - - public static final ParseField NAME = new ParseField("name"); - public static final ParseField COMPONENT_TEMPLATES = new ParseField("component_templates"); - 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 INNER_PARSER = new ConstructingObjectParser<>( - "named_component_template", - false, - a -> new NamedComponentTemplate((String) a[0], (ComponentTemplate) a[1]) - ); - - static { - INNER_PARSER.declareString(ConstructingObjectParser.constructorArg(), NAME); - INNER_PARSER.declareObject(ConstructingObjectParser.constructorArg(), ComponentTemplate.PARSER, COMPONENT_TEMPLATE); - PARSER.declareObjectArray(ConstructingObjectParser.constructorArg(), INNER_PARSER, COMPONENT_TEMPLATES); - } - - private static class NamedComponentTemplate { - String name; - ComponentTemplate componentTemplate; - - private NamedComponentTemplate(String name, ComponentTemplate componentTemplate) { - this.name = name; - this.componentTemplate = componentTemplate; - } - } - - @Override - public String toString() { - return "GetIndexTemplatesResponse [indexTemplates=" + componentTemplates + "]"; - } - - private final Map componentTemplates; - - GetComponentTemplatesResponse(Map componentTemplates) { - this.componentTemplates = Collections.unmodifiableMap(new LinkedHashMap<>(componentTemplates)); - } - - public Map getComponentTemplates() { - return componentTemplates; - } - - public static GetComponentTemplatesResponse fromXContent(XContentParser parser) throws IOException { - return new GetComponentTemplatesResponse(PARSER.apply(parser, null)); - } - - @Override - public int hashCode() { - return Objects.hash(componentTemplates); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - GetComponentTemplatesResponse other = (GetComponentTemplatesResponse) obj; - return Objects.equals(componentTemplates, other.componentTemplates); - } - -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetComposableIndexTemplateRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetComposableIndexTemplateRequest.java deleted file mode 100644 index a06cafb1905e..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetComposableIndexTemplateRequest.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -package org.elasticsearch.client.indices; - -import org.elasticsearch.client.TimedRequest; -import org.elasticsearch.client.Validatable; -import org.elasticsearch.core.Nullable; -import org.elasticsearch.core.TimeValue; - -/** - * A request to read the content of index templates - */ -public class GetComposableIndexTemplateRequest implements Validatable { - - private final String name; - - private TimeValue masterNodeTimeout = TimedRequest.DEFAULT_MASTER_NODE_TIMEOUT; - private boolean local = false; - - /** - * Create a request to read the content of index template. If no template name is provided, all templates will - * be read - * - * @param name the name of template to read - */ - public GetComposableIndexTemplateRequest(String name) { - this.name = name; - } - - /** - * @return the name of index template this request is requesting - */ - public String name() { - return name; - } - - /** - * @return the timeout for waiting for the master node to respond - */ - public TimeValue getMasterNodeTimeout() { - return masterNodeTimeout; - } - - public void setMasterNodeTimeout(@Nullable TimeValue masterNodeTimeout) { - this.masterNodeTimeout = masterNodeTimeout; - } - - public void setMasterNodeTimeout(String masterNodeTimeout) { - final TimeValue timeValue = TimeValue.parseTimeValue(masterNodeTimeout, getClass().getSimpleName() + ".masterNodeTimeout"); - setMasterNodeTimeout(timeValue); - } - - /** - * @return true if this request is to read from the local cluster state, rather than the master node - false otherwise - */ - public boolean isLocal() { - return local; - } - - public void setLocal(boolean local) { - this.local = local; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetComposableIndexTemplatesResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetComposableIndexTemplatesResponse.java deleted file mode 100644 index 2d9d715bf29d..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetComposableIndexTemplatesResponse.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ -package org.elasticsearch.client.indices; - -import org.elasticsearch.cluster.metadata.ComposableIndexTemplate; -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.stream.Collectors; - -public class GetComposableIndexTemplatesResponse { - - public static final ParseField NAME = new ParseField("name"); - public static final ParseField INDEX_TEMPLATES = new ParseField("index_templates"); - 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 INNER_PARSER = new ConstructingObjectParser<>( - "named_index_template", - false, - a -> new NamedIndexTemplate((String) a[0], (ComposableIndexTemplate) a[1]) - ); - - static { - INNER_PARSER.declareString(ConstructingObjectParser.constructorArg(), NAME); - INNER_PARSER.declareObject(ConstructingObjectParser.constructorArg(), ComposableIndexTemplate.PARSER, INDEX_TEMPLATE); - PARSER.declareObjectArray(ConstructingObjectParser.constructorArg(), INNER_PARSER, INDEX_TEMPLATES); - } - - private static class NamedIndexTemplate { - String name; - ComposableIndexTemplate indexTemplate; - - private NamedIndexTemplate(String name, ComposableIndexTemplate indexTemplate) { - this.name = name; - this.indexTemplate = indexTemplate; - } - } - - @Override - public String toString() { - return "GetIndexTemplatesResponse [indexTemplates=" + indexTemplates + "]"; - } - - private final Map indexTemplates; - - GetComposableIndexTemplatesResponse(Map indexTemplates) { - this.indexTemplates = Collections.unmodifiableMap(new LinkedHashMap<>(indexTemplates)); - } - - public Map getIndexTemplates() { - return indexTemplates; - } - - public static GetComposableIndexTemplatesResponse fromXContent(XContentParser parser) throws IOException { - return new GetComposableIndexTemplatesResponse(PARSER.apply(parser, null)); - } - - @Override - public int hashCode() { - return Objects.hash(indexTemplates); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - GetComposableIndexTemplatesResponse other = (GetComposableIndexTemplatesResponse) obj; - return Objects.equals(indexTemplates, other.indexTemplates); - } - -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetDataStreamRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetDataStreamRequest.java deleted file mode 100644 index 61e62f844ace..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetDataStreamRequest.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -package org.elasticsearch.client.indices; - -import org.elasticsearch.client.Validatable; - -public class GetDataStreamRequest implements Validatable { - - private final String name; - - public GetDataStreamRequest(String name) { - this.name = name; - } - - public String getName() { - return name; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetDataStreamResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetDataStreamResponse.java deleted file mode 100644 index 344a0ce11593..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetDataStreamResponse.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ -package org.elasticsearch.client.indices; - -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashSet; -import java.util.List; -import java.util.Objects; - -public class GetDataStreamResponse { - - private final List dataStreams; - - GetDataStreamResponse(List dataStreams) { - this.dataStreams = dataStreams; - } - - public List getDataStreams() { - return dataStreams; - } - - public static GetDataStreamResponse fromXContent(XContentParser parser) throws IOException { - final List templates = new ArrayList<>(); - for (XContentParser.Token token = parser.nextToken(); token != XContentParser.Token.END_OBJECT; token = parser.nextToken()) { - if (token == XContentParser.Token.START_ARRAY) { - while (parser.nextToken() != XContentParser.Token.END_ARRAY) { - templates.add(DataStream.fromXContent(parser)); - } - } - } - return new GetDataStreamResponse(templates); - } - - @Override - public int hashCode() { - return Objects.hash(new HashSet<>(this.dataStreams)); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - GetDataStreamResponse other = (GetDataStreamResponse) obj; - return Objects.equals(new HashSet<>(this.dataStreams), new HashSet<>(other.dataStreams)); - } - - @Override - public String toString() { - List thisList = new ArrayList<>(this.dataStreams); - thisList.sort(Comparator.comparing(DataStream::getName)); - return "GetDataStreamResponse [dataStreams=" + thisList + "]"; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetFieldMappingsRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetFieldMappingsRequest.java deleted file mode 100644 index fdcbd1a240ba..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetFieldMappingsRequest.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -package org.elasticsearch.client.indices; - -import org.elasticsearch.action.support.IndicesOptions; -import org.elasticsearch.client.Validatable; -import org.elasticsearch.common.Strings; - -/** Request the mappings of specific fields */ -public class GetFieldMappingsRequest implements Validatable { - - private String[] fields = Strings.EMPTY_ARRAY; - - private boolean includeDefaults = false; - - private String[] indices = Strings.EMPTY_ARRAY; - - private IndicesOptions indicesOptions; - - public GetFieldMappingsRequest indices(String... indices) { - this.indices = indices; - return this; - } - - public GetFieldMappingsRequest indicesOptions(IndicesOptions indicesOptions) { - this.indicesOptions = indicesOptions; - return this; - } - - public String[] indices() { - return indices; - } - - public IndicesOptions indicesOptions() { - return indicesOptions; - } - - /** @param fields a list of fields to retrieve the mapping for */ - public GetFieldMappingsRequest fields(String... fields) { - this.fields = fields; - return this; - } - - public String[] fields() { - return fields; - } - - public boolean includeDefaults() { - return includeDefaults; - } - - /** Indicates whether default mapping settings should be returned */ - public GetFieldMappingsRequest includeDefaults(boolean includeDefaults) { - this.includeDefaults = includeDefaults; - return this; - } - -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetFieldMappingsResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetFieldMappingsResponse.java deleted file mode 100644 index 3683d46b359d..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetFieldMappingsResponse.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -package org.elasticsearch.client.indices; - -import org.elasticsearch.common.bytes.BytesReference; -import org.elasticsearch.common.xcontent.XContentHelper; -import org.elasticsearch.index.mapper.Mapper; -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentBuilder; -import org.elasticsearch.xcontent.XContentParser; -import org.elasticsearch.xcontent.XContentType; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; - -import static org.elasticsearch.common.xcontent.XContentParserUtils.ensureExpectedToken; -import static org.elasticsearch.xcontent.ConstructingObjectParser.optionalConstructorArg; -import static org.elasticsearch.xcontent.XContentFactory.jsonBuilder; - -/** Response object for {@link GetFieldMappingsRequest} API */ -public class GetFieldMappingsResponse { - - private static final ParseField MAPPINGS = new ParseField("mappings"); - - private static final ObjectParser, String> PARSER = new ObjectParser<>( - MAPPINGS.getPreferredName(), - true, - HashMap::new - ); - - static { - PARSER.declareField((p, fieldMappings, index) -> { - p.nextToken(); - while (p.currentToken() == XContentParser.Token.FIELD_NAME) { - final String fieldName = p.currentName(); - final FieldMappingMetadata fieldMappingMetadata = FieldMappingMetadata.fromXContent(p); - fieldMappings.put(fieldName, fieldMappingMetadata); - p.nextToken(); - } - }, MAPPINGS, ObjectParser.ValueType.OBJECT); - } - - private Map> mappings; - - GetFieldMappingsResponse(Map> mappings) { - this.mappings = mappings; - } - - /** - * Returns the fields mapping. The return map keys are indexes and fields (as specified in the request). - */ - public Map> mappings() { - return mappings; - } - - /** - * Returns the mappings of a specific index and field. - * - * @param field field name as specified in the {@link GetFieldMappingsRequest} - * @return FieldMappingMetadata for the requested field or null if not found. - */ - public FieldMappingMetadata fieldMappings(String index, String field) { - Map indexMapping = mappings.get(index); - if (indexMapping == null) { - return null; - } - 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<>(); - if (parser.nextToken() == XContentParser.Token.FIELD_NAME) { - while (parser.currentToken() == XContentParser.Token.FIELD_NAME) { - final String index = parser.currentName(); - final Map fieldMappings = PARSER.parse(parser, index); - mappings.put(index, fieldMappings); - parser.nextToken(); - } - } - return new GetFieldMappingsResponse(mappings); - } - - public static class FieldMappingMetadata { - 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]) - ); - - 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); - } - - private String fullName; - private BytesReference source; - - public FieldMappingMetadata(String fullName, BytesReference source) { - this.fullName = fullName; - this.source = source; - } - - public String fullName() { - return fullName; - } - - /** - * Returns the mappings as a map. Note that the returned map has a single key which is always the field's {@link Mapper#name}. - */ - public Map sourceAsMap() { - return XContentHelper.convertToMap(source, true, XContentType.JSON).v2(); - } - - // pkg-private for testing - BytesReference getSource() { - return source; - } - - public static FieldMappingMetadata fromXContent(XContentParser parser) throws IOException { - return PARSER.parse(parser, null); - } - - @Override - public String toString() { - return "FieldMappingMetadata{fullName='" + fullName + '\'' + ", source=" + source + '}'; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if ((o instanceof FieldMappingMetadata) == false) return false; - FieldMappingMetadata that = (FieldMappingMetadata) o; - return Objects.equals(fullName, that.fullName) && Objects.equals(source, that.source); - } - - @Override - public int hashCode() { - return Objects.hash(fullName, source); - } - } - - @Override - public String toString() { - return "GetFieldMappingsResponse{" + "mappings=" + mappings + '}'; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if ((o instanceof GetFieldMappingsResponse) == false) return false; - GetFieldMappingsResponse that = (GetFieldMappingsResponse) o; - return Objects.equals(mappings, that.mappings); - } - - @Override - public int hashCode() { - return Objects.hash(mappings); - } - -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetIndexRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetIndexRequest.java deleted file mode 100644 index 53340711f82a..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetIndexRequest.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -package org.elasticsearch.client.indices; - -import org.elasticsearch.action.support.IndicesOptions; -import org.elasticsearch.client.TimedRequest; -import org.elasticsearch.common.util.ArrayUtils; - -/** - * A request to retrieve information about an index. - */ -public class GetIndexRequest extends TimedRequest { - - public enum Feature { - ALIASES, - MAPPINGS, - SETTINGS; - } - - public static final IndicesOptions DEFAULT_INDICES_OPTIONS = IndicesOptions.fromOptions(false, false, true, true); - - static final Feature[] DEFAULT_FEATURES = new Feature[] { Feature.ALIASES, Feature.MAPPINGS, Feature.SETTINGS }; - private Feature[] features = DEFAULT_FEATURES; - private boolean humanReadable = false; - private transient boolean includeDefaults = false; - - private final String[] indices; - private IndicesOptions indicesOptions = DEFAULT_INDICES_OPTIONS; - private boolean local = false; - - public GetIndexRequest(String... indices) { - this.indices = indices; - } - - /** - * The indices into which the mappings will be put. - */ - public String[] indices() { - return indices; - } - - public IndicesOptions indicesOptions() { - return indicesOptions; - } - - public GetIndexRequest indicesOptions(IndicesOptions indicesOptions) { - this.indicesOptions = indicesOptions; - return this; - } - - public final GetIndexRequest local(boolean local) { - this.local = local; - return this; - } - - /** - * Return local information, do not retrieve the state from master node (default: false). - * @return true if local information is to be returned; - * false if information is to be retrieved from master node (default). - */ - public final boolean local() { - return local; - } - - public GetIndexRequest features(Feature... features) { - if (features == null) { - throw new IllegalArgumentException("features cannot be null"); - } else { - this.features = features; - } - return this; - } - - public GetIndexRequest addFeatures(Feature... featuresToAdd) { - if (this.features == DEFAULT_FEATURES) { - return features(featuresToAdd); - } else { - return features(ArrayUtils.concat(features(), featuresToAdd, Feature.class)); - } - } - - public Feature[] features() { - return features; - } - - public GetIndexRequest humanReadable(boolean humanReadable) { - this.humanReadable = humanReadable; - return this; - } - - public boolean humanReadable() { - return humanReadable; - } - - /** - * Sets the value of "include_defaults". - * - * @param includeDefaults value of "include_defaults" to be set. - * @return this request - */ - public GetIndexRequest includeDefaults(boolean includeDefaults) { - this.includeDefaults = includeDefaults; - return this; - } - - /** - * Whether to return all default settings for each of the indices. - * - * @return true if defaults settings for each of the indices need to returned; - * false otherwise. - */ - public boolean includeDefaults() { - return includeDefaults; - } - -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetIndexResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetIndexResponse.java deleted file mode 100644 index 1d922a7f641e..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetIndexResponse.java +++ /dev/null @@ -1,232 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -package org.elasticsearch.client.indices; - -import org.apache.lucene.util.CollectionUtil; -import org.elasticsearch.cluster.metadata.AliasMetadata; -import org.elasticsearch.cluster.metadata.MappingMetadata; -import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.index.mapper.MapperService; -import org.elasticsearch.xcontent.XContentParser; -import org.elasticsearch.xcontent.XContentParser.Token; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.elasticsearch.common.xcontent.XContentParserUtils.ensureExpectedToken; - -/** - * A client side response for a get index action. - */ -public class GetIndexResponse { - - private Map mappings; - private Map> aliases; - private Map settings; - private Map defaultSettings; - private Map dataStreams; - private String[] indices; - - GetIndexResponse( - String[] indices, - Map mappings, - Map> aliases, - Map settings, - Map defaultSettings, - Map dataStreams - ) { - this.indices = indices; - // to have deterministic order - Arrays.sort(indices); - if (mappings != null) { - this.mappings = mappings; - } - if (aliases != null) { - this.aliases = aliases; - } - if (settings != null) { - this.settings = settings; - } - if (defaultSettings != null) { - this.defaultSettings = defaultSettings; - } - if (dataStreams != null) { - this.dataStreams = dataStreams; - } - } - - public String[] getIndices() { - return indices; - } - - public Map getMappings() { - return mappings; - } - - public Map> getAliases() { - return aliases; - } - - /** - * If the originating {@link GetIndexRequest} object was configured to include - * defaults, this will contain a mapping of index name to {@link Settings} objects. - * The returned {@link Settings} objects will contain only those settings taking - * effect as defaults. Any settings explicitly set on the index will be available - * via {@link #getSettings()}. - * See also {@link GetIndexRequest#includeDefaults(boolean)} - */ - public Map getDefaultSettings() { - return defaultSettings; - } - - public Map getSettings() { - return settings; - } - - public Map getDataStreams() { - return dataStreams; - } - - /** - * Returns the string value for the specified index and setting. If the includeDefaults flag was not set or set to - * false on the {@link GetIndexRequest}, this method will only return a value where the setting was explicitly set - * on the index. If the includeDefaults flag was set to true on the {@link GetIndexRequest}, this method will fall - * back to return the default value if the setting was not explicitly set. - */ - public String getSetting(String index, String setting) { - Settings indexSettings = settings.get(index); - if (setting != null) { - if (indexSettings != null && indexSettings.hasValue(setting)) { - return indexSettings.get(setting); - } else { - Settings defaultIndexSettings = defaultSettings.get(index); - if (defaultIndexSettings != null) { - return defaultIndexSettings.get(setting); - } else { - return null; - } - } - } else { - return null; - } - } - - private static List parseAliases(XContentParser parser) throws IOException { - List indexAliases = new ArrayList<>(); - // We start at START_OBJECT since parseIndexEntry ensures that - while (parser.nextToken() != Token.END_OBJECT) { - ensureExpectedToken(Token.FIELD_NAME, parser.currentToken(), parser); - indexAliases.add(AliasMetadata.Builder.fromXContent(parser)); - } - return indexAliases; - } - - private static MappingMetadata parseMappings(XContentParser parser) throws IOException { - return new MappingMetadata(MapperService.SINGLE_MAPPING_NAME, parser.map()); - } - - private static IndexEntry parseIndexEntry(XContentParser parser) throws IOException { - List indexAliases = null; - MappingMetadata indexMappings = null; - Settings indexSettings = null; - Settings indexDefaultSettings = null; - String dataStream = null; - // We start at START_OBJECT since fromXContent ensures that - while (parser.nextToken() != Token.END_OBJECT) { - ensureExpectedToken(Token.FIELD_NAME, parser.currentToken(), parser); - parser.nextToken(); - if (parser.currentToken() == Token.START_OBJECT) { - switch (parser.currentName()) { - case "aliases" -> indexAliases = parseAliases(parser); - case "mappings" -> indexMappings = parseMappings(parser); - case "settings" -> indexSettings = Settings.fromXContent(parser); - case "defaults" -> indexDefaultSettings = Settings.fromXContent(parser); - default -> parser.skipChildren(); - } - } else if (parser.currentToken() == Token.VALUE_STRING) { - if (parser.currentName().equals("data_stream")) { - dataStream = parser.text(); - } - parser.skipChildren(); - } else if (parser.currentToken() == Token.START_ARRAY) { - parser.skipChildren(); - } - } - return new IndexEntry(indexAliases, indexMappings, indexSettings, indexDefaultSettings, dataStream); - } - - // This is just an internal container to make stuff easier for returning - private static class IndexEntry { - List indexAliases = new ArrayList<>(); - MappingMetadata indexMappings; - Settings indexSettings = Settings.EMPTY; - Settings indexDefaultSettings = Settings.EMPTY; - 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; - if (indexDefaultSettings != null) this.indexDefaultSettings = indexDefaultSettings; - if (dataStream != null) this.dataStream = dataStream; - } - } - - public static GetIndexResponse fromXContent(XContentParser parser) throws IOException { - Map> aliases = new HashMap<>(); - Map mappings = new HashMap<>(); - Map settings = new HashMap<>(); - Map defaultSettings = new HashMap<>(); - Map dataStreams = new HashMap<>(); - List indices = new ArrayList<>(); - - if (parser.currentToken() == null) { - parser.nextToken(); - } - ensureExpectedToken(Token.START_OBJECT, parser.currentToken(), parser); - parser.nextToken(); - - while (parser.isClosed() == false) { - if (parser.currentToken() == Token.START_OBJECT) { - // we assume this is an index entry - String indexName = parser.currentName(); - indices.add(indexName); - IndexEntry indexEntry = parseIndexEntry(parser); - // make the order deterministic - CollectionUtil.timSort(indexEntry.indexAliases, Comparator.comparing(AliasMetadata::alias)); - aliases.put(indexName, Collections.unmodifiableList(indexEntry.indexAliases)); - mappings.put(indexName, indexEntry.indexMappings); - settings.put(indexName, indexEntry.indexSettings); - if (indexEntry.indexDefaultSettings.isEmpty() == false) { - defaultSettings.put(indexName, indexEntry.indexDefaultSettings); - } - if (indexEntry.dataStream != null) { - dataStreams.put(indexName, indexEntry.dataStream); - } - } else if (parser.currentToken() == Token.START_ARRAY) { - parser.skipChildren(); - } else { - parser.nextToken(); - } - } - return new GetIndexResponse(indices.toArray(new String[0]), mappings, aliases, settings, defaultSettings, dataStreams); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetIndexTemplatesRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetIndexTemplatesRequest.java deleted file mode 100644 index a3ad6c4a9100..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetIndexTemplatesRequest.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -package org.elasticsearch.client.indices; - -import org.elasticsearch.client.TimedRequest; -import org.elasticsearch.client.Validatable; -import org.elasticsearch.common.Strings; -import org.elasticsearch.core.Nullable; -import org.elasticsearch.core.TimeValue; - -import java.util.Arrays; -import java.util.List; -import java.util.Objects; - -import static java.util.Collections.unmodifiableList; - -/** - * A request to read the content of index templates - */ -public class GetIndexTemplatesRequest implements Validatable { - - private final List names; - - private TimeValue masterNodeTimeout = TimedRequest.DEFAULT_MASTER_NODE_TIMEOUT; - private boolean local = false; - - /** - * Create a request to read the content of one or more index templates. If no template names are provided, all templates will be read - * - * @param names the names of templates to read - */ - public GetIndexTemplatesRequest(String... names) { - this(Arrays.asList(names)); - } - - /** - * Create a request to read the content of one or more index templates. If no template names are provided, all templates will be read - * - * @param names the names of templates to read - */ - public GetIndexTemplatesRequest(List names) { - Objects.requireNonNull(names); - if (names.stream().anyMatch(name -> name == null || Strings.hasText(name) == false)) { - throw new IllegalArgumentException("all index template names must be non null and non empty"); - } - this.names = unmodifiableList(names); - } - - /** - * @return the names of index templates this request is requesting - */ - public List names() { - return names; - } - - /** - * @return the timeout for waiting for the master node to respond - */ - public TimeValue getMasterNodeTimeout() { - return masterNodeTimeout; - } - - public void setMasterNodeTimeout(@Nullable TimeValue masterNodeTimeout) { - this.masterNodeTimeout = masterNodeTimeout; - } - - public void setMasterNodeTimeout(String masterNodeTimeout) { - final TimeValue timeValue = TimeValue.parseTimeValue(masterNodeTimeout, getClass().getSimpleName() + ".masterNodeTimeout"); - setMasterNodeTimeout(timeValue); - } - - /** - * @return true if this request is to read from the local cluster state, rather than the master node - false otherwise - */ - public boolean isLocal() { - return local; - } - - public void setLocal(boolean local) { - this.local = local; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetIndexTemplatesResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetIndexTemplatesResponse.java deleted file mode 100644 index fbdf82ad21b1..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetIndexTemplatesResponse.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ -package org.elasticsearch.client.indices; - -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.Objects; - -public class GetIndexTemplatesResponse { - - @Override - public String toString() { - List thisList = new ArrayList<>(this.indexTemplates); - thisList.sort(Comparator.comparing(IndexTemplateMetadata::name)); - return "GetIndexTemplatesResponse [indexTemplates=" + thisList + "]"; - } - - private final List indexTemplates; - - GetIndexTemplatesResponse() { - indexTemplates = new ArrayList<>(); - } - - GetIndexTemplatesResponse(List indexTemplates) { - this.indexTemplates = indexTemplates; - } - - public List getIndexTemplates() { - 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()) { - if (token == XContentParser.Token.FIELD_NAME) { - final IndexTemplateMetadata templateMetadata = IndexTemplateMetadata.Builder.fromXContent(parser, parser.currentName()); - templates.add(templateMetadata); - } - } - return new GetIndexTemplatesResponse(templates); - } - - @Override - public int hashCode() { - List sortedList = new ArrayList<>(this.indexTemplates); - sortedList.sort(Comparator.comparing(IndexTemplateMetadata::name)); - return Objects.hash(sortedList); - } - - @Override - public boolean equals(Object obj) { - 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); - List otherList = new ArrayList<>(other.indexTemplates); - thisList.sort(Comparator.comparing(IndexTemplateMetadata::name)); - otherList.sort(Comparator.comparing(IndexTemplateMetadata::name)); - return Objects.equals(thisList, otherList); - } - -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetMappingsRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetMappingsRequest.java deleted file mode 100644 index 29c4df678a18..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetMappingsRequest.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -package org.elasticsearch.client.indices; - -import org.elasticsearch.action.support.IndicesOptions; -import org.elasticsearch.client.TimedRequest; -import org.elasticsearch.common.Strings; - -public class GetMappingsRequest extends TimedRequest { - - private boolean local = false; - private boolean includeDefaults = false; - private String[] indices = Strings.EMPTY_ARRAY; - private IndicesOptions indicesOptions; - - /** - * Indicates whether the receiving node should operate based on local index information or - * forward requests, where needed, to other nodes. If running locally, request will not - * raise errors if local index information is missing. - */ - public GetMappingsRequest local(boolean local) { - this.local = local; - return this; - } - - public boolean local() { - return local; - } - - public GetMappingsRequest indices(String... indices) { - this.indices = indices; - return this; - } - - public GetMappingsRequest indicesOptions(IndicesOptions indicesOptions) { - this.indicesOptions = indicesOptions; - return this; - } - - public String[] indices() { - return indices; - } - - public IndicesOptions indicesOptions() { - return indicesOptions; - } - - public boolean includeDefaults() { - return includeDefaults; - } - - /** Indicates whether default mapping settings should be returned */ - public GetMappingsRequest includeDefaults(boolean includeDefaults) { - this.includeDefaults = includeDefaults; - return this; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetMappingsResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetMappingsResponse.java deleted file mode 100644 index 1ccf18e75e67..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/GetMappingsResponse.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -package org.elasticsearch.client.indices; - -import org.elasticsearch.cluster.metadata.MappingMetadata; -import org.elasticsearch.common.xcontent.XContentParserUtils; -import org.elasticsearch.index.mapper.MapperService; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -public class GetMappingsResponse { - - static final ParseField MAPPINGS = new ParseField("mappings"); - - private Map mappings; - - public GetMappingsResponse(Map mappings) { - this.mappings = mappings; - } - - public Map mappings() { - return mappings; - } - - public static GetMappingsResponse fromXContent(XContentParser parser) throws IOException { - if (parser.currentToken() == null) { - parser.nextToken(); - } - - XContentParserUtils.ensureExpectedToken(parser.currentToken(), XContentParser.Token.START_OBJECT, parser); - - Map parts = parser.map(); - - Map mappings = new HashMap<>(); - for (Map.Entry entry : parts.entrySet()) { - String indexName = entry.getKey(); - 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() - ); - - mappings.put(indexName, new MappingMetadata(MapperService.SINGLE_MAPPING_NAME, fieldMappings)); - } - - return new GetMappingsResponse(mappings); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/IndexTemplateMetadata.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/IndexTemplateMetadata.java deleted file mode 100644 index 5ee3fff8a54a..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/IndexTemplateMetadata.java +++ /dev/null @@ -1,263 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ -package org.elasticsearch.client.indices; - -import org.elasticsearch.cluster.metadata.AliasMetadata; -import org.elasticsearch.cluster.metadata.IndexMetadata; -import org.elasticsearch.cluster.metadata.MappingMetadata; -import org.elasticsearch.common.collect.ImmutableOpenMap; -import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.core.Nullable; -import org.elasticsearch.index.mapper.MapperService; -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.AbstractMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.stream.Collectors; - -import static org.elasticsearch.xcontent.ConstructingObjectParser.optionalConstructorArg; - -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().putAllFromMap( - 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")); - PARSER.declareInt(optionalConstructorArg(), new ParseField("version")); - PARSER.declareStringArray(optionalConstructorArg(), new ParseField("index_patterns")); - PARSER.declareObject(optionalConstructorArg(), (p, c) -> { - Settings.Builder templateSettingsBuilder = Settings.builder(); - templateSettingsBuilder.put(Settings.fromXContent(p)); - templateSettingsBuilder.normalizePrefix(IndexMetadata.INDEX_SETTING_PREFIX); - return templateSettingsBuilder.build(); - }, new ParseField("settings")); - PARSER.declareObject(optionalConstructorArg(), (p, c) -> { - Map mapping = p.map(); - if (mapping.isEmpty()) { - return null; - } - 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") - ); - } - - private final String name; - - private final int order; - - /** - * The version is an arbitrary number managed by the user so that they can easily and quickly verify the existence of a given template. - * Expected usage: - *


-     * PUT /_template/my_template
-     * {
-     *   "index_patterns": ["my_index-*"],
-     *   "mappings": { ... },
-     *   "version": 1
-     * }
-     * 
- * Then, some process from the user can occasionally verify that the template exists with the appropriate version without having to - * check the template's content: - *

-     * GET /_template/my_template?filter_path=*.version
-     * 
- */ - @Nullable - private final Integer version; - - private final List patterns; - - private final Settings settings; - - private final MappingMetadata mappings; - - private final 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.settings = settings; - this.mappings = mappings; - this.aliases = aliases; - } - - public String name() { - return this.name; - } - - public int order() { - return this.order; - } - - @Nullable - public Integer version() { - return version; - } - - public List patterns() { - return this.patterns; - } - - public Settings settings() { - return this.settings; - } - - public MappingMetadata mappings() { - return this.mappings; - } - - public ImmutableOpenMap aliases() { - return this.aliases; - } - - public static Builder builder(String name) { - return new Builder(name); - } - - @Override - public boolean equals(Object o) { - 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); - } - - @Override - public int hashCode() { - return Objects.hash(name, order, version, patterns, settings, mappings, aliases); - } - - public static class Builder { - - private String name; - - private int order; - - private Integer version; - - private List indexPatterns; - - private Settings settings = Settings.EMPTY; - - private MappingMetadata mappings; - - private final ImmutableOpenMap.Builder aliases; - - public Builder(String name) { - this.name = name; - mappings = null; - aliases = ImmutableOpenMap.builder(); - } - - public Builder(IndexTemplateMetadata indexTemplateMetadata) { - this.name = indexTemplateMetadata.name(); - order(indexTemplateMetadata.order()); - version(indexTemplateMetadata.version()); - patterns(indexTemplateMetadata.patterns()); - settings(indexTemplateMetadata.settings()); - - mappings = indexTemplateMetadata.mappings(); - aliases = ImmutableOpenMap.builder(indexTemplateMetadata.aliases()); - } - - public Builder order(int order) { - this.order = order; - return this; - } - - public Builder version(Integer version) { - this.version = version; - return this; - } - - public Builder patterns(List patterns) { - this.indexPatterns = patterns; - return this; - } - - public Builder settings(Settings.Builder settings) { - this.settings = settings.build(); - return this; - } - - public Builder settings(Settings settings) { - this.settings = settings; - return this; - } - - public Builder mapping(MappingMetadata mappingMetadata) { - this.mappings = mappingMetadata; - return this; - } - - public Builder putAlias(AliasMetadata aliasMetadata) { - aliases.put(aliasMetadata.alias(), aliasMetadata); - return this; - } - - public Builder putAlias(AliasMetadata.Builder aliasMetadata) { - aliases.put(aliasMetadata.alias(), aliasMetadata.build()); - return this; - } - - public IndexTemplateMetadata build() { - 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/elasticsearch/client/indices/IndexTemplatesExistRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/IndexTemplatesExistRequest.java deleted file mode 100644 index f505babc15ce..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/IndexTemplatesExistRequest.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -package org.elasticsearch.client.indices; - -import java.util.Arrays; -import java.util.List; - -/** - * A request to check for the existence of index templates - */ -public class IndexTemplatesExistRequest extends GetIndexTemplatesRequest { - - /** - * Create a request to check for the existence of index templates. At least one template index name must be provided - * - * @param names the names of templates to check for the existence of - */ - public IndexTemplatesExistRequest(String... names) { - this(Arrays.asList(names)); - } - - /** - * Create a request to check for the existence of index templates. At least one template index name must be provided - * - * @param names the names of templates to check for the existence of - */ - public IndexTemplatesExistRequest(List names) { - super(names); - if (names().isEmpty()) { - throw new IllegalArgumentException("must provide at least one index template name"); - } - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/PutComponentTemplateRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/PutComponentTemplateRequest.java deleted file mode 100644 index 0ca1993e8955..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/PutComponentTemplateRequest.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ -package org.elasticsearch.client.indices; - -import org.elasticsearch.client.TimedRequest; -import org.elasticsearch.cluster.metadata.ComponentTemplate; -import org.elasticsearch.common.Strings; -import org.elasticsearch.xcontent.ToXContentObject; -import org.elasticsearch.xcontent.XContentBuilder; - -import java.io.IOException; - -/** - * A request to create an component template. - */ -public class PutComponentTemplateRequest extends TimedRequest implements ToXContentObject { - - private String name; - - private String cause = ""; - - private boolean create; - - private ComponentTemplate componentTemplate; - - /** - * Sets the name of the component template. - */ - public PutComponentTemplateRequest name(String name) { - if (Strings.isNullOrEmpty(name)) { - throw new IllegalArgumentException("name cannot be null or empty"); - } - this.name = name; - return this; - } - - /** - * The name of the component template. - */ - public String name() { - return this.name; - } - - /** - * Set to {@code true} to force only creation, not an update of an component template. If it already - * exists, it will fail with an {@link IllegalArgumentException}. - */ - public PutComponentTemplateRequest create(boolean create) { - this.create = create; - return this; - } - - public boolean create() { - return create; - } - - /** - * The component template to create. - */ - public PutComponentTemplateRequest componentTemplate(ComponentTemplate componentTemplate) { - this.componentTemplate = componentTemplate; - return this; - } - - /** - * The cause for this component template creation. - */ - public PutComponentTemplateRequest cause(String cause) { - this.cause = cause; - return this; - } - - public String cause() { - return this.cause; - } - - @Override - public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - if (componentTemplate != null) { - componentTemplate.toXContent(builder, params); - } - return builder; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/PutComposableIndexTemplateRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/PutComposableIndexTemplateRequest.java deleted file mode 100644 index e683db04523f..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/PutComposableIndexTemplateRequest.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ -package org.elasticsearch.client.indices; - -import org.elasticsearch.client.TimedRequest; -import org.elasticsearch.cluster.metadata.ComposableIndexTemplate; -import org.elasticsearch.common.Strings; -import org.elasticsearch.xcontent.ToXContentObject; -import org.elasticsearch.xcontent.XContentBuilder; - -import java.io.IOException; - -/** - * A request to create an index template. - */ -public class PutComposableIndexTemplateRequest extends TimedRequest implements ToXContentObject { - - private String name; - - private String cause = ""; - - private boolean create; - - private ComposableIndexTemplate indexTemplate; - - /** - * Sets the name of the index template. - */ - public PutComposableIndexTemplateRequest name(String name) { - if (Strings.isNullOrEmpty(name)) { - throw new IllegalArgumentException("name cannot be null or empty"); - } - this.name = name; - return this; - } - - /** - * The name of the index template. - */ - public String name() { - return this.name; - } - - /** - * Set to {@code true} to force only creation, not an update of an index template. If it already - * exists, it will fail with an {@link IllegalArgumentException}. - */ - public PutComposableIndexTemplateRequest create(boolean create) { - this.create = create; - return this; - } - - public boolean create() { - return create; - } - - /** - * The index template to create. - */ - public PutComposableIndexTemplateRequest indexTemplate(ComposableIndexTemplate indexTemplate) { - this.indexTemplate = indexTemplate; - return this; - } - - /** - * The cause for this index template creation. - */ - public PutComposableIndexTemplateRequest cause(String cause) { - this.cause = cause; - return this; - } - - public String cause() { - return this.cause; - } - - @Override - public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - if (indexTemplate != null) { - indexTemplate.toXContent(builder, params); - } - return builder; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/PutIndexTemplateRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/PutIndexTemplateRequest.java deleted file mode 100644 index c999ceda70be..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/PutIndexTemplateRequest.java +++ /dev/null @@ -1,423 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ -package org.elasticsearch.client.indices; - -import org.elasticsearch.ElasticsearchGenerationException; -import org.elasticsearch.ElasticsearchParseException; -import org.elasticsearch.action.admin.indices.alias.Alias; -import org.elasticsearch.client.TimedRequest; -import org.elasticsearch.common.bytes.BytesArray; -import org.elasticsearch.common.bytes.BytesReference; -import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.common.xcontent.XContentHelper; -import org.elasticsearch.common.xcontent.support.XContentMapValues; -import org.elasticsearch.core.TimeValue; -import org.elasticsearch.xcontent.ToXContentFragment; -import org.elasticsearch.xcontent.XContentBuilder; -import org.elasticsearch.xcontent.XContentFactory; -import org.elasticsearch.xcontent.XContentParser; -import org.elasticsearch.xcontent.XContentParserConfiguration; -import org.elasticsearch.xcontent.XContentType; -import org.elasticsearch.xcontent.json.JsonXContent; - -import java.io.IOException; -import java.io.UncheckedIOException; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.stream.Collectors; - -/** - * A request to create an index template. - */ -public class PutIndexTemplateRequest extends TimedRequest implements ToXContentFragment { - - private String name; - - private String cause = ""; - - private List indexPatterns; - - private int order; - - private boolean create; - - private Settings settings = Settings.EMPTY; - - private BytesReference mappings = null; - - private final Set aliases = new HashSet<>(); - - private Integer version; - - /** - * Constructs a new put index template request with the provided name and patterns. - */ - public PutIndexTemplateRequest(String name, List indexPatterns) { - this.name(name); - this.patterns(indexPatterns); - } - - /** - * Sets the name of the index template. - */ - public PutIndexTemplateRequest name(String name) { - if (name == null) { - throw new IllegalArgumentException("Name cannot be null"); - } - this.name = name; - return this; - } - - /** - * The name of the index template. - */ - public String name() { - return this.name; - } - - public PutIndexTemplateRequest patterns(List patterns) { - if (patterns == null || patterns.size() == 0) { - throw new IllegalArgumentException("index patterns are missing"); - } - this.indexPatterns = patterns; - return this; - } - - public List patterns() { - return this.indexPatterns; - } - - public PutIndexTemplateRequest order(int order) { - this.order = order; - return this; - } - - public int order() { - return this.order; - } - - public PutIndexTemplateRequest version(Integer version) { - this.version = version; - return this; - } - - public Integer version() { - return this.version; - } - - /** - * Set to {@code true} to force only creation, not an update of an index template. If it already - * exists, it will fail with an {@link IllegalArgumentException}. - */ - public PutIndexTemplateRequest create(boolean create) { - this.create = create; - return this; - } - - public boolean create() { - return create; - } - - /** - * The settings to create the index template with. - */ - public PutIndexTemplateRequest settings(Settings settings) { - this.settings = settings; - return this; - } - - /** - * The settings to create the index template with. - */ - public PutIndexTemplateRequest settings(Settings.Builder settings) { - this.settings = settings.build(); - return this; - } - - /** - * The settings to create the index template with (either json/yaml format). - */ - public PutIndexTemplateRequest settings(String source, XContentType xContentType) { - this.settings = Settings.builder().loadFromSource(source, xContentType).build(); - return this; - } - - /** - * The settings to create the index template with (either json or yaml format). - */ - public PutIndexTemplateRequest settings(Map source) { - this.settings = Settings.builder().loadFromMap(source).build(); - return this; - } - - public Settings settings() { - return this.settings; - } - - /** - * Adds mapping that will be added when the index gets created. - * - * @param source The mapping source - * @param xContentType The type of content contained within the source - */ - public PutIndexTemplateRequest mapping(String source, XContentType xContentType) { - internalMapping(XContentHelper.convertToMap(new BytesArray(source), true, xContentType).v2()); - return this; - } - - /** - * The cause for this index template creation. - */ - public PutIndexTemplateRequest cause(String cause) { - this.cause = cause; - return this; - } - - public String cause() { - return this.cause; - } - - /** - * Adds mapping that will be added when the index gets created. - * - * @param source The mapping source - */ - public PutIndexTemplateRequest mapping(XContentBuilder source) { - internalMapping(XContentHelper.convertToMap(BytesReference.bytes(source), true, source.contentType()).v2()); - return this; - } - - /** - * Adds mapping that will be added when the index gets created. - * - * @param source The mapping source - * @param xContentType the source content type - */ - public PutIndexTemplateRequest mapping(BytesReference source, XContentType xContentType) { - internalMapping(XContentHelper.convertToMap(source, true, xContentType).v2()); - return this; - } - - /** - * Adds mapping that will be added when the index gets created. - * - * @param source The mapping source - */ - public PutIndexTemplateRequest mapping(Map source) { - return internalMapping(source); - } - - private PutIndexTemplateRequest internalMapping(Map source) { - try { - XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON); - builder.map(source); - Objects.requireNonNull(builder.contentType()); - try { - mappings = new BytesArray(XContentHelper.convertToJson(BytesReference.bytes(builder), false, false, builder.contentType())); - return this; - } catch (IOException e) { - throw new UncheckedIOException("failed to convert source to json", e); - } - } catch (IOException e) { - throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e); - } - } - - public BytesReference mappings() { - return this.mappings; - } - - /** - * The template source definition. - */ - public PutIndexTemplateRequest source(XContentBuilder templateBuilder) { - try { - return source(BytesReference.bytes(templateBuilder), templateBuilder.contentType()); - } catch (Exception e) { - throw new IllegalArgumentException("Failed to build json for template request", e); - } - } - - /** - * The template source definition. - */ - @SuppressWarnings("unchecked") - public PutIndexTemplateRequest source(Map templateSource) { - Map source = templateSource; - for (Map.Entry entry : source.entrySet()) { - String entryName = entry.getKey(); - if (entryName.equals("index_patterns")) { - 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()); - patterns(elements); - } else { - throw new IllegalArgumentException("Malformed [index_patterns] value, should be a string or a list of strings"); - } - } else if (entryName.equals("order")) { - order(XContentMapValues.nodeIntegerValue(entry.getValue(), order())); - } else if ("version".equals(entryName)) { - if ((entry.getValue() instanceof Integer) == false) { - throw new IllegalArgumentException("Malformed [version] value, should be an integer"); - } - version((Integer) entry.getValue()); - } else if (entryName.equals("settings")) { - if ((entry.getValue() instanceof Map) == false) { - throw new IllegalArgumentException("Malformed [settings] section, should include an inner object"); - } - settings((Map) entry.getValue()); - } else if (entryName.equals("mappings")) { - mapping((Map) entry.getValue()); - } else if (entryName.equals("aliases")) { - aliases((Map) entry.getValue()); - } else { - throw new ElasticsearchParseException("unknown key [{}] in the template ", entryName); - } - } - return this; - } - - /** - * The template source definition. - */ - public PutIndexTemplateRequest source(String templateSource, XContentType xContentType) { - return source(XContentHelper.convertToMap(xContentType.xContent(), templateSource, true)); - } - - /** - * The template source definition. - */ - public PutIndexTemplateRequest source(byte[] source, XContentType xContentType) { - return source(source, 0, source.length, xContentType); - } - - /** - * The template source definition. - */ - public PutIndexTemplateRequest source(byte[] source, int offset, int length, XContentType xContentType) { - return source(new BytesArray(source, offset, length), xContentType); - } - - /** - * The template source definition. - */ - public PutIndexTemplateRequest source(BytesReference source, XContentType xContentType) { - return source(XContentHelper.convertToMap(source, true, xContentType).v2()); - } - - public Set aliases() { - return this.aliases; - } - - /** - * Sets the aliases that will be associated with the index when it gets created - */ - public PutIndexTemplateRequest aliases(Map source) { - try { - XContentBuilder builder = XContentFactory.jsonBuilder(); - builder.map(source); - return aliases(BytesReference.bytes(builder)); - } catch (IOException e) { - throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e); - } - } - - /** - * Sets the aliases that will be associated with the index when it gets created - */ - public PutIndexTemplateRequest aliases(XContentBuilder source) { - return aliases(BytesReference.bytes(source)); - } - - /** - * Sets the aliases that will be associated with the index when it gets created - */ - public PutIndexTemplateRequest aliases(String source) { - return aliases(new BytesArray(source)); - } - - /** - * Sets the aliases that will be associated with the index when it gets created - */ - public PutIndexTemplateRequest aliases(BytesReference source) { - // EMPTY is safe here because we never call namedObject - try (XContentParser parser = XContentHelper.createParser(XContentParserConfiguration.EMPTY, source)) { - // move to the first alias - parser.nextToken(); - while ((parser.nextToken()) != XContentParser.Token.END_OBJECT) { - alias(Alias.fromXContent(parser)); - } - return this; - } catch (IOException e) { - throw new ElasticsearchParseException("Failed to parse aliases", e); - } - } - - /** - * Adds an alias that will be added when the index gets created. - * - * @param alias The metadata for the new alias - * @return the index template creation request - */ - public PutIndexTemplateRequest alias(Alias alias) { - aliases.add(alias); - return this; - } - - /** - * @deprecated Use {@link #setMasterTimeout(TimeValue)} instead - */ - @Deprecated - public final PutIndexTemplateRequest masterNodeTimeout(TimeValue timeout) { - setMasterTimeout(timeout); - return this; - } - - /** - * @deprecated Use {@link #setMasterTimeout(TimeValue)} instead - */ - @Deprecated - public final PutIndexTemplateRequest masterNodeTimeout(String timeout) { - return masterNodeTimeout(TimeValue.parseTimeValue(timeout, null, getClass().getSimpleName() + ".masterNodeTimeout")); - } - - @Override - public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - builder.stringListField("index_patterns", indexPatterns); - builder.field("order", order); - if (version != null) { - builder.field("version", version); - } - - builder.startObject("settings"); - settings.toXContent(builder, params); - builder.endObject(); - - if (mappings != null) { - builder.field("mappings"); - try ( - XContentParser parser = JsonXContent.jsonXContent.createParser(XContentParserConfiguration.EMPTY, mappings.utf8ToString()) - ) { - builder.copyCurrentStructure(parser); - } - } - - builder.startObject("aliases"); - for (Alias alias : aliases) { - alias.toXContent(builder, params); - } - builder.endObject(); - - return builder; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/PutMappingRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/PutMappingRequest.java deleted file mode 100644 index 76e36b0bb923..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/PutMappingRequest.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -package org.elasticsearch.client.indices; - -import org.elasticsearch.ElasticsearchGenerationException; -import org.elasticsearch.action.IndicesRequest; -import org.elasticsearch.action.support.IndicesOptions; -import org.elasticsearch.client.TimedRequest; -import org.elasticsearch.common.bytes.BytesArray; -import org.elasticsearch.common.bytes.BytesReference; -import org.elasticsearch.xcontent.ToXContent; -import org.elasticsearch.xcontent.ToXContentObject; -import org.elasticsearch.xcontent.XContentBuilder; -import org.elasticsearch.xcontent.XContentFactory; -import org.elasticsearch.xcontent.XContentType; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Map; - -/** - * Put a mapping definition into one or more indices. If an index already contains mappings, - * the new mappings will be merged with the existing one. If there are elements that cannot - * be merged, the request will be rejected. - */ -public class PutMappingRequest extends TimedRequest implements IndicesRequest, ToXContentObject { - - public static final IndicesOptions DEFAULT_INDICES_OPTIONS = IndicesOptions.fromOptions(false, false, true, true); - - private final String[] indices; - private IndicesOptions indicesOptions = DEFAULT_INDICES_OPTIONS; - - private BytesReference source; - private XContentType xContentType; - - /** - * Constructs a new put mapping request against one or more indices. If no indices - * are provided then it will be executed against all indices. - */ - public PutMappingRequest(String... indices) { - this.indices = indices; - } - - /** - * The indices into which the mappings will be put. - */ - @Override - public String[] indices() { - return indices; - } - - @Override - public IndicesOptions indicesOptions() { - return indicesOptions; - } - - public PutMappingRequest indicesOptions(IndicesOptions indicesOptions) { - this.indicesOptions = indicesOptions; - return this; - } - - /** - * The mapping source definition. - */ - public BytesReference source() { - return source; - } - - /** - * The {@link XContentType} of the mapping source. - */ - public XContentType xContentType() { - return xContentType; - } - - /** - * The mapping source definition. - * - * Note that the definition should *not* be nested under a type name. - */ - public PutMappingRequest source(Map mappingSource) { - try { - XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON); - builder.map(mappingSource); - return source(builder); - } catch (IOException e) { - throw new ElasticsearchGenerationException("Failed to generate [" + mappingSource + "]", e); - } - } - - /** - * The mapping source definition. - * - * Note that the definition should *not* be nested under a type name. - */ - public PutMappingRequest source(String mappingSource, XContentType type) { - this.source = new BytesArray(mappingSource); - this.xContentType = type; - return this; - } - - /** - * The mapping source definition. - * - * Note that the definition should *not* be nested under a type name. - */ - public PutMappingRequest source(XContentBuilder builder) { - this.source = BytesReference.bytes(builder); - this.xContentType = builder.contentType(); - return this; - } - - /** - * The mapping source definition. - * - * Note that the definition should *not* be nested under a type name. - */ - public PutMappingRequest source(BytesReference bytesReference, XContentType type) { - this.source = bytesReference; - this.xContentType = type; - return this; - } - - @Override - public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException { - if (source != null) { - try (InputStream stream = source.streamInput()) { - builder.rawValue(stream, xContentType); - } - } else { - builder.startObject().endObject(); - } - return builder; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/ReloadAnalyzersRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/ReloadAnalyzersRequest.java deleted file mode 100644 index 4b17000d5e38..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/ReloadAnalyzersRequest.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ -package org.elasticsearch.client.indices; - -import org.elasticsearch.action.support.IndicesOptions; -import org.elasticsearch.client.Validatable; - -import java.util.Objects; - -/** - * Request for the _reload_search_analyzers API - */ -public final class ReloadAnalyzersRequest implements Validatable { - - public static final IndicesOptions DEFAULT_INDICES_OPTIONS = IndicesOptions.strictExpandOpen(); - - private final String[] indices; - private IndicesOptions indicesOptions = DEFAULT_INDICES_OPTIONS; - - /** - * Creates a new reload analyzers request - * @param indices the index for which to reload analyzers - */ - public ReloadAnalyzersRequest(String... indices) { - this.indices = Objects.requireNonNull(indices); - } - - /** - * Returns the indices - */ - public String[] getIndices() { - return indices; - } - - /** - * Specifies what type of requested indices to ignore and how to deal with wildcard expressions. - * For example indices that don't exist. - * - * @return the current behaviour when it comes to index names and wildcard indices expressions - */ - public IndicesOptions indicesOptions() { - return indicesOptions; - } - - /** - * Specifies what type of requested indices to ignore and how to deal with wildcard expressions. - * For example indices that don't exist. - * - * @param indicesOptions the desired behaviour regarding indices to ignore and wildcard indices expressions - */ - public void setIndicesOptions(IndicesOptions indicesOptions) { - this.indicesOptions = indicesOptions; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/ReloadAnalyzersResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/ReloadAnalyzersResponse.java deleted file mode 100644 index db7fa2299de2..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/ReloadAnalyzersResponse.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ -package org.elasticsearch.client.indices; - -import org.elasticsearch.client.core.BroadcastResponse; -import org.elasticsearch.core.Tuple; -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentParser; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import static org.elasticsearch.xcontent.ConstructingObjectParser.constructorArg; - -/** - * The response object that will be returned when reloading analyzers - */ -public class ReloadAnalyzersResponse extends BroadcastResponse { - - private final Map reloadDetails; - - ReloadAnalyzersResponse(final Shards shards, Map reloadDetails) { - super(shards); - this.reloadDetails = reloadDetails; - } - - @SuppressWarnings({ "unchecked" }) - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "reload_analyzer", - true, - arg -> { - Shards shards = (Shards) arg[0]; - List> results = (List>) arg[1]; - Map reloadDetails = new HashMap<>(); - for (Tuple result : results) { - reloadDetails.put(result.v1(), result.v2()); - } - return new ReloadAnalyzersResponse(shards, reloadDetails); - } - ); - - @SuppressWarnings({ "unchecked" }) - private static final ConstructingObjectParser, Void> ENTRY_PARSER = new ConstructingObjectParser<>( - "reload_analyzer.entry", - true, - arg -> { - String index = (String) arg[0]; - Set nodeIds = new HashSet<>((List) arg[1]); - Set analyzers = new HashSet<>((List) arg[2]); - return new Tuple<>(index, new ReloadDetails(index, nodeIds, analyzers)); - } - ); - - static { - declareShardsField(PARSER); - PARSER.declareObjectArray(constructorArg(), ENTRY_PARSER, new ParseField("reload_details")); - ENTRY_PARSER.declareString(constructorArg(), new ParseField("index")); - ENTRY_PARSER.declareStringArray(constructorArg(), new ParseField("reloaded_node_ids")); - ENTRY_PARSER.declareStringArray(constructorArg(), new ParseField("reloaded_analyzers")); - } - - public static ReloadAnalyzersResponse fromXContent(XContentParser parser) { - return PARSER.apply(parser, null); - } - - public Map getReloadedDetails() { - return reloadDetails; - } - - public static class ReloadDetails { - - private final String indexName; - private final Set reloadedIndicesNodes; - private final Set reloadedAnalyzers; - - public ReloadDetails(String name, Set reloadedIndicesNodes, Set reloadedAnalyzers) { - this.indexName = name; - this.reloadedIndicesNodes = reloadedIndicesNodes; - this.reloadedAnalyzers = reloadedAnalyzers; - } - - public String getIndexName() { - return indexName; - } - - public Set getReloadedIndicesNodes() { - return reloadedIndicesNodes; - } - - public Set getReloadedAnalyzers() { - return reloadedAnalyzers; - } - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/ResizeRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/ResizeRequest.java deleted file mode 100644 index 75322a6cf5d8..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/ResizeRequest.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ -package org.elasticsearch.client.indices; - -import org.elasticsearch.action.admin.indices.alias.Alias; -import org.elasticsearch.action.support.ActiveShardCount; -import org.elasticsearch.client.TimedRequest; -import org.elasticsearch.client.Validatable; -import org.elasticsearch.client.ValidationException; -import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.common.unit.ByteSizeValue; -import org.elasticsearch.xcontent.ToXContentObject; -import org.elasticsearch.xcontent.XContentBuilder; - -import java.io.IOException; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; - -/** - * Request class to resize an index - */ -public class ResizeRequest extends TimedRequest implements Validatable, ToXContentObject { - - private ActiveShardCount waitForActiveShards; - private final String sourceIndex; - private final String targetIndex; - private Settings settings = Settings.EMPTY; - private Set aliases = new HashSet<>(); - private ByteSizeValue maxPrimaryShardSize; - - /** - * Creates a new resize request - * @param targetIndex the new index to create with resized shards - * @param sourceIndex the index to resize - */ - public ResizeRequest(String targetIndex, String sourceIndex) { - this.targetIndex = Objects.requireNonNull(targetIndex); - this.sourceIndex = Objects.requireNonNull(sourceIndex); - } - - /** - * Sets the Settings to be used on the target index - */ - public ResizeRequest setSettings(Settings settings) { - this.settings = settings; - return this; - } - - /** - * Returns the Settings to be used on the target index - */ - public Settings getSettings() { - return this.settings; - } - - /** - * Sets the Aliases to be used on the target index - */ - public ResizeRequest setAliases(List aliases) { - this.aliases.clear(); - this.aliases.addAll(aliases); - return this; - } - - /** - * Returns the Aliases to be used on the target index - */ - public Set getAliases() { - return Collections.unmodifiableSet(this.aliases); - } - - /** - * Sets the max primary shard size of the target index - */ - public void setMaxPrimaryShardSize(ByteSizeValue maxPrimaryShardSize) { - this.maxPrimaryShardSize = maxPrimaryShardSize; - } - - /** - * Return the max primary shard size of the target index - */ - public ByteSizeValue getMaxPrimaryShardSize() { - return maxPrimaryShardSize; - } - - @Override - public Optional validate() { - ValidationException validationException = new ValidationException(); - if (settings.getByPrefix("index.sort.").isEmpty() == false) { - validationException.addValidationError("can't override index sort when resizing an index"); - } - return validationException.validationErrors().isEmpty() ? Optional.empty() : Optional.of(validationException); - } - - /** - * Returns the target index name - */ - public String getTargetIndex() { - return targetIndex; - } - - /** - * Returns the source index name - */ - public String getSourceIndex() { - return sourceIndex; - } - - /** - * Sets the number of shard copies that should be active for creation of the - * new shrunken index to return. Defaults to {@link ActiveShardCount#DEFAULT}, which will - * wait for one shard copy (the primary) to become active. Set this value to - * {@link ActiveShardCount#ALL} to wait for all shards (primary and all replicas) to be active - * before returning. Otherwise, use {@link ActiveShardCount#from(int)} to set this value to any - * non-negative integer, up to the number of copies per shard (number of replicas + 1), - * to wait for the desired amount of shard copies to become active before returning. - * Index creation will only wait up until the timeout value for the number of shard copies - * to be active before returning. Check {@link ResizeResponse#isShardsAcknowledged()} to - * determine if the requisite shard copies were all started before returning or timing out. - * - * @param waitForActiveShards number of active shard copies to wait on - */ - public ResizeRequest setWaitForActiveShards(ActiveShardCount waitForActiveShards) { - this.waitForActiveShards = waitForActiveShards; - return this; - } - - /** - * A shortcut for {@link #setWaitForActiveShards(ActiveShardCount)} where the numerical - * shard count is passed in, instead of having to first call {@link ActiveShardCount#from(int)} - * to get the ActiveShardCount. - */ - public ResizeRequest setWaitForActiveShards(final int waitForActiveShards) { - return setWaitForActiveShards(ActiveShardCount.from(waitForActiveShards)); - } - - public ActiveShardCount getWaitForActiveShards() { - return waitForActiveShards; - } - - @Override - public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(); - { - builder.startObject(CreateIndexRequest.SETTINGS.getPreferredName()); - { - settings.toXContent(builder, params); - } - builder.endObject(); - builder.startObject(CreateIndexRequest.ALIASES.getPreferredName()); - { - for (Alias alias : aliases) { - alias.toXContent(builder, params); - } - } - builder.endObject(); - } - builder.endObject(); - return builder; - } - -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/ResizeResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/ResizeResponse.java deleted file mode 100644 index 8d61f5f4a268..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/ResizeResponse.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -package org.elasticsearch.client.indices; - -import org.elasticsearch.client.core.AcknowledgedResponse; -import org.elasticsearch.client.core.ShardsAcknowledgedResponse; -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentParser; - -import java.util.Objects; - -import static org.elasticsearch.xcontent.ConstructingObjectParser.constructorArg; - -/** - * The response from a {@link ResizeRequest} call - */ -public class ResizeResponse extends ShardsAcknowledgedResponse { - - private static final ParseField INDEX = new ParseField("index"); - 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)); - PARSER.declareBoolean(constructorArg(), new ParseField(SHARDS_PARSE_FIELD_NAME)); - PARSER.declareField(constructorArg(), (parser, context) -> parser.textOrNull(), INDEX, ObjectParser.ValueType.STRING_OR_NULL); - } - - private final String index; - - public ResizeResponse(boolean acknowledged, boolean shardsAcknowledged, String index) { - super(acknowledged, shardsAcknowledged); - this.index = index; - } - - public String index() { - return index; - } - - public static ResizeResponse fromXContent(XContentParser parser) { - return PARSER.apply(parser, null); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - if (super.equals(o) == false) return false; - ResizeResponse that = (ResizeResponse) o; - return Objects.equals(index, that.index); - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), index); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/SimulateIndexTemplateRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/SimulateIndexTemplateRequest.java deleted file mode 100644 index a59cb5e39d1e..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/SimulateIndexTemplateRequest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -package org.elasticsearch.client.indices; - -import org.elasticsearch.client.TimedRequest; -import org.elasticsearch.common.Strings; -import org.elasticsearch.core.Nullable; - -/** - * A request to simulate matching a provided index name and an optional new index template against the existing index templates. - */ -public class SimulateIndexTemplateRequest extends TimedRequest { - - private String indexName; - - @Nullable - private PutComposableIndexTemplateRequest indexTemplateV2Request; - - public SimulateIndexTemplateRequest(String indexName) { - if (Strings.isNullOrEmpty(indexName)) { - throw new IllegalArgumentException("index name cannot be null or empty"); - } - this.indexName = indexName; - } - - /** - * Return the index name for which we simulate the index template matching. - */ - public String indexName() { - return indexName; - } - - /** - * Set the index name to simulate template matching against the index templates in the system. - */ - public SimulateIndexTemplateRequest indexName(String indexName) { - if (Strings.isNullOrEmpty(indexName)) { - throw new IllegalArgumentException("index name cannot be null or empty"); - } - this.indexName = indexName; - return this; - } - - /** - * An optional new template request will be part of the index template simulation. - */ - @Nullable - public PutComposableIndexTemplateRequest indexTemplateV2Request() { - return indexTemplateV2Request; - } - - /** - * Optionally, define a new template request which will included in the index simulation as if it was an index template stored in the - * system. The new template will be validated just as a regular, standalone, live, new index template request. - */ - public SimulateIndexTemplateRequest indexTemplateV2Request(@Nullable PutComposableIndexTemplateRequest indexTemplateV2Request) { - this.indexTemplateV2Request = indexTemplateV2Request; - return this; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/SimulateIndexTemplateResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/SimulateIndexTemplateResponse.java deleted file mode 100644 index 92822ccb63b5..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/SimulateIndexTemplateResponse.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ -package org.elasticsearch.client.indices; - -import org.elasticsearch.cluster.metadata.Template; -import org.elasticsearch.core.Nullable; -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.stream.Collectors; - -public class SimulateIndexTemplateResponse { - - private static final ParseField TEMPLATE = new ParseField("template"); - private static final ParseField OVERLAPPING = new ParseField("overlapping"); - private static final ParseField NAME = new ParseField("name"); - 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 - ) - ); - - @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 class IndexTemplateAndPatterns { - String name; - List indexPatterns; - - IndexTemplateAndPatterns(String name, List indexPatterns) { - this.name = name; - this.indexPatterns = indexPatterns; - } - - public String name() { - return name; - } - - public List indexPatterns() { - return indexPatterns; - } - } - - static { - PARSER.declareObject(ConstructingObjectParser.optionalConstructorArg(), Template.PARSER, TEMPLATE); - INNER_PARSER.declareString(ConstructingObjectParser.constructorArg(), NAME); - INNER_PARSER.declareStringArray(ConstructingObjectParser.constructorArg(), INDEX_PATTERNS); - PARSER.declareObjectArray(ConstructingObjectParser.optionalConstructorArg(), INNER_PARSER, OVERLAPPING); - } - - @Nullable - // the resolved settings, mappings and aliases for the matched templates, if any - private Template resolvedTemplate; - - @Nullable - // a map of template names and their index patterns that would overlap when matching the given index name - private Map> overlappingTemplates; - - SimulateIndexTemplateResponse(@Nullable Template resolvedTemplate, @Nullable Map> overlappingTemplates) { - this.resolvedTemplate = resolvedTemplate; - this.overlappingTemplates = overlappingTemplates; - } - - public static SimulateIndexTemplateResponse fromXContent(XContentParser parser) throws IOException { - return PARSER.parse(parser, null); - } - - public Template resolvedTemplate() { - return resolvedTemplate; - } - - public Map> overlappingTemplates() { - return overlappingTemplates; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - SimulateIndexTemplateResponse that = (SimulateIndexTemplateResponse) o; - return Objects.equals(resolvedTemplate, that.resolvedTemplate) - && Objects.deepEquals(overlappingTemplates, that.overlappingTemplates); - } - - @Override - public int hashCode() { - return Objects.hash(resolvedTemplate, overlappingTemplates); - } - - @Override - public String toString() { - return "SimulateIndexTemplateResponse{" - + "resolved template=" - + resolvedTemplate - + ", overlapping templates=" - + String.join("|", overlappingTemplates.keySet()) - + "}"; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/UnfreezeIndexRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/UnfreezeIndexRequest.java deleted file mode 100644 index 9510a17e3353..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/UnfreezeIndexRequest.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ -package org.elasticsearch.client.indices; - -import org.elasticsearch.action.admin.indices.open.OpenIndexResponse; -import org.elasticsearch.action.support.ActiveShardCount; -import org.elasticsearch.action.support.IndicesOptions; -import org.elasticsearch.client.TimedRequest; - -import java.util.Objects; - -/** - * Request for the _unfreeze index API - */ -public final class UnfreezeIndexRequest extends TimedRequest { - - private final String[] indices; - private IndicesOptions indicesOptions; - private ActiveShardCount waitForActiveShards; - - /** - * Creates a new unfreeze index request - * @param indices the index to unfreeze - */ - public UnfreezeIndexRequest(String... indices) { - this.indices = Objects.requireNonNull(indices); - } - - /** - * Returns the indices to unfreeze - */ - public String[] getIndices() { - return indices; - } - - /** - * Specifies what type of requested indices to ignore and how to deal with wildcard expressions. - * For example indices that don't exist. - * - * @return the current behaviour when it comes to index names and wildcard indices expressions - */ - public IndicesOptions indicesOptions() { - return indicesOptions; - } - - /** - * Specifies what type of requested indices to ignore and how to deal with wildcard expressions. - * For example indices that don't exist. - * - * @param indicesOptions the desired behaviour regarding indices to ignore and wildcard indices expressions - */ - public void setIndicesOptions(IndicesOptions indicesOptions) { - this.indicesOptions = indicesOptions; - } - - /** - * Returns the wait for active shard cound or null if the default should be used - */ - public ActiveShardCount getWaitForActiveShards() { - return waitForActiveShards; - } - - /** - * Sets the number of shard copies that should be active for indices opening to return. - * Defaults to {@link ActiveShardCount#DEFAULT}, which will wait for one shard copy - * (the primary) to become active. Set this value to {@link ActiveShardCount#ALL} to - * wait for all shards (primary and all replicas) to be active before returning. - * Otherwise, use {@link ActiveShardCount#from(int)} to set this value to any - * non-negative integer, up to the number of copies per shard (number of replicas + 1), - * to wait for the desired amount of shard copies to become active before returning. - * Indices opening will only wait up until the timeout value for the number of shard copies - * to be active before returning. Check {@link OpenIndexResponse#isShardsAcknowledged()} to - * determine if the requisite shard copies were all started before returning or timing out. - * - * @param waitForActiveShards number of active shard copies to wait on - */ - public void setWaitForActiveShards(ActiveShardCount waitForActiveShards) { - this.waitForActiveShards = waitForActiveShards; - } - -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/rollover/RolloverRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/rollover/RolloverRequest.java deleted file mode 100644 index 7824932528b1..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/rollover/RolloverRequest.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ -package org.elasticsearch.client.indices.rollover; - -import org.elasticsearch.action.admin.indices.rollover.Condition; -import org.elasticsearch.action.admin.indices.rollover.MaxAgeCondition; -import org.elasticsearch.action.admin.indices.rollover.MaxDocsCondition; -import org.elasticsearch.action.admin.indices.rollover.MaxPrimaryShardSizeCondition; -import org.elasticsearch.action.admin.indices.rollover.MaxSizeCondition; -import org.elasticsearch.client.TimedRequest; -import org.elasticsearch.client.indices.CreateIndexRequest; -import org.elasticsearch.common.unit.ByteSizeValue; -import org.elasticsearch.common.util.Maps; -import org.elasticsearch.core.TimeValue; -import org.elasticsearch.xcontent.ToXContentObject; -import org.elasticsearch.xcontent.XContentBuilder; - -import java.io.IOException; -import java.util.Map; - -/** - * Request class to swap index under an alias upon satisfying conditions - */ -public class RolloverRequest extends TimedRequest implements ToXContentObject { - - private final String alias; - private final String newIndexName; - private boolean dryRun; - private final Map> conditions = Maps.newMapWithExpectedSize(2); - // 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) { - if (alias == null) { - throw new IllegalArgumentException("The index alias cannot be null!"); - } - this.alias = alias; - this.newIndexName = newIndexName; - } - - /** - * Returns the alias of the rollover operation - */ - public String getAlias() { - return alias; - } - - /** - * Returns the new index name for the rollover - */ - public String getNewIndexName() { - return newIndexName; - } - - /** - * Sets if the rollover should not be executed when conditions are met - */ - public RolloverRequest dryRun(boolean dryRun) { - this.dryRun = dryRun; - return this; - } - - /** - * Returns if the rollover should not be executed when conditions are met - */ - public boolean isDryRun() { - return dryRun; - } - - /** - * Adds condition to check if the index is at least age old - */ - public RolloverRequest addMaxIndexAgeCondition(TimeValue age) { - MaxAgeCondition maxAgeCondition = new MaxAgeCondition(age); - if (this.conditions.containsKey(maxAgeCondition.name())) { - throw new IllegalArgumentException(maxAgeCondition.name() + " condition is already set"); - } - this.conditions.put(maxAgeCondition.name(), maxAgeCondition); - return this; - } - - /** - * Adds condition to check if the index has at least numDocs - */ - public RolloverRequest addMaxIndexDocsCondition(long numDocs) { - MaxDocsCondition maxDocsCondition = new MaxDocsCondition(numDocs); - if (this.conditions.containsKey(maxDocsCondition.name())) { - throw new IllegalArgumentException(maxDocsCondition.name() + " condition is already set"); - } - this.conditions.put(maxDocsCondition.name(), maxDocsCondition); - return this; - } - - /** - * Adds a size-based condition to check if the index size is at least size. - */ - public RolloverRequest addMaxIndexSizeCondition(ByteSizeValue size) { - MaxSizeCondition maxSizeCondition = new MaxSizeCondition(size); - if (this.conditions.containsKey(maxSizeCondition.name())) { - throw new IllegalArgumentException(maxSizeCondition + " condition is already set"); - } - this.conditions.put(maxSizeCondition.name(), maxSizeCondition); - return this; - } - - /** - * Adds a size-based condition to check if the size of the largest primary shard is at least size. - */ - public RolloverRequest addMaxPrimaryShardSizeCondition(ByteSizeValue size) { - MaxPrimaryShardSizeCondition maxPrimaryShardSizeCondition = new MaxPrimaryShardSizeCondition(size); - if (this.conditions.containsKey(maxPrimaryShardSizeCondition.name())) { - throw new IllegalArgumentException(maxPrimaryShardSizeCondition + " condition is already set"); - } - this.conditions.put(maxPrimaryShardSizeCondition.name(), maxPrimaryShardSizeCondition); - return this; - } - - /** - * Returns all set conditions - */ - public Map> getConditions() { - return conditions; - } - - /** - * Returns the inner {@link CreateIndexRequest}. Allows to configure mappings, settings and aliases for the new index. - */ - public CreateIndexRequest getCreateIndexRequest() { - return createIndexRequest; - } - - @Override - public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(); - createIndexRequest.innerToXContent(builder, params); - - builder.startObject("conditions"); - for (Condition condition : conditions.values()) { - condition.toXContent(builder, params); - } - builder.endObject(); - - builder.endObject(); - return builder; - } - -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/rollover/RolloverResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/rollover/RolloverResponse.java deleted file mode 100644 index fcbd1508d76d..000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/indices/rollover/RolloverResponse.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -package org.elasticsearch.client.indices.rollover; - -import org.elasticsearch.action.support.master.ShardsAcknowledgedResponse; -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentParser; - -import java.util.Map; -import java.util.Objects; - -import static org.elasticsearch.xcontent.ConstructingObjectParser.constructorArg; - -/** - * Response object for {@link RolloverRequest} API - */ -public final class RolloverResponse extends ShardsAcknowledgedResponse { - - private static final ParseField NEW_INDEX = new ParseField("new_index"); - private static final ParseField OLD_INDEX = new ParseField("old_index"); - private static final ParseField DRY_RUN = new ParseField("dry_run"); - private static final ParseField ROLLED_OVER = new ParseField("rolled_over"); - 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] - ) - ); - - static { - PARSER.declareString(constructorArg(), OLD_INDEX); - PARSER.declareString(constructorArg(), NEW_INDEX); - PARSER.declareObject(constructorArg(), (parser, context) -> parser.map(), CONDITIONS); - PARSER.declareBoolean(constructorArg(), DRY_RUN); - PARSER.declareBoolean(constructorArg(), ROLLED_OVER); - declareAcknowledgedAndShardsAcknowledgedFields(PARSER); - } - - private final String oldIndex; - private final String newIndex; - private final Map conditionStatus; - private final boolean dryRun; - private final boolean rolledOver; - - 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; - this.dryRun = dryRun; - this.rolledOver = rolledOver; - this.conditionStatus = conditionResults; - } - - /** - * Returns the name of the index that the request alias was pointing to - */ - public String getOldIndex() { - return oldIndex; - } - - /** - * Returns the name of the index that the request alias currently points to - */ - public String getNewIndex() { - return newIndex; - } - - /** - * Returns the statuses of all the request conditions - */ - public Map getConditionStatus() { - return conditionStatus; - } - - /** - * Returns if the rollover execution was skipped even when conditions were met - */ - public boolean isDryRun() { - return dryRun; - } - - /** - * Returns true if the rollover was not simulated and the conditions were met - */ - public boolean isRolledOver() { - return rolledOver; - } - - public static RolloverResponse fromXContent(XContentParser parser) { - return PARSER.apply(parser, null); - } - - @Override - 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 false; - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), oldIndex, newIndex, conditionStatus, dryRun, rolledOver); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/transform/PreviewTransformResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/transform/PreviewTransformResponse.java index 637464d0f4f1..92e396b8e95b 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/transform/PreviewTransformResponse.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/transform/PreviewTransformResponse.java @@ -9,7 +9,6 @@ package org.elasticsearch.client.transform; import org.elasticsearch.action.admin.indices.alias.Alias; -import org.elasticsearch.client.indices.CreateIndexRequest; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.xcontent.ConstructingObjectParser; import org.elasticsearch.xcontent.ParseField; @@ -162,15 +161,6 @@ public class PreviewTransformResponse { return generatedDestIndexSettings.getAliases(); } - public CreateIndexRequest getCreateIndexRequest(String index) { - CreateIndexRequest createIndexRequest = new CreateIndexRequest(index); - createIndexRequest.aliases(generatedDestIndexSettings.getAliases()); - createIndexRequest.settings(generatedDestIndexSettings.getSettings()); - createIndexRequest.mapping(generatedDestIndexSettings.getMappings()); - - return createIndexRequest; - } - @Override public boolean equals(Object obj) { if (obj == this) { diff --git a/qa/ccs-rolling-upgrade-remote-cluster/src/test/java/org/elasticsearch/upgrades/SearchStatesIT.java b/qa/ccs-rolling-upgrade-remote-cluster/src/test/java/org/elasticsearch/upgrades/SearchStatesIT.java index 66b6b7860716..73d6cdf4711a 100644 --- a/qa/ccs-rolling-upgrade-remote-cluster/src/test/java/org/elasticsearch/upgrades/SearchStatesIT.java +++ b/qa/ccs-rolling-upgrade-remote-cluster/src/test/java/org/elasticsearch/upgrades/SearchStatesIT.java @@ -31,8 +31,6 @@ import org.apache.http.HttpHost; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.elasticsearch.Version; -import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; -import org.elasticsearch.action.admin.indices.refresh.RefreshRequest; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.Request; @@ -40,7 +38,6 @@ import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.Response; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; -import org.elasticsearch.client.indices.CreateIndexRequest; import org.elasticsearch.cluster.metadata.IndexMetadata; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.test.hamcrest.ElasticsearchAssertions; @@ -162,7 +159,8 @@ public class SearchStatesIT extends ESRestTestCase { for (int i = 0; i < numDocs; i++) { client.index(new IndexRequest(index).id("id_" + i).source("f", i), RequestOptions.DEFAULT); } - client.indices().refresh(new RefreshRequest(index), RequestOptions.DEFAULT); + + refresh(client.getLowLevelClient(), index); return numDocs; } @@ -209,22 +207,18 @@ public class SearchStatesIT extends ESRestTestCase { String localIndex = "test_bwc_search_states_index"; String remoteIndex = "test_bwc_search_states_remote_index"; try (RestHighLevelClient localClient = newLocalClient(); RestHighLevelClient remoteClient = newRemoteClient()) { - localClient.indices() - .create( - new CreateIndexRequest(localIndex).settings( - Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, between(1, 5)) - ), - RequestOptions.DEFAULT - ); + createIndex( + localClient.getLowLevelClient(), + localIndex, + Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, between(1, 5)).build() + ); int localNumDocs = indexDocs(localClient, localIndex, between(10, 100)); - remoteClient.indices() - .create( - new CreateIndexRequest(remoteIndex).settings( - Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, between(1, 5)) - ), - RequestOptions.DEFAULT - ); + createIndex( + remoteClient.getLowLevelClient(), + remoteIndex, + Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, between(1, 5)).build() + ); int remoteNumDocs = indexDocs(remoteClient, remoteIndex, between(10, 100)); configureRemoteClusters(getNodes(remoteClient.getLowLevelClient())); @@ -232,8 +226,8 @@ public class SearchStatesIT extends ESRestTestCase { for (int i = 0; i < iterations; i++) { verifySearch(localIndex, localNumDocs, CLUSTER_ALIAS + ":" + remoteIndex, remoteNumDocs, null); } - localClient.indices().delete(new DeleteIndexRequest(localIndex), RequestOptions.DEFAULT); - remoteClient.indices().delete(new DeleteIndexRequest(remoteIndex), RequestOptions.DEFAULT); + deleteIndex(localClient.getLowLevelClient(), localIndex); + deleteIndex(remoteClient.getLowLevelClient(), remoteIndex); } } @@ -241,22 +235,18 @@ public class SearchStatesIT extends ESRestTestCase { String localIndex = "test_can_match_local_index"; String remoteIndex = "test_can_match_remote_index"; try (RestHighLevelClient localClient = newLocalClient(); RestHighLevelClient remoteClient = newRemoteClient()) { - localClient.indices() - .create( - new CreateIndexRequest(localIndex).settings( - Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, between(5, 20)) - ), - RequestOptions.DEFAULT - ); + createIndex( + localClient.getLowLevelClient(), + localIndex, + Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, between(5, 20)).build() + ); int localNumDocs = indexDocs(localClient, localIndex, between(10, 100)); - remoteClient.indices() - .create( - new CreateIndexRequest(remoteIndex).settings( - Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, between(5, 20)) - ), - RequestOptions.DEFAULT - ); + createIndex( + remoteClient.getLowLevelClient(), + remoteIndex, + Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, between(5, 20)).build() + ); int remoteNumDocs = indexDocs(remoteClient, remoteIndex, between(10, 100)); configureRemoteClusters(getNodes(remoteClient.getLowLevelClient())); @@ -264,8 +254,8 @@ public class SearchStatesIT extends ESRestTestCase { for (int i = 0; i < iterations; i++) { verifySearch(localIndex, localNumDocs, CLUSTER_ALIAS + ":" + remoteIndex, remoteNumDocs, between(1, 10)); } - localClient.indices().delete(new DeleteIndexRequest(localIndex), RequestOptions.DEFAULT); - remoteClient.indices().delete(new DeleteIndexRequest(remoteIndex), RequestOptions.DEFAULT); + deleteIndex(localClient.getLowLevelClient(), localIndex); + deleteIndex(remoteClient.getLowLevelClient(), remoteIndex); } } } diff --git a/qa/full-cluster-restart/src/test/java/org/elasticsearch/upgrades/QueryBuilderBWCIT.java b/qa/full-cluster-restart/src/test/java/org/elasticsearch/upgrades/QueryBuilderBWCIT.java index dbbd55f7725a..ff27ecfc3851 100644 --- a/qa/full-cluster-restart/src/test/java/org/elasticsearch/upgrades/QueryBuilderBWCIT.java +++ b/qa/full-cluster-restart/src/test/java/org/elasticsearch/upgrades/QueryBuilderBWCIT.java @@ -8,7 +8,6 @@ package org.elasticsearch.upgrades; -import org.apache.http.util.EntityUtils; import org.elasticsearch.client.Request; import org.elasticsearch.client.Response; import org.elasticsearch.common.Strings; @@ -18,7 +17,6 @@ import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.Fuzziness; -import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.ConstantScoreQueryBuilder; import org.elasticsearch.index.query.DisMaxQueryBuilder; @@ -34,10 +32,8 @@ import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder; import org.elasticsearch.index.query.functionscore.RandomScoreFunctionBuilder; import org.elasticsearch.search.SearchModule; import org.elasticsearch.xcontent.XContentBuilder; -import org.elasticsearch.xcontent.json.JsonXContent; import java.io.ByteArrayInputStream; -import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Base64; @@ -217,7 +213,7 @@ public class QueryBuilderBWCIT extends AbstractFullClusterRestartTestCase { """.formatted(i)); Response rsp = client().performRequest(request); assertEquals(200, rsp.getStatusLine().getStatusCode()); - Map hitRsp = (Map) ((List) ((Map) toMap(rsp).get("hits")).get("hits")).get(0); + var hitRsp = (Map) ((List) ((Map) responseAsMap(rsp).get("hits")).get("hits")).get(0); String queryBuilderStr = (String) ((List) ((Map) hitRsp.get("fields")).get("query.query_builder_field")).get(0); byte[] qbSource = Base64.getDecoder().decode(queryBuilderStr); try (InputStream in = new ByteArrayInputStream(qbSource, 0, qbSource.length)) { @@ -231,12 +227,4 @@ public class QueryBuilderBWCIT extends AbstractFullClusterRestartTestCase { } } } - - private static Map toMap(Response response) throws IOException { - return toMap(EntityUtils.toString(response.getEntity())); - } - - private static Map toMap(String response) throws IOException { - return XContentHelper.convertToMap(JsonXContent.jsonXContent, response, false); - } } diff --git a/qa/multi-cluster-search/src/test/java/org/elasticsearch/search/CCSDuelIT.java b/qa/multi-cluster-search/src/test/java/org/elasticsearch/search/CCSDuelIT.java index e031403ec954..b69b15ea8948 100644 --- a/qa/multi-cluster-search/src/test/java/org/elasticsearch/search/CCSDuelIT.java +++ b/qa/multi-cluster-search/src/test/java/org/elasticsearch/search/CCSDuelIT.java @@ -15,7 +15,7 @@ import org.apache.lucene.search.join.ScoreMode; import org.apache.lucene.tests.util.TimeUnits; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.LatchedActionListener; -import org.elasticsearch.action.admin.indices.refresh.RefreshRequest; +import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import org.elasticsearch.action.admin.indices.refresh.RefreshResponse; import org.elasticsearch.action.bulk.BulkProcessor; import org.elasticsearch.action.bulk.BulkRequest; @@ -28,8 +28,6 @@ import org.elasticsearch.action.support.WriteRequest; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; -import org.elasticsearch.client.indices.CreateIndexRequest; -import org.elasticsearch.client.indices.CreateIndexResponse; import org.elasticsearch.common.Strings; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.settings.Settings; @@ -171,14 +169,12 @@ public class CCSDuelIT extends ESRestTestCase { IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT); assertEquals(201, indexResponse.status().getStatus()); - CreateIndexRequest createEmptyIndexRequest = new CreateIndexRequest(INDEX_NAME + "_empty"); - CreateIndexResponse response = restHighLevelClient.indices().create(createEmptyIndexRequest, RequestOptions.DEFAULT); + CreateIndexResponse response = createIndex(INDEX_NAME + "_empty"); assertTrue(response.isAcknowledged()); int numShards = randomIntBetween(1, 5); - CreateIndexRequest createIndexRequest = new CreateIndexRequest(INDEX_NAME); - createIndexRequest.settings(Settings.builder().put("index.number_of_shards", numShards).put("index.number_of_replicas", 0)); - createIndexRequest.mapping(""" + Settings settings = Settings.builder().put("index.number_of_shards", numShards).put("index.number_of_replicas", 0).build(); + String mapping = """ { "properties": { "id": { @@ -194,9 +190,9 @@ public class CCSDuelIT extends ESRestTestCase { } } } - }""", XContentType.JSON); - CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT); - assertTrue(createIndexResponse.isAcknowledged()); + }"""; + response = createIndex(INDEX_NAME, settings, mapping); + assertTrue(response.isAcknowledged()); BulkProcessor bulkProcessor = BulkProcessor.builder( (r, l) -> restHighLevelClient.bulkAsync(r, RequestOptions.DEFAULT, l), @@ -227,7 +223,7 @@ public class CCSDuelIT extends ESRestTestCase { } assertTrue(bulkProcessor.awaitClose(30, TimeUnit.SECONDS)); - RefreshResponse refreshResponse = restHighLevelClient.indices().refresh(new RefreshRequest(INDEX_NAME), RequestOptions.DEFAULT); + RefreshResponse refreshResponse = refresh(INDEX_NAME); ElasticsearchAssertions.assertNoFailures(refreshResponse); } diff --git a/qa/remote-clusters/src/test/java/org/elasticsearch/cluster/remote/test/RemoteClustersIT.java b/qa/remote-clusters/src/test/java/org/elasticsearch/cluster/remote/test/RemoteClustersIT.java index 78aa2b7e1c5d..748249c60e4d 100644 --- a/qa/remote-clusters/src/test/java/org/elasticsearch/cluster/remote/test/RemoteClustersIT.java +++ b/qa/remote-clusters/src/test/java/org/elasticsearch/cluster/remote/test/RemoteClustersIT.java @@ -7,13 +7,11 @@ */ package org.elasticsearch.cluster.remote.test; -import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.support.WriteRequest; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; -import org.elasticsearch.client.indices.CreateIndexRequest; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.xcontent.XContentFactory; import org.junit.After; @@ -30,28 +28,17 @@ public class RemoteClustersIT extends AbstractMultiClusterRemoteTestCase { @Before public void setupIndices() throws IOException { - assertTrue( - cluster1Client().indices() - .create( - new CreateIndexRequest("test1").settings(Settings.builder().put("index.number_of_replicas", 0).build()), - RequestOptions.DEFAULT - ) - .isAcknowledged() - ); + RestClient cluster1Client = cluster1Client().getLowLevelClient(); + assertTrue(createIndex(cluster1Client, "test1", Settings.builder().put("index.number_of_replicas", 0).build()).isAcknowledged()); cluster1Client().index( new IndexRequest("test1").id("id1") .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE) .source(XContentFactory.jsonBuilder().startObject().field("foo", "bar").endObject()), RequestOptions.DEFAULT ); - assertTrue( - cluster2Client().indices() - .create( - new CreateIndexRequest("test2").settings(Settings.builder().put("index.number_of_replicas", 0).build()), - RequestOptions.DEFAULT - ) - .isAcknowledged() - ); + + RestClient cluster2Client = cluster2Client().getLowLevelClient(); + assertTrue(createIndex(cluster2Client, "test2", Settings.builder().put("index.number_of_replicas", 0).build()).isAcknowledged()); cluster2Client().index( new IndexRequest("test2").id("id1").source(XContentFactory.jsonBuilder().startObject().field("foo", "bar").endObject()), RequestOptions.DEFAULT @@ -68,8 +55,10 @@ public class RemoteClustersIT extends AbstractMultiClusterRemoteTestCase { @After public void clearIndices() throws IOException { - assertTrue(cluster1Client().indices().delete(new DeleteIndexRequest("*"), RequestOptions.DEFAULT).isAcknowledged()); - assertTrue(cluster2Client().indices().delete(new DeleteIndexRequest("*"), RequestOptions.DEFAULT).isAcknowledged()); + RestClient cluster1Client = cluster1Client().getLowLevelClient(); + assertTrue(deleteIndex(cluster1Client, "*").isAcknowledged()); + RestClient cluster2Client = cluster2Client().getLowLevelClient(); + assertTrue(deleteIndex(cluster2Client, "*").isAcknowledged()); } @After diff --git a/test/framework/src/main/java/org/elasticsearch/test/rest/ESRestTestCase.java b/test/framework/src/main/java/org/elasticsearch/test/rest/ESRestTestCase.java index 4b99cfdf8455..e9ee022f79c8 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/rest/ESRestTestCase.java +++ b/test/framework/src/main/java/org/elasticsearch/test/rest/ESRestTestCase.java @@ -25,7 +25,10 @@ import org.apache.lucene.util.SetOnce; import org.elasticsearch.Version; import org.elasticsearch.action.admin.cluster.node.tasks.list.ListTasksAction; import org.elasticsearch.action.admin.cluster.repositories.put.PutRepositoryRequest; +import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; +import org.elasticsearch.action.admin.indices.refresh.RefreshResponse; import org.elasticsearch.action.fieldcaps.FieldCapabilitiesResponse; +import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.client.Request; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RequestOptions.Builder; @@ -35,6 +38,8 @@ import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClientBuilder; import org.elasticsearch.client.WarningsHandler; import org.elasticsearch.common.Strings; +import org.elasticsearch.common.bytes.BytesArray; +import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.ssl.PemUtils; @@ -1141,6 +1146,16 @@ public abstract class ESRestTestCase extends ESTestCase { client().performRequest(refreshRequest); } + protected static RefreshResponse refresh(String index) throws IOException { + return refresh(client(), index); + } + + protected static RefreshResponse refresh(RestClient client, String index) throws IOException { + Request refreshRequest = new Request("POST", "/" + index + "/_refresh"); + Response response = client.performRequest(refreshRequest); + return RefreshResponse.fromXContent(responseAsParser(response)); + } + private void waitForPendingRollupTasks() throws Exception { waitForPendingTasks(adminClient(), taskName -> taskName.startsWith("xpack/rollup/job") == false); } @@ -1511,38 +1526,66 @@ public abstract class ESRestTestCase extends ESTestCase { adminClient().performRequest(request); } - protected static void createIndex(String name, Settings settings) throws IOException { - createIndex(name, settings, null); + protected static CreateIndexResponse createIndex(String name) throws IOException { + return createIndex(name, null, null, null); } - protected static void createIndex(String name, Settings settings, String mapping) throws IOException { - createIndex(name, settings, mapping, null); + protected static CreateIndexResponse createIndex(String name, Settings settings) throws IOException { + return createIndex(name, settings, null, null); } - protected static void createIndex(String name, Settings settings, String mapping, String aliases) throws IOException { + protected static CreateIndexResponse createIndex(RestClient client, String name, Settings settings) throws IOException { + return createIndex(client, name, settings, null, null); + } + + protected static CreateIndexResponse createIndex(String name, Settings settings, String mapping) throws IOException { + return createIndex(name, settings, mapping, null); + } + + protected static CreateIndexResponse createIndex(String name, Settings settings, String mapping, String aliases) throws IOException { + return createIndex(client(), name, settings, mapping, aliases); + } + + public static CreateIndexResponse createIndex(RestClient client, String name, Settings settings, String mapping, String aliases) + throws IOException { Request request = new Request("PUT", "/" + name); - String entity = "{\"settings\": " + Strings.toString(settings); + String entity = "{"; + if (settings != null) { + entity += "\"settings\": " + Strings.toString(settings); + if (settings.getAsBoolean(IndexSettings.INDEX_SOFT_DELETES_SETTING.getKey(), true) == false) { + expectSoftDeletesWarning(request, name); + } + } if (mapping != null) { - entity += ",\"mappings\" : {" + mapping + "}"; + if (settings != null) { + entity += ","; + } + if (mapping.trim().startsWith("{")) { + entity += "\"mappings\" : " + mapping + ""; + } else { + entity += "\"mappings\" : {" + mapping + "}"; + } } if (aliases != null) { - entity += ",\"aliases\": {" + aliases + "}"; + if (settings != null || mapping != null) { + entity += ","; + } + entity += "\"aliases\": {" + aliases + "}"; } entity += "}"; - if (settings.getAsBoolean(IndexSettings.INDEX_SOFT_DELETES_SETTING.getKey(), true) == false) { - expectSoftDeletesWarning(request, name); - } request.setJsonEntity(entity); - client().performRequest(request); + Response response = client.performRequest(request); + return CreateIndexResponse.fromXContent(responseAsParser(response)); } - protected static void deleteIndex(String name) throws IOException { - deleteIndex(client(), name); + protected static AcknowledgedResponse deleteIndex(String name) throws IOException { + return deleteIndex(client(), name); } - protected static void deleteIndex(RestClient restClient, String name) throws IOException { + protected static AcknowledgedResponse deleteIndex(RestClient restClient, String name) throws IOException { Request request = new Request("DELETE", "/" + name); - restClient.performRequest(request); + Response response = restClient.performRequest(request); + return AcknowledgedResponse.fromXContent(responseAsParser(response)); } protected static void updateIndexSettings(String index, Settings.Builder settings) throws IOException { @@ -1657,6 +1700,14 @@ public abstract class ESRestTestCase extends ESTestCase { return responseEntity; } + protected static XContentParser responseAsParser(Response response) throws IOException { + return XContentHelper.createParser(XContentParserConfiguration.EMPTY, responseAsBytes(response), XContentType.JSON); + } + + protected static BytesReference responseAsBytes(Response response) throws IOException { + return new BytesArray(EntityUtils.toByteArray(response.getEntity())); + } + protected static void registerRepository(String repository, String type, boolean verify, Settings settings) throws IOException { registerRepository(client(), repository, type, verify, settings); } @@ -2015,4 +2066,5 @@ public abstract class ESRestTestCase extends ESTestCase { return FieldCapabilitiesResponse.fromXContent(parser); } } + } diff --git a/x-pack/plugin/async-search/qa/security/src/javaRestTest/java/org/elasticsearch/xpack/search/AsyncSearchSecurityIT.java b/x-pack/plugin/async-search/qa/security/src/javaRestTest/java/org/elasticsearch/xpack/search/AsyncSearchSecurityIT.java index b9fc52d7e01a..687a3ee8e176 100644 --- a/x-pack/plugin/async-search/qa/security/src/javaRestTest/java/org/elasticsearch/xpack/search/AsyncSearchSecurityIT.java +++ b/x-pack/plugin/async-search/qa/security/src/javaRestTest/java/org/elasticsearch/xpack/search/AsyncSearchSecurityIT.java @@ -61,35 +61,35 @@ public class AsyncSearchSecurityIT extends ESRestTestCase { index("index", "0", "foo", "bar"); index("index", "1", "bar", "baz"); index("index", "2", "baz", "boo"); - refresh("index"); + refresh(adminClient(), "index"); createIndex("index-user1", Settings.EMPTY); index("index-user1", "0", "foo", "bar"); - refresh("index-user1"); + refresh(adminClient(), "index-user1"); createIndex("index-user2", Settings.EMPTY); index("index-user2", "0", "foo", "bar"); index("index-user2", "1", "bar", "baz"); - refresh("index-user2"); + refresh(adminClient(), "index-user2"); } public void testWithDlsAndFls() throws Exception { Response submitResp = submitAsyncSearch("*", "*", TimeValue.timeValueSeconds(10), "user-dls"); assertOK(submitResp); SearchHit[] hits = getSearchHits(extractResponseId(submitResp), "user-dls"); - assertThat(hits, arrayContainingInAnyOrder(new CustomMatcher("\"index\" doc 1 matcher") { + assertThat(hits, arrayContainingInAnyOrder(new CustomMatcher<>("\"index\" doc 1 matcher") { @Override public boolean matches(Object actual) { SearchHit hit = (SearchHit) actual; return "index".equals(hit.getIndex()) && "1".equals(hit.getId()) && hit.getSourceAsMap().isEmpty(); } - }, new CustomMatcher("\"index\" doc 2 matcher") { + }, new CustomMatcher<>("\"index\" doc 2 matcher") { @Override public boolean matches(Object actual) { SearchHit hit = (SearchHit) actual; return "index".equals(hit.getIndex()) && "2".equals(hit.getId()) && "boo".equals(hit.getSourceAsMap().get("baz")); } - }, new CustomMatcher("\"index-user2\" doc 1 matcher") { + }, new CustomMatcher<>("\"index-user2\" doc 1 matcher") { @Override public boolean matches(Object actual) { SearchHit hit = (SearchHit) actual; @@ -274,13 +274,13 @@ public class AsyncSearchSecurityIT extends ESRestTestCase { assertOK(dlsResp); assertThat( getSearchHits(extractResponseId(dlsResp), "user-dls"), - arrayContainingInAnyOrder(new CustomMatcher("\"index\" doc 1 matcher") { + arrayContainingInAnyOrder(new CustomMatcher<>("\"index\" doc 1 matcher") { @Override public boolean matches(Object actual) { SearchHit hit = (SearchHit) actual; return "index".equals(hit.getIndex()) && "1".equals(hit.getId()) && hit.getSourceAsMap().isEmpty(); } - }, new CustomMatcher("\"index\" doc 2 matcher") { + }, new CustomMatcher<>("\"index\" doc 2 matcher") { @Override public boolean matches(Object actual) { SearchHit hit = (SearchHit) actual; @@ -294,7 +294,7 @@ public class AsyncSearchSecurityIT extends ESRestTestCase { } static String extractResponseId(Response response) throws IOException { - Map map = toMap(response); + var map = responseAsMap(response); return (String) map.get("id"); } @@ -315,10 +315,6 @@ public class AsyncSearchSecurityIT extends ESRestTestCase { assertOK(client().performRequest(request)); } - static void refresh(String index) throws IOException { - assertOK(adminClient().performRequest(new Request("POST", "/" + index + "/_refresh"))); - } - static Response get(String index, String id, String user) throws IOException { final Request request = new Request("GET", "/" + index + "/_doc/" + id); setRunAsHeader(request, user); @@ -348,14 +344,6 @@ public class AsyncSearchSecurityIT extends ESRestTestCase { return client().performRequest(request); } - static Map toMap(Response response) throws IOException { - return toMap(EntityUtils.toString(response.getEntity())); - } - - static Map toMap(String response) { - return XContentHelper.convertToMap(JsonXContent.jsonXContent, response, false); - } - static void setRunAsHeader(Request request, String user) { final RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder(); builder.addHeader(RUN_AS_USER_HEADER, user); @@ -369,7 +357,7 @@ public class AsyncSearchSecurityIT extends ESRestTestCase { request.addParameter("keep_alive", between(1, 5) + "m"); final Response response = client().performRequest(request); assertOK(response); - return (String) toMap(response).get("id"); + return (String) responseAsMap(response).get("id"); } static Response submitAsyncSearchWithPIT(String pit, String query, TimeValue waitForCompletion, String user) throws IOException { diff --git a/x-pack/plugin/ccr/qa/multi-cluster/src/test/java/org/elasticsearch/xpack/ccr/ChainIT.java b/x-pack/plugin/ccr/qa/multi-cluster/src/test/java/org/elasticsearch/xpack/ccr/ChainIT.java index 8ffbaaaacb56..f2b431ed1c8b 100644 --- a/x-pack/plugin/ccr/qa/multi-cluster/src/test/java/org/elasticsearch/xpack/ccr/ChainIT.java +++ b/x-pack/plugin/ccr/qa/multi-cluster/src/test/java/org/elasticsearch/xpack/ccr/ChainIT.java @@ -25,12 +25,12 @@ public class ChainIT extends ESCCRRestTestCase { mapping = """ "_source": { "includes": ["field"], "excludes": ["filtered_field"]}"""; } - createIndex(leaderIndexName, Settings.EMPTY, mapping); + createIndex(adminClient(), leaderIndexName, Settings.EMPTY, mapping, null); for (int i = 0; i < numDocs; i++) { logger.info("Indexing doc [{}]", i); index(client(), leaderIndexName, Integer.toString(i), "field", i, "filtered_field", "true"); } - refresh(leaderIndexName); + refresh(adminClient(), leaderIndexName); verifyDocuments(leaderIndexName, numDocs, "filtered_field:true"); } else if ("middle".equals(targetCluster)) { logger.info("Running against middle cluster"); diff --git a/x-pack/plugin/ccr/qa/multi-cluster/src/test/java/org/elasticsearch/xpack/ccr/FollowIndexIT.java b/x-pack/plugin/ccr/qa/multi-cluster/src/test/java/org/elasticsearch/xpack/ccr/FollowIndexIT.java index c34351020547..ba0706656b6e 100644 --- a/x-pack/plugin/ccr/qa/multi-cluster/src/test/java/org/elasticsearch/xpack/ccr/FollowIndexIT.java +++ b/x-pack/plugin/ccr/qa/multi-cluster/src/test/java/org/elasticsearch/xpack/ccr/FollowIndexIT.java @@ -48,12 +48,12 @@ public class FollowIndexIT extends ESCCRRestTestCase { mapping = """ "_source": { "includes": ["field"], "excludes": ["filtered_field"]}"""; } - createIndex(leaderIndexName, Settings.EMPTY, mapping); + createIndex(adminClient(), leaderIndexName, Settings.EMPTY, mapping, null); for (int i = 0; i < numDocs; i++) { logger.info("Indexing doc [{}]", i); index(client(), leaderIndexName, Integer.toString(i), "field", i, "filtered_field", "true"); } - refresh(leaderIndexName); + refresh(adminClient(), leaderIndexName); verifyDocuments(leaderIndexName, numDocs, "filtered_field:true"); } else if ("follow".equals(targetCluster)) { logger.info("Running against follow cluster"); @@ -100,7 +100,7 @@ public class FollowIndexIT extends ESCCRRestTestCase { public void testFollowThatOverridesRequiredLeaderSetting() throws IOException { if ("leader".equals(targetCluster)) { - createIndex("override_leader_index", Settings.EMPTY); + createIndex(adminClient(), "override_leader_index", Settings.EMPTY); } else { final Settings settings = Settings.builder().put("index.number_of_shards", 5).build(); final ResponseException responseException = expectThrows( @@ -124,7 +124,7 @@ public class FollowIndexIT extends ESCCRRestTestCase { public void testFollowThatOverridesNonExistentSetting() throws IOException { if ("leader".equals(targetCluster)) { - createIndex("override_leader_index_non_existent_setting", Settings.EMPTY); + createIndex(adminClient(), "override_leader_index_non_existent_setting", Settings.EMPTY); } else { final Settings settings = Settings.builder().put("index.non_existent_setting", randomAlphaOfLength(3)).build(); final ResponseException responseException = expectThrows( @@ -213,7 +213,7 @@ public class FollowIndexIT extends ESCCRRestTestCase { registerRepository(repository, FsRepository.TYPE, true, Settings.builder().put("location", repositoryPath).build()); final String indexName = "index-" + testPrefix; - createIndex(indexName, Settings.EMPTY); + createIndex(adminClient(), indexName, Settings.EMPTY); final String snapshot = "snapshot-" + testPrefix; deleteSnapshot(repository, snapshot, true); @@ -249,6 +249,7 @@ public class FollowIndexIT extends ESCCRRestTestCase { if ("leader".equals(targetCluster)) { logger.info("Running against leader cluster"); createIndex( + adminClient(), leaderIndexName, Settings.builder() .put(IndexSettings.MODE.getKey(), "time_series") @@ -257,13 +258,14 @@ public class FollowIndexIT extends ESCCRRestTestCase { .put(IndexSettings.TIME_SERIES_END_TIME.getKey(), "2021-04-29T00:00:00Z") .build(), """ - "properties": {"@timestamp": {"type": "date"}, "dim": {"type": "keyword", "time_series_dimension": true}}""" + "properties": {"@timestamp": {"type": "date"}, "dim": {"type": "keyword", "time_series_dimension": true}}""", + null ); for (int i = 0; i < numDocs; i++) { logger.info("Indexing doc [{}]", i); index(client(), leaderIndexName, null, "@timestamp", basetime + TimeUnit.SECONDS.toMillis(i * 10), "dim", "foobar"); } - refresh(leaderIndexName); + refresh(adminClient(), leaderIndexName); verifyDocuments(client(), leaderIndexName, numDocs); } else if ("follow".equals(targetCluster)) { logger.info("Running against follow cluster"); diff --git a/x-pack/plugin/ccr/qa/security/src/test/java/org/elasticsearch/xpack/ccr/FollowIndexSecurityIT.java b/x-pack/plugin/ccr/qa/security/src/test/java/org/elasticsearch/xpack/ccr/FollowIndexSecurityIT.java index b2d0ca845152..72a0316fb888 100644 --- a/x-pack/plugin/ccr/qa/security/src/test/java/org/elasticsearch/xpack/ccr/FollowIndexSecurityIT.java +++ b/x-pack/plugin/ccr/qa/security/src/test/java/org/elasticsearch/xpack/ccr/FollowIndexSecurityIT.java @@ -53,8 +53,8 @@ public class FollowIndexSecurityIT extends ESCCRRestTestCase { final String unallowedIndex = "unallowed-index"; if ("leader".equals(targetCluster)) { logger.info("Running against leader cluster"); - createIndex(allowedIndex, Settings.EMPTY); - createIndex(unallowedIndex, Settings.EMPTY); + createIndex(adminClient(), allowedIndex, Settings.EMPTY); + createIndex(adminClient(), unallowedIndex, Settings.EMPTY); for (int i = 0; i < numDocs; i++) { logger.info("Indexing doc [{}]", i); index(allowedIndex, Integer.toString(i), "field", i); @@ -63,7 +63,7 @@ public class FollowIndexSecurityIT extends ESCCRRestTestCase { logger.info("Indexing doc [{}]", i); index(unallowedIndex, Integer.toString(i), "field", i); } - refresh(allowedIndex); + refresh(adminClient(), allowedIndex); verifyDocuments(allowedIndex, numDocs, "*:*"); } else { followIndex("leader_cluster", allowedIndex, allowedIndex); @@ -195,7 +195,7 @@ public class FollowIndexSecurityIT extends ESCCRRestTestCase { if ("leader".equals(targetCluster)) { logger.info("running against leader cluster"); final Settings indexSettings = Settings.builder().put("index.number_of_replicas", 0).put("index.number_of_shards", 1).build(); - createIndex(forgetLeader, indexSettings); + createIndex(adminClient(), forgetLeader, indexSettings); } else { logger.info("running against follower cluster"); followIndex(client(), "leader_cluster", forgetLeader, forgetFollower); @@ -249,7 +249,7 @@ public class FollowIndexSecurityIT extends ESCCRRestTestCase { .put("index.number_of_shards", 1) .put("index.soft_deletes.enabled", true) .build(); - createIndex(cleanLeader, indexSettings); + createIndex(adminClient(), cleanLeader, indexSettings); } else { logger.info("running against follower cluster"); followIndex(client(), "leader_cluster", cleanLeader, cleanFollower); diff --git a/x-pack/plugin/ccr/qa/src/main/java/org/elasticsearch/xpack/ccr/ESCCRRestTestCase.java b/x-pack/plugin/ccr/qa/src/main/java/org/elasticsearch/xpack/ccr/ESCCRRestTestCase.java index 595bcd6112e3..b88f751941a7 100644 --- a/x-pack/plugin/ccr/qa/src/main/java/org/elasticsearch/xpack/ccr/ESCCRRestTestCase.java +++ b/x-pack/plugin/ccr/qa/src/main/java/org/elasticsearch/xpack/ccr/ESCCRRestTestCase.java @@ -64,10 +64,6 @@ public class ESCCRRestTestCase extends ESRestTestCase { assertOK(client.performRequest(request)); } - protected static void refresh(String index) throws IOException { - assertOK(adminClient().performRequest(new Request("POST", "/" + index + "/_refresh"))); - } - protected static void resumeFollow(String followIndex) throws IOException { final Request request = new Request("POST", "/" + followIndex + "/_ccr/resume_follow"); request.setJsonEntity("{\"read_poll_timeout\": \"10ms\"}"); @@ -302,16 +298,6 @@ public class ESCCRRestTestCase extends ESRestTestCase { protected record CcrNodeTask(String remoteCluster, String leaderIndex, String followerIndex, int shardId) {} - protected static void createIndex(String name, Settings settings) throws IOException { - createIndex(name, settings, ""); - } - - protected static void createIndex(String name, Settings settings, String mapping) throws IOException { - final Request request = new Request("PUT", "/" + name); - request.setJsonEntity("{ \"settings\": " + Strings.toString(settings) + ", \"mappings\" : {" + mapping + "} }"); - assertOK(adminClient().performRequest(request)); - } - protected static boolean indexExists(String index) throws IOException { Response response = adminClient().performRequest(new Request("HEAD", "/" + index)); return RestStatus.OK.getStatus() == response.getStatusLine().getStatusCode(); diff --git a/x-pack/plugin/eql/qa/common/src/main/java/org/elasticsearch/test/eql/DataLoader.java b/x-pack/plugin/eql/qa/common/src/main/java/org/elasticsearch/test/eql/DataLoader.java index 05208ccb82f6..0959e65276d0 100644 --- a/x-pack/plugin/eql/qa/common/src/main/java/org/elasticsearch/test/eql/DataLoader.java +++ b/x-pack/plugin/eql/qa/common/src/main/java/org/elasticsearch/test/eql/DataLoader.java @@ -15,7 +15,6 @@ import org.elasticsearch.action.support.WriteRequest; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; -import org.elasticsearch.client.indices.CreateIndexRequest; import org.elasticsearch.cluster.ClusterModule; import org.elasticsearch.common.CheckedBiFunction; import org.elasticsearch.common.util.Maps; @@ -124,11 +123,7 @@ public class DataLoader { } private static void createTestIndex(RestHighLevelClient client, String indexName, String mapping) throws IOException { - CreateIndexRequest request = new CreateIndexRequest(indexName); - if (mapping != null) { - request.mapping(mapping, XContentType.JSON); - } - client.indices().create(request, RequestOptions.DEFAULT); + ESRestTestCase.createIndex(client.getLowLevelClient(), indexName, null, mapping, null); } /** diff --git a/x-pack/plugin/eql/qa/common/src/main/java/org/elasticsearch/test/eql/EqlRestTestCase.java b/x-pack/plugin/eql/qa/common/src/main/java/org/elasticsearch/test/eql/EqlRestTestCase.java index c3192c71e784..ad4e34712e30 100644 --- a/x-pack/plugin/eql/qa/common/src/main/java/org/elasticsearch/test/eql/EqlRestTestCase.java +++ b/x-pack/plugin/eql/qa/common/src/main/java/org/elasticsearch/test/eql/EqlRestTestCase.java @@ -74,7 +74,7 @@ public abstract class EqlRestTestCase extends RemoteClusterAwareEqlRestTestCase assertThat(response.getStatusLine().getStatusCode(), is(400)); } - deleteIndex(defaultValidationIndexName); + deleteIndexWithProvisioningClient(defaultValidationIndexName); } @SuppressWarnings("unchecked") @@ -121,8 +121,8 @@ public abstract class EqlRestTestCase extends RemoteClusterAwareEqlRestTestCase assertEquals("2", events.get(1).get("_id")); } - deleteIndex("test1"); - deleteIndex("test2"); + deleteIndexWithProvisioningClient("test1"); + deleteIndexWithProvisioningClient("test2"); } @SuppressWarnings("unchecked") @@ -164,7 +164,7 @@ public abstract class EqlRestTestCase extends RemoteClusterAwareEqlRestTestCase assertEquals(1, events.size()); assertEquals("2", events.get(0).get("_id")); - deleteIndex("test"); + deleteIndexWithProvisioningClient("test"); } private void bulkIndex(String bulk) throws IOException { diff --git a/x-pack/plugin/eql/qa/common/src/main/java/org/elasticsearch/test/eql/RemoteClusterAwareEqlRestTestCase.java b/x-pack/plugin/eql/qa/common/src/main/java/org/elasticsearch/test/eql/RemoteClusterAwareEqlRestTestCase.java index e0ea99ddca3a..ae8ccf2522cd 100644 --- a/x-pack/plugin/eql/qa/common/src/main/java/org/elasticsearch/test/eql/RemoteClusterAwareEqlRestTestCase.java +++ b/x-pack/plugin/eql/qa/common/src/main/java/org/elasticsearch/test/eql/RemoteClusterAwareEqlRestTestCase.java @@ -113,7 +113,7 @@ public abstract class RemoteClusterAwareEqlRestTestCase extends ESRestTestCase { provisioningClient().performRequest(request); } - protected static void deleteIndex(String name) throws IOException { + protected static void deleteIndexWithProvisioningClient(String name) throws IOException { deleteIndex(provisioningClient(), name); } diff --git a/x-pack/plugin/eql/qa/security/src/javaRestTest/java/org/elasticsearch/xpack/eql/AsyncEqlSecurityIT.java b/x-pack/plugin/eql/qa/security/src/javaRestTest/java/org/elasticsearch/xpack/eql/AsyncEqlSecurityIT.java index 43f4d27868f1..d40545604f72 100644 --- a/x-pack/plugin/eql/qa/security/src/javaRestTest/java/org/elasticsearch/xpack/eql/AsyncEqlSecurityIT.java +++ b/x-pack/plugin/eql/qa/security/src/javaRestTest/java/org/elasticsearch/xpack/eql/AsyncEqlSecurityIT.java @@ -7,13 +7,11 @@ package org.elasticsearch.xpack.eql; -import org.apache.http.util.EntityUtils; import org.elasticsearch.client.Request; import org.elasticsearch.client.Response; import org.elasticsearch.client.ResponseException; import org.elasticsearch.common.Strings; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.core.TimeValue; import org.elasticsearch.test.rest.ESRestTestCase; import org.elasticsearch.xcontent.XContentBuilder; @@ -23,7 +21,6 @@ import org.elasticsearch.xpack.core.async.AsyncExecutionId; import org.junit.Before; import java.io.IOException; -import java.util.Map; import static org.elasticsearch.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.xpack.eql.SecurityUtils.secureClientSettings; @@ -45,15 +42,15 @@ public class AsyncEqlSecurityIT extends ESRestTestCase { public void indexDocuments() throws IOException { createIndex("index", Settings.EMPTY); index("index", "0", "event_type", "my_event", "@timestamp", "2020-04-09T12:35:48Z", "val", 0); - refresh("index"); + refresh(adminClient(), "index"); createIndex("index-user1", Settings.EMPTY); index("index-user1", "0", "event_type", "my_event", "@timestamp", "2020-04-09T12:35:48Z", "val", 0); - refresh("index-user1"); + refresh(adminClient(), "index-user1"); createIndex("index-user2", Settings.EMPTY); index("index-user2", "0", "event_type", "my_event", "@timestamp", "2020-04-09T12:35:48Z", "val", 0); - refresh("index-user2"); + refresh(adminClient(), "index-user2"); } public void testWithUsers() throws Exception { @@ -96,7 +93,7 @@ public class AsyncEqlSecurityIT extends ESRestTestCase { } static String extractResponseId(Response response) throws IOException { - Map map = toMap(response); + var map = responseAsMap(response); return (String) map.get("id"); } @@ -111,10 +108,6 @@ public class AsyncEqlSecurityIT extends ESRestTestCase { assertOK(client().performRequest(request)); } - static void refresh(String index) throws IOException { - assertOK(adminClient().performRequest(new Request("POST", "/" + index + "/_refresh"))); - } - static Response get(String index, String id, String user) throws IOException { final Request request = new Request("GET", "/" + index + "/_doc/" + id); setRunAsHeader(request, user); @@ -148,11 +141,4 @@ public class AsyncEqlSecurityIT extends ESRestTestCase { return client().performRequest(request); } - static Map toMap(Response response) throws IOException { - return toMap(EntityUtils.toString(response.getEntity())); - } - - static Map toMap(String response) { - return XContentHelper.convertToMap(JsonXContent.jsonXContent, response, false); - } } diff --git a/x-pack/plugin/ilm/qa/multi-cluster/src/test/java/org/elasticsearch/xpack/ilm/CCRIndexLifecycleIT.java b/x-pack/plugin/ilm/qa/multi-cluster/src/test/java/org/elasticsearch/xpack/ilm/CCRIndexLifecycleIT.java index d2dca266d587..d16d96bbb750 100644 --- a/x-pack/plugin/ilm/qa/multi-cluster/src/test/java/org/elasticsearch/xpack/ilm/CCRIndexLifecycleIT.java +++ b/x-pack/plugin/ilm/qa/multi-cluster/src/test/java/org/elasticsearch/xpack/ilm/CCRIndexLifecycleIT.java @@ -112,7 +112,7 @@ public class CCRIndexLifecycleIT extends ESCCRRestTestCase { String indexName = "unfollow-test-index"; if ("leader".equals(targetCluster)) { Settings indexSettings = Settings.builder().put("index.number_of_shards", 2).put("index.number_of_replicas", 0).build(); - createIndex(indexName, indexSettings); + createIndex(adminClient(), indexName, indexSettings); ensureGreen(indexName); } else if ("follow".equals(targetCluster)) { createNewSingletonPolicy("unfollow-only", "hot", UnfollowAction.INSTANCE, TimeValue.ZERO); diff --git a/x-pack/plugin/ilm/qa/with-security/src/javaRestTest/java/org/elasticsearch/xpack/security/PermissionsIT.java b/x-pack/plugin/ilm/qa/with-security/src/javaRestTest/java/org/elasticsearch/xpack/security/PermissionsIT.java index 04cd0731c906..05c95e3d1e70 100644 --- a/x-pack/plugin/ilm/qa/with-security/src/javaRestTest/java/org/elasticsearch/xpack/security/PermissionsIT.java +++ b/x-pack/plugin/ilm/qa/with-security/src/javaRestTest/java/org/elasticsearch/xpack/security/PermissionsIT.java @@ -283,7 +283,7 @@ public class PermissionsIT extends ESRestTestCase { // test_user: index docs using alias in the newly created index indexDocs("test_user", "x-pack-test-password", "foo_alias", 2); - refresh("foo_alias"); + refresh(adminClient(), "foo_alias"); // wait so the ILM policy triggers rollover action, verify that the new index exists assertBusy(() -> { @@ -294,7 +294,7 @@ public class PermissionsIT extends ESRestTestCase { // test_user: index docs using alias, now should be able write to new index indexDocs("test_user", "x-pack-test-password", "foo_alias", 1); - refresh("foo_alias"); + refresh(adminClient(), "foo_alias"); // verify that the doc has been indexed into new write index assertBusy(() -> { @@ -393,9 +393,4 @@ public class PermissionsIT extends ESRestTestCase { } } - private void refresh(String index) throws IOException { - Request request = new Request("POST", "/" + index + "/_refresh"); - assertOK(adminClient().performRequest(request)); - } - } diff --git a/x-pack/plugin/searchable-snapshots/src/test/java/org/elasticsearch/xpack/searchablesnapshots/AbstractSearchableSnapshotsRestTestCase.java b/x-pack/plugin/searchable-snapshots/src/test/java/org/elasticsearch/xpack/searchablesnapshots/AbstractSearchableSnapshotsRestTestCase.java index 0a4d8680c588..c5c45d268d89 100644 --- a/x-pack/plugin/searchable-snapshots/src/test/java/org/elasticsearch/xpack/searchablesnapshots/AbstractSearchableSnapshotsRestTestCase.java +++ b/x-pack/plugin/searchable-snapshots/src/test/java/org/elasticsearch/xpack/searchablesnapshots/AbstractSearchableSnapshotsRestTestCase.java @@ -533,11 +533,6 @@ public abstract class AbstractSearchableSnapshotsRestTestCase extends ESRestTest ); } - protected static void deleteIndex(String index) throws IOException { - final Response response = client().performRequest(new Request("DELETE", "/" + index)); - assertAcked("Fail to delete index [" + index + ']', response); - } - private static void assertAcked(String message, Response response) throws IOException { final int responseStatusCode = response.getStatusLine().getStatusCode(); assertThat( diff --git a/x-pack/plugin/security/src/internalClusterTest/java/org/elasticsearch/xpack/security/authc/TokenAuthIntegTests.java b/x-pack/plugin/security/src/internalClusterTest/java/org/elasticsearch/xpack/security/authc/TokenAuthIntegTests.java index 8cff238a4330..6c254bebad93 100644 --- a/x-pack/plugin/security/src/internalClusterTest/java/org/elasticsearch/xpack/security/authc/TokenAuthIntegTests.java +++ b/x-pack/plugin/security/src/internalClusterTest/java/org/elasticsearch/xpack/security/authc/TokenAuthIntegTests.java @@ -11,7 +11,6 @@ import org.elasticsearch.ElasticsearchSecurityException; import org.elasticsearch.ElasticsearchStatusException; import org.elasticsearch.Version; import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse; -import org.elasticsearch.action.admin.indices.refresh.RefreshRequest; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.support.PlainActionFuture; @@ -19,6 +18,7 @@ import org.elasticsearch.action.support.WriteRequest; import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.action.update.UpdateResponse; +import org.elasticsearch.client.Request; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.ResponseException; import org.elasticsearch.client.RestHighLevelClient; @@ -218,7 +218,9 @@ public class TokenAuthIntegTests extends SecurityIntegTestCase { assertThat(invalidateResponseTwo.getPreviouslyInvalidatedTokens(), equalTo(0)); assertThat(invalidateResponseTwo.getErrors(), empty()); } - restClient.indices().refresh(new RefreshRequest(SecuritySystemIndices.SECURITY_TOKENS_ALIAS), SECURITY_REQUEST_OPTIONS); + Request refreshRequest = new Request("POST", "/" + SecuritySystemIndices.SECURITY_TOKENS_ALIAS + "/_refresh"); + refreshRequest.setOptions(SECURITY_REQUEST_OPTIONS); + restClient.getLowLevelClient().performRequest(refreshRequest); SearchResponse searchResponse = restClient.search( new SearchRequest(SecuritySystemIndices.SECURITY_TOKENS_ALIAS).source( SearchSourceBuilder.searchSource().query(QueryBuilders.termQuery("doc_type", "token")).terminateAfter(1) diff --git a/x-pack/plugin/sql/qa/jdbc/src/main/java/org/elasticsearch/xpack/sql/qa/jdbc/ResultSetMetaDataTestCase.java b/x-pack/plugin/sql/qa/jdbc/src/main/java/org/elasticsearch/xpack/sql/qa/jdbc/ResultSetMetaDataTestCase.java index 8c8afc455025..20cc43b7a0d8 100644 --- a/x-pack/plugin/sql/qa/jdbc/src/main/java/org/elasticsearch/xpack/sql/qa/jdbc/ResultSetMetaDataTestCase.java +++ b/x-pack/plugin/sql/qa/jdbc/src/main/java/org/elasticsearch/xpack/sql/qa/jdbc/ResultSetMetaDataTestCase.java @@ -41,7 +41,7 @@ public abstract class ResultSetMetaDataTestCase extends JdbcIntegrationTestCase private static final String UNSIGNED_LONG_FIELD = "test_" + UNSIGNED_LONG_TYPE_NAME.toLowerCase(Locale.ROOT); private static void createMappedIndex(List fieldsNames) throws IOException { - ResultSetTestCase.createIndex("test"); + ResultSetTestCase.createIndexWithMapping("test"); ResultSetTestCase.updateMapping("test", builder -> { for (String field : fieldsNames) { builder.startObject(field).field("type", field.substring(5)).endObject(); diff --git a/x-pack/plugin/sql/qa/jdbc/src/main/java/org/elasticsearch/xpack/sql/qa/jdbc/ResultSetTestCase.java b/x-pack/plugin/sql/qa/jdbc/src/main/java/org/elasticsearch/xpack/sql/qa/jdbc/ResultSetTestCase.java index 7aafcce432a5..cbeeee12262c 100644 --- a/x-pack/plugin/sql/qa/jdbc/src/main/java/org/elasticsearch/xpack/sql/qa/jdbc/ResultSetTestCase.java +++ b/x-pack/plugin/sql/qa/jdbc/src/main/java/org/elasticsearch/xpack/sql/qa/jdbc/ResultSetTestCase.java @@ -246,7 +246,7 @@ public abstract class ResultSetTestCase extends JdbcIntegrationTestCase { } public void testGettingInvalidByte() throws IOException, SQLException { - createIndex("test"); + createIndexWithMapping("test"); updateMappingForNumericValuesTests("test"); updateMapping("test", builder -> { builder.startObject("test_keyword").field("type", "keyword").endObject(); @@ -316,7 +316,7 @@ public abstract class ResultSetTestCase extends JdbcIntegrationTestCase { public void testGettingInvalidByteFromUnsignedLong() throws IOException, SQLException { assumeTrue("Driver version [" + JDBC_DRIVER_VERSION + "] doesn't support UNSIGNED_LONGs", isUnsignedLongSupported()); - createIndex("test"); + createIndexWithMapping("test"); updateMappingForNumericValuesTests("test", singletonList(UNSIGNED_LONG_FIELD)); BigInteger bigIntegerNotByte = BigInteger.valueOf(randomLongBetween(Byte.MAX_VALUE + 1, Long.MAX_VALUE)); @@ -388,7 +388,7 @@ public abstract class ResultSetTestCase extends JdbcIntegrationTestCase { } public void testGettingInvalidShort() throws IOException, SQLException { - createIndex("test"); + createIndexWithMapping("test"); updateMappingForNumericValuesTests("test"); updateMapping("test", builder -> { builder.startObject("test_date").field("type", "date").endObject(); }); @@ -449,7 +449,7 @@ public abstract class ResultSetTestCase extends JdbcIntegrationTestCase { public void testGettingInvalidShortFromUnsignedLong() throws IOException, SQLException { assumeTrue("Driver version [" + JDBC_DRIVER_VERSION + "] doesn't support UNSIGNED_LONGs", isUnsignedLongSupported()); - createIndex("test"); + createIndexWithMapping("test"); updateMappingForNumericValuesTests("test", singletonList(UNSIGNED_LONG_FIELD)); BigInteger bigIntegerNotShort = BigInteger.valueOf(randomLongBetween(Short.MAX_VALUE + 1, Long.MAX_VALUE)); @@ -521,7 +521,7 @@ public abstract class ResultSetTestCase extends JdbcIntegrationTestCase { } public void testGettingInvalidInteger() throws IOException, SQLException { - createIndex("test"); + createIndexWithMapping("test"); updateMappingForNumericValuesTests("test"); updateMapping("test", builder -> { builder.startObject("test_date").field("type", "date").endObject(); }); @@ -576,7 +576,7 @@ public abstract class ResultSetTestCase extends JdbcIntegrationTestCase { public void testGettingInvalidIntegerFromUnsignedLong() throws IOException, SQLException { assumeTrue("Driver version [" + JDBC_DRIVER_VERSION + "] doesn't support UNSIGNED_LONGs", isUnsignedLongSupported()); - createIndex("test"); + createIndexWithMapping("test"); updateMappingForNumericValuesTests("test", singletonList(UNSIGNED_LONG_FIELD)); BigInteger bigIntegerNotInt = BigInteger.valueOf(randomLongBetween(getMaxIntPlusOne(), Long.MAX_VALUE)); @@ -645,7 +645,7 @@ public abstract class ResultSetTestCase extends JdbcIntegrationTestCase { } public void testGettingInvalidLong() throws IOException, SQLException { - createIndex("test"); + createIndexWithMapping("test"); updateMappingForNumericValuesTests("test"); updateMapping("test", builder -> { builder.startObject("test_date").field("type", "date").endObject(); }); @@ -690,7 +690,7 @@ public abstract class ResultSetTestCase extends JdbcIntegrationTestCase { public void testGettingInvalidLongFromUnsignedLong() throws IOException, SQLException { assumeTrue("Driver version [" + JDBC_DRIVER_VERSION + "] doesn't support UNSIGNED_LONGs", isUnsignedLongSupported()); - createIndex("test"); + createIndexWithMapping("test"); updateMappingForNumericValuesTests("test", singletonList(UNSIGNED_LONG_FIELD)); BigInteger bigIntegerNotLong = BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.valueOf(randomNonNegativeLong())); @@ -774,7 +774,7 @@ public abstract class ResultSetTestCase extends JdbcIntegrationTestCase { public void testGettingInvalidBigInteger() throws IOException, SQLException { assumeTrue("Driver version [" + JDBC_DRIVER_VERSION + "] doesn't support UNSIGNED_LONGs", isUnsignedLongSupported()); - createIndex("test"); + createIndexWithMapping("test"); updateMappingForNumericValuesTests("test"); updateMapping("test", builder -> { builder.startObject("test_keyword").field("type", "keyword").endObject(); @@ -809,7 +809,7 @@ public abstract class ResultSetTestCase extends JdbcIntegrationTestCase { public void testGettingValidNumbersWithCastingFromUnsignedLong() throws IOException, SQLException { assumeTrue("Driver version [" + JDBC_DRIVER_VERSION + "] doesn't support UNSIGNED_LONGs", isUnsignedLongSupported()); - createIndex("test"); + createIndexWithMapping("test"); updateMappingForNumericValuesTests("test", singletonList(UNSIGNED_LONG_FIELD)); byte randomNonNegativeByte = randomNonNegativeByte(); @@ -896,7 +896,7 @@ public abstract class ResultSetTestCase extends JdbcIntegrationTestCase { } public void testGettingInvalidDouble() throws IOException, SQLException { - createIndex("test"); + createIndexWithMapping("test"); updateMappingForNumericValuesTests("test"); updateMapping("test", builder -> { builder.startObject("test_keyword").field("type", "keyword").endObject(); @@ -979,7 +979,7 @@ public abstract class ResultSetTestCase extends JdbcIntegrationTestCase { } public void testGettingInvalidFloat() throws Exception { - createIndex("test"); + createIndexWithMapping("test"); updateMappingForNumericValuesTests("test"); updateMapping("test", builder -> { builder.startObject("test_keyword").field("type", "keyword").endObject(); @@ -1187,7 +1187,7 @@ public abstract class ResultSetTestCase extends JdbcIntegrationTestCase { } public void testGettingInvalidBigDecimal() throws IOException, SQLException { - createIndex("test"); + createIndexWithMapping("test"); updateMappingForNumericValuesTests("test"); updateMapping("test", builder -> { builder.startObject("test_keyword").field("type", "keyword").endObject(); @@ -1224,7 +1224,7 @@ public abstract class ResultSetTestCase extends JdbcIntegrationTestCase { } public void testGettingBooleanValues() throws Exception { - createIndex("test"); + createIndexWithMapping("test"); updateMappingForNumericValuesTests("test"); updateMapping("test", builder -> { builder.startObject("test_boolean").field("type", "boolean").endObject(); @@ -1307,7 +1307,7 @@ public abstract class ResultSetTestCase extends JdbcIntegrationTestCase { public void testGettingBooleanValuesFromUnsignedLong() throws IOException, SQLException { assumeTrue("Driver version [" + JDBC_DRIVER_VERSION + "] doesn't support UNSIGNED_LONGs", isUnsignedLongSupported()); - createIndex("test"); + createIndexWithMapping("test"); updateMappingForNumericValuesTests("test", singletonList(UNSIGNED_LONG_FIELD)); indexTestFieldsDoc("1", BigInteger.ONE); @@ -1334,7 +1334,7 @@ public abstract class ResultSetTestCase extends JdbcIntegrationTestCase { } private void setupDataForDateTimeTests(long randomLongDate, Long randomLongDateNanos) throws IOException { - createIndex("test"); + createIndexWithMapping("test"); updateMappingForNumericValuesTests("test"); updateMapping("test", builder -> { builder.startObject("test_boolean").field("type", "boolean").endObject(); @@ -1687,7 +1687,7 @@ public abstract class ResultSetTestCase extends JdbcIntegrationTestCase { public void testErrorsValidationForDateTimeTypesConvertingToUnsignedLong() throws IOException, SQLException { assumeTrue("Driver version [" + JDBC_DRIVER_VERSION + "] doesn't support UNSIGNED_LONGs", isUnsignedLongSupported()); - createIndex("test"); + createIndexWithMapping("test"); updateMappingForNumericValuesTests("test", singletonList(UNSIGNED_LONG_FIELD)); indexTestFieldsDoc("1", BigInteger.ONE); @@ -1711,7 +1711,7 @@ public abstract class ResultSetTestCase extends JdbcIntegrationTestCase { } public void testScalarOnDates() throws IOException, SQLException { - createIndex("test"); + createIndexWithMapping("test"); updateMapping("test", builder -> builder.startObject("test_date").field("type", "date").endObject()); // 2018-03-12 17:00:00 UTC @@ -1774,7 +1774,7 @@ public abstract class ResultSetTestCase extends JdbcIntegrationTestCase { "Driver version [" + JDBC_DRIVER_VERSION + "] doesn't support DATETIME with nanosecond resolution]", versionSupportsDateNanos() ); - createIndex("test"); + createIndexWithMapping("test"); updateMapping("test", builder -> builder.startObject("test_date_nanos").field("type", "date_nanos").endObject()); // 2018-03-12 17:00:00.123456789 UTC @@ -1835,7 +1835,7 @@ public abstract class ResultSetTestCase extends JdbcIntegrationTestCase { } public void testGetDateType() throws IOException, SQLException { - createIndex("test"); + createIndexWithMapping("test"); updateMapping("test", builder -> builder.startObject("test_date").field("type", "date").endObject()); // 2018-03-12 17:00:00 UTC @@ -1869,7 +1869,7 @@ public abstract class ResultSetTestCase extends JdbcIntegrationTestCase { } public void testGetDateTypeFromAggregation() throws IOException, SQLException { - createIndex("test"); + createIndexWithMapping("test"); updateMapping("test", builder -> builder.startObject("test_date").field("type", "date").endObject()); // 1984-05-02 14:59:12 UTC @@ -1897,7 +1897,7 @@ public abstract class ResultSetTestCase extends JdbcIntegrationTestCase { } public void testGetTimeType() throws IOException, SQLException { - createIndex("test"); + createIndexWithMapping("test"); updateMapping("test", builder -> builder.startObject("test_date").field("type", "date").endObject()); // 2018-03-12 17:20:30.123 UTC @@ -1925,7 +1925,7 @@ public abstract class ResultSetTestCase extends JdbcIntegrationTestCase { } public void testValidGetObjectCalls() throws IOException, SQLException { - createIndex("test"); + createIndexWithMapping("test"); updateMappingForNumericValuesTests("test"); updateMapping("test", builder -> { builder.startObject("test_boolean").field("type", "boolean").endObject(); @@ -2286,7 +2286,7 @@ public abstract class ResultSetTestCase extends JdbcIntegrationTestCase { } } - protected static void createIndex(String index) throws IOException { + protected static void createIndexWithMapping(String index) throws IOException { Request request = new Request("PUT", "/" + index); XContentBuilder createIndex = JsonXContent.contentBuilder().startObject(); createIndex.startObject("settings"); @@ -2319,7 +2319,7 @@ public abstract class ResultSetTestCase extends JdbcIntegrationTestCase { } private void createTestDataForMultiValueTests() throws IOException { - createIndex("test"); + createIndexWithMapping("test"); updateMapping("test", builder -> { builder.startObject("int").field("type", "integer").endObject(); builder.startObject("keyword").field("type", "keyword").endObject(); @@ -2341,7 +2341,7 @@ public abstract class ResultSetTestCase extends JdbcIntegrationTestCase { } private void createTestDataForMultiValuesInObjectsTests() throws IOException { - createIndex("test"); + createIndexWithMapping("test"); updateMapping("test", builder -> { builder.startObject("object") .startObject("properties") @@ -2392,7 +2392,7 @@ public abstract class ResultSetTestCase extends JdbcIntegrationTestCase { assertNotNull(esType); String esTypeName = esType.getName().toLowerCase(Locale.ROOT); - createIndex("test"); + createIndexWithMapping("test"); updateMapping("test", builder -> { builder.startObject("test_" + esTypeName).field("type", esTypeName).endObject(); builder.startObject("test_null_" + esTypeName).field("type", esTypeName).endObject(); @@ -2412,7 +2412,7 @@ public abstract class ResultSetTestCase extends JdbcIntegrationTestCase { } private void createTestDataForBooleanValueTests() throws IOException { - createIndex("test"); + createIndexWithMapping("test"); updateMapping("test", builder -> { builder.startObject("test_boolean").field("type", "boolean").endObject(); builder.startObject("test_null_boolean").field("type", "boolean").endObject(); @@ -2476,7 +2476,7 @@ public abstract class ResultSetTestCase extends JdbcIntegrationTestCase { */ private Map createTestDataForNumericValueTypes(Supplier randomGenerator) throws IOException { Map map = new HashMap<>(); - createIndex("test"); + createIndexWithMapping("test"); updateMappingForNumericValuesTests("test"); index("test", "1", builder -> { diff --git a/x-pack/plugin/sql/qa/server/multi-node/src/test/java/org/elasticsearch/xpack/sql/qa/multi_node/RestSqlMultinodeIT.java b/x-pack/plugin/sql/qa/server/multi-node/src/test/java/org/elasticsearch/xpack/sql/qa/multi_node/RestSqlMultinodeIT.java index 9b0546b5bdf2..27df5619b615 100644 --- a/x-pack/plugin/sql/qa/server/multi-node/src/test/java/org/elasticsearch/xpack/sql/qa/multi_node/RestSqlMultinodeIT.java +++ b/x-pack/plugin/sql/qa/server/multi-node/src/test/java/org/elasticsearch/xpack/sql/qa/multi_node/RestSqlMultinodeIT.java @@ -15,6 +15,7 @@ import org.elasticsearch.test.NotEqualMessageBuilder; import org.elasticsearch.test.rest.ESRestTestCase; import org.elasticsearch.xcontent.XContentBuilder; import org.elasticsearch.xcontent.json.JsonXContent; +import org.elasticsearch.xpack.sql.qa.rest.BaseRestSqlTestCase; import java.io.IOException; import java.nio.charset.UnsupportedCharsetException; @@ -26,7 +27,6 @@ import java.util.Map; import static java.util.Collections.singletonList; import static org.elasticsearch.xpack.sql.qa.rest.BaseRestSqlTestCase.query; import static org.elasticsearch.xpack.sql.qa.rest.BaseRestSqlTestCase.randomMode; -import static org.elasticsearch.xpack.sql.qa.rest.BaseRestSqlTestCase.toMap; import static org.elasticsearch.xpack.sql.qa.rest.RestSqlTestCase.SQL_QUERY_REST_ENDPOINT; import static org.elasticsearch.xpack.sql.qa.rest.RestSqlTestCase.columnInfo; @@ -104,7 +104,7 @@ public class RestSqlMultinodeIT extends ESRestTestCase { } private Map responseToMap(Response response) throws IOException { - return toMap(response, "plain"); + return BaseRestSqlTestCase.toMap(response, "plain"); } private void assertCount(RestClient client, int count) throws IOException { @@ -115,7 +115,7 @@ public class RestSqlMultinodeIT extends ESRestTestCase { Request request = new Request("POST", SQL_QUERY_REST_ENDPOINT); request.setJsonEntity(query("SELECT COUNT(*) FROM test").mode(mode).toString()); - Map actual = toMap(client.performRequest(request), mode); + Map actual = BaseRestSqlTestCase.toMap(client.performRequest(request), mode); if (false == expected.equals(actual)) { NotEqualMessageBuilder message = new NotEqualMessageBuilder(); diff --git a/x-pack/plugin/sql/qa/server/security/src/test/java/org/elasticsearch/xpack/sql/qa/security/RestSqlSecurityAsyncIT.java b/x-pack/plugin/sql/qa/server/security/src/test/java/org/elasticsearch/xpack/sql/qa/security/RestSqlSecurityAsyncIT.java index a2c19ee93361..0a0c3eed25cf 100644 --- a/x-pack/plugin/sql/qa/server/security/src/test/java/org/elasticsearch/xpack/sql/qa/security/RestSqlSecurityAsyncIT.java +++ b/x-pack/plugin/sql/qa/server/security/src/test/java/org/elasticsearch/xpack/sql/qa/security/RestSqlSecurityAsyncIT.java @@ -38,15 +38,15 @@ public class RestSqlSecurityAsyncIT extends ESRestTestCase { public void indexDocuments() throws IOException { createIndex("index", Settings.EMPTY); index("index", "0", "event_type", "my_event", "@timestamp", "2020-04-09T12:35:48Z", "val", 0); - refresh("index"); + refresh(adminClient(), "index"); createIndex("index-user1", Settings.EMPTY); index("index-user1", "0", "event_type", "my_event", "@timestamp", "2020-04-09T12:35:48Z", "val", 0); - refresh("index-user1"); + refresh(adminClient(), "index-user1"); createIndex("index-user2", Settings.EMPTY); index("index-user2", "0", "event_type", "my_event", "@timestamp", "2020-04-09T12:35:48Z", "val", 0); - refresh("index-user2"); + refresh(adminClient(), "index-user2"); } @Override @@ -135,10 +135,6 @@ public class RestSqlSecurityAsyncIT extends ESRestTestCase { assertOK(client().performRequest(request)); } - static void refresh(String index) throws IOException { - assertOK(adminClient().performRequest(new Request("POST", "/" + index + "/_refresh"))); - } - static Response get(String index, String id, String user) throws IOException { final Request request = new Request("GET", "/" + index + "/_doc/" + id); setRunAsHeader(request, user); diff --git a/x-pack/plugin/sql/qa/server/security/src/test/java/org/elasticsearch/xpack/sql/qa/security/UserFunctionIT.java b/x-pack/plugin/sql/qa/server/security/src/test/java/org/elasticsearch/xpack/sql/qa/security/UserFunctionIT.java index 4be397063b0b..1e6339bffab1 100644 --- a/x-pack/plugin/sql/qa/server/security/src/test/java/org/elasticsearch/xpack/sql/qa/security/UserFunctionIT.java +++ b/x-pack/plugin/sql/qa/server/security/src/test/java/org/elasticsearch/xpack/sql/qa/security/UserFunctionIT.java @@ -17,6 +17,7 @@ import org.elasticsearch.test.NotEqualMessageBuilder; import org.elasticsearch.test.rest.ESRestTestCase; import org.elasticsearch.xcontent.XContentBuilder; import org.elasticsearch.xcontent.json.JsonXContent; +import org.elasticsearch.xpack.sql.qa.rest.BaseRestSqlTestCase; import org.junit.After; import org.junit.Before; import org.junit.Rule; @@ -33,7 +34,6 @@ import java.util.Map; import static org.elasticsearch.xpack.sql.qa.rest.BaseRestSqlTestCase.query; import static org.elasticsearch.xpack.sql.qa.rest.BaseRestSqlTestCase.randomMode; -import static org.elasticsearch.xpack.sql.qa.rest.BaseRestSqlTestCase.toMap; import static org.elasticsearch.xpack.sql.qa.rest.RestSqlTestCase.SQL_QUERY_REST_ENDPOINT; import static org.elasticsearch.xpack.sql.qa.rest.RestSqlTestCase.columnInfo; @@ -165,7 +165,7 @@ public class UserFunctionIT extends ESRestTestCase { request.setOptions(options); } request.setEntity(new StringEntity(query(sql).mode(mode).toString(), ContentType.APPLICATION_JSON)); - return toMap(client().performRequest(request), mode); + return BaseRestSqlTestCase.toMap(client().performRequest(request), mode); } private void assertResponse(Map expected, Map actual) { diff --git a/x-pack/plugin/sql/qa/server/src/main/java/org/elasticsearch/xpack/sql/qa/jdbc/JdbcIntegrationTestCase.java b/x-pack/plugin/sql/qa/server/src/main/java/org/elasticsearch/xpack/sql/qa/jdbc/JdbcIntegrationTestCase.java index 2f7bcb71a79f..34383404544a 100644 --- a/x-pack/plugin/sql/qa/server/src/main/java/org/elasticsearch/xpack/sql/qa/jdbc/JdbcIntegrationTestCase.java +++ b/x-pack/plugin/sql/qa/server/src/main/java/org/elasticsearch/xpack/sql/qa/jdbc/JdbcIntegrationTestCase.java @@ -116,7 +116,7 @@ public abstract class JdbcIntegrationTestCase extends RemoteClusterAwareSqlRestT return connectionProperties; } - protected static void createIndex(String index) throws IOException { + protected static void createIndexWithSettingsAndMappings(String index) throws IOException { Request request = new Request("PUT", "/" + index); XContentBuilder createIndex = JsonXContent.contentBuilder().startObject(); createIndex.startObject("settings"); diff --git a/x-pack/plugin/sql/qa/server/src/main/java/org/elasticsearch/xpack/sql/qa/jdbc/SysColumnsTestCase.java b/x-pack/plugin/sql/qa/server/src/main/java/org/elasticsearch/xpack/sql/qa/jdbc/SysColumnsTestCase.java index 44a882cde21f..8239f9d2fc14 100644 --- a/x-pack/plugin/sql/qa/server/src/main/java/org/elasticsearch/xpack/sql/qa/jdbc/SysColumnsTestCase.java +++ b/x-pack/plugin/sql/qa/server/src/main/java/org/elasticsearch/xpack/sql/qa/jdbc/SysColumnsTestCase.java @@ -420,7 +420,7 @@ public class SysColumnsTestCase extends JdbcIntegrationTestCase { } private static void createIndexWithMapping(String indexName, CheckedConsumer mapping) throws Exception { - createIndex(indexName); + createIndexWithSettingsAndMappings(indexName); updateMapping(indexName, mapping); } diff --git a/x-pack/plugin/sql/qa/server/src/main/java/org/elasticsearch/xpack/sql/qa/rest/BaseRestSqlTestCase.java b/x-pack/plugin/sql/qa/server/src/main/java/org/elasticsearch/xpack/sql/qa/rest/BaseRestSqlTestCase.java index 236c8af0a1a1..14d0a9c3990a 100644 --- a/x-pack/plugin/sql/qa/server/src/main/java/org/elasticsearch/xpack/sql/qa/rest/BaseRestSqlTestCase.java +++ b/x-pack/plugin/sql/qa/server/src/main/java/org/elasticsearch/xpack/sql/qa/rest/BaseRestSqlTestCase.java @@ -212,10 +212,10 @@ public abstract class BaseRestSqlTestCase extends RemoteClusterAwareSqlRestTestC } protected void deleteTestIndex() throws IOException { - deleteIndex(TEST_INDEX); + deleteIndexWithProvisioningClient(TEST_INDEX); } - protected static void deleteIndex(String name) throws IOException { + protected static void deleteIndexWithProvisioningClient(String name) throws IOException { deleteIndex(provisioningClient(), name); } diff --git a/x-pack/plugin/sql/qa/server/src/main/java/org/elasticsearch/xpack/sql/qa/rest/RestSqlTestCase.java b/x-pack/plugin/sql/qa/server/src/main/java/org/elasticsearch/xpack/sql/qa/rest/RestSqlTestCase.java index b6ccc32ae7fb..2a64f5f5896c 100644 --- a/x-pack/plugin/sql/qa/server/src/main/java/org/elasticsearch/xpack/sql/qa/rest/RestSqlTestCase.java +++ b/x-pack/plugin/sql/qa/server/src/main/java/org/elasticsearch/xpack/sql/qa/rest/RestSqlTestCase.java @@ -278,7 +278,7 @@ public abstract class RestSqlTestCase extends BaseRestSqlTestCase implements Err assertNull(cursor); - deleteIndex("test_date_timezone"); + deleteIndexWithProvisioningClient("test_date_timezone"); } @AwaitsFix(bugUrl = "Unclear status, https://github.com/elastic/x-pack-elasticsearch/issues/2074") @@ -1152,7 +1152,7 @@ public abstract class RestSqlTestCase extends BaseRestSqlTestCase implements Err expected.put("rows", singletonList(singletonList(nullId))); assertResponse(expected, runSql(mode, "SELECT id FROM " + indexPattern("test_binary") + " WHERE binary IS NULL", false)); - deleteIndex("test_binary"); + deleteIndexWithProvisioningClient("test_binary"); } public void testPreventedUnsignedLongMaskedAccess() throws IOException { diff --git a/x-pack/plugin/sql/qa/server/src/main/java/org/elasticsearch/xpack/sql/qa/rest/RestSqlUsageTestCase.java b/x-pack/plugin/sql/qa/server/src/main/java/org/elasticsearch/xpack/sql/qa/rest/RestSqlUsageTestCase.java index 3c8ae1dc367a..7c9263de94aa 100644 --- a/x-pack/plugin/sql/qa/server/src/main/java/org/elasticsearch/xpack/sql/qa/rest/RestSqlUsageTestCase.java +++ b/x-pack/plugin/sql/qa/server/src/main/java/org/elasticsearch/xpack/sql/qa/rest/RestSqlUsageTestCase.java @@ -30,7 +30,6 @@ import java.util.Map; import static org.elasticsearch.xpack.sql.proto.CoreProtocol.SQL_QUERY_REST_ENDPOINT; import static org.elasticsearch.xpack.sql.proto.CoreProtocol.SQL_STATS_REST_ENDPOINT; import static org.elasticsearch.xpack.sql.proto.CoreProtocol.SQL_TRANSLATE_REST_ENDPOINT; -import static org.elasticsearch.xpack.sql.qa.rest.BaseRestSqlTestCase.toMap; import static org.elasticsearch.xpack.sql.qa.rest.RestSqlTestCase.query; public abstract class RestSqlUsageTestCase extends ESRestTestCase { @@ -345,7 +344,7 @@ public abstract class RestSqlUsageTestCase extends ESRestTestCase { request.setEntity( new StringEntity(RestSqlTestCase.cursor(cursor).mode(mode).clientId(clientType).toString(), ContentType.APPLICATION_JSON) ); - return (String) toMap(client().performRequest(request), mode).get("cursor"); + return (String) BaseRestSqlTestCase.toMap(client().performRequest(request), mode).get("cursor"); } @SuppressWarnings({ "unchecked", "rawtypes" }) @@ -380,7 +379,7 @@ public abstract class RestSqlUsageTestCase extends ESRestTestCase { ContentType.APPLICATION_JSON ) ); - return (String) toMap(client().performRequest(request), mode).get("cursor"); + return (String) BaseRestSqlTestCase.toMap(client().performRequest(request), mode).get("cursor"); } @SuppressWarnings({ "unchecked", "rawtypes" }) diff --git a/x-pack/qa/multi-node/src/test/java/org/elasticsearch/multi_node/RollupIT.java b/x-pack/qa/multi-node/src/test/java/org/elasticsearch/multi_node/RollupIT.java index 1368ee3a219f..17dcb7c90e3b 100644 --- a/x-pack/qa/multi-node/src/test/java/org/elasticsearch/multi_node/RollupIT.java +++ b/x-pack/qa/multi-node/src/test/java/org/elasticsearch/multi_node/RollupIT.java @@ -8,20 +8,17 @@ package org.elasticsearch.multi_node; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; -import org.apache.http.util.EntityUtils; import org.elasticsearch.client.Request; import org.elasticsearch.client.Response; import org.elasticsearch.common.Strings; import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; -import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.test.rest.ESRestTestCase; import org.elasticsearch.xcontent.ObjectPath; import org.elasticsearch.xcontent.XContentBuilder; -import org.elasticsearch.xcontent.json.JsonXContent; import java.io.IOException; import java.time.Instant; @@ -54,14 +51,6 @@ public class RollupIT extends ESRestTestCase { return Settings.builder().put(ThreadContext.PREFIX + ".Authorization", token).build(); } - static Map toMap(Response response) throws IOException { - return toMap(EntityUtils.toString(response.getEntity())); - } - - static Map toMap(String response) throws IOException { - return XContentHelper.convertToMap(JsonXContent.jsonXContent, response, false); - } - public void testBigRollup() throws Exception { final int numDocs = 200; String dateFormat = "strict_date_optional_time"; @@ -132,12 +121,12 @@ public class RollupIT extends ESRestTestCase { ] }""".formatted(pageSize)); - Map createRollupJobResponse = toMap(client().performRequest(createRollupJobRequest)); + var createRollupJobResponse = responseAsMap(client().performRequest(createRollupJobRequest)); assertThat(createRollupJobResponse.get("acknowledged"), equalTo(Boolean.TRUE)); // start the rollup job final Request startRollupJobRequest = new Request("POST", "_rollup/job/rollup-job-test/_start"); - Map startRollupJobResponse = toMap(client().performRequest(startRollupJobRequest)); + var startRollupJobResponse = responseAsMap(client().performRequest(startRollupJobRequest)); assertThat(startRollupJobResponse.get("started"), equalTo(Boolean.TRUE)); assertRollUpJob("rollup-job-test"); @@ -148,7 +137,7 @@ public class RollupIT extends ESRestTestCase { Response getRollupJobResponse = client().performRequest(getRollupJobRequest); assertThat(getRollupJobResponse.getStatusLine().getStatusCode(), equalTo(RestStatus.OK.getStatus())); - Map job = getJob(getRollupJobResponse, "rollup-job-test"); + Map job = getJob(getRollupJobResponse, "rollup-job-test"); if (job != null) { assertThat(ObjectPath.eval("status.job_state", job), equalTo("started")); assertThat(ObjectPath.eval("stats.rollups_indexed", job), equalTo(41)); @@ -157,7 +146,7 @@ public class RollupIT extends ESRestTestCase { // Refresh the rollup index to make sure all newly indexed docs are searchable final Request refreshRollupIndex = new Request("POST", "results-rollup/_refresh"); - toMap(client().performRequest(refreshRollupIndex)); + client().performRequest(refreshRollupIndex); String jsonRequestBody = """ { @@ -186,12 +175,12 @@ public class RollupIT extends ESRestTestCase { Request request = new Request("GET", "rollup-docs/_search"); request.setJsonEntity(jsonRequestBody); Response liveResponse = client().performRequest(request); - Map liveBody = toMap(liveResponse); + var liveBody = responseAsMap(liveResponse); request = new Request("GET", "results-rollup/_rollup_search"); request.setJsonEntity(jsonRequestBody); Response rollupResponse = client().performRequest(request); - Map rollupBody = toMap(rollupResponse); + var rollupBody = responseAsMap(rollupResponse); // Do the live agg results match the rollup agg results? assertThat( @@ -202,7 +191,7 @@ public class RollupIT extends ESRestTestCase { request = new Request("GET", "rollup-docs/_rollup_search"); request.setJsonEntity(jsonRequestBody); Response liveRollupResponse = client().performRequest(request); - Map liveRollupBody = toMap(liveRollupResponse); + var liveRollupBody = responseAsMap(liveRollupResponse); // Does searching the live index via rollup_search work match the live search? assertThat( @@ -219,8 +208,8 @@ public class RollupIT extends ESRestTestCase { // check that the rollup job is started using the RollUp API final Request getRollupJobRequest = new Request("GET", "_rollup/job/" + rollupJob); - Map getRollupJobResponse = toMap(client().performRequest(getRollupJobRequest)); - Map job = getJob(getRollupJobResponse, rollupJob); + var getRollupJobResponse = responseAsMap(client().performRequest(getRollupJobRequest)); + Map job = getJob(getRollupJobResponse, rollupJob); if (job != null) { assertThat(ObjectPath.eval("status.job_state", job), is(oneOf(states))); } @@ -229,7 +218,7 @@ public class RollupIT extends ESRestTestCase { final Request taskRequest = new Request("GET", "_tasks"); taskRequest.addParameter("detailed", "true"); taskRequest.addParameter("actions", "xpack/rollup/*"); - Map taskResponse = toMap(client().performRequest(taskRequest)); + var taskResponse = responseAsMap(client().performRequest(taskRequest)); Map taskResponseNodes = (Map) taskResponse.get("nodes"); Map taskResponseNode = (Map) taskResponseNodes.values().iterator().next(); Map taskResponseTasks = (Map) taskResponseNode.get("tasks"); @@ -238,7 +227,7 @@ public class RollupIT extends ESRestTestCase { // check that the rollup job is started using the Cluster State API final Request clusterStateRequest = new Request("GET", "_cluster/state/metadata"); - Map clusterStateResponse = toMap(client().performRequest(clusterStateRequest)); + var clusterStateResponse = responseAsMap(client().performRequest(clusterStateRequest)); List> rollupJobTasks = ObjectPath.eval("metadata.persistent_tasks.tasks", clusterStateResponse); boolean hasRollupTask = false; @@ -267,28 +256,26 @@ public class RollupIT extends ESRestTestCase { Response getRollupJobResponse = client().performRequest(getRollupJobRequest); assertThat(getRollupJobResponse.getStatusLine().getStatusCode(), equalTo(RestStatus.OK.getStatus())); - Map job = getJob(getRollupJobResponse, rollupJob); + Map job = getJob(getRollupJobResponse, rollupJob); if (job != null) { assertThat(ObjectPath.eval("status.job_state", job), is(oneOf(expectedStates))); } }, 30L, TimeUnit.SECONDS); } - private Map getJob(Response response, String targetJobId) throws IOException { + private Map getJob(Response response, String targetJobId) throws IOException { return getJob(ESRestTestCase.entityAsMap(response), targetJobId); } - @SuppressWarnings("unchecked") - private Map getJob(Map jobsMap, String targetJobId) throws IOException { - - List> jobs = (List>) XContentMapValues.extractValue("jobs", jobsMap); - + private Map getJob(Map jobsMap, String targetJobId) { + List jobs = (List) XContentMapValues.extractValue("jobs", jobsMap); if (jobs == null) { return null; } - for (Map job : jobs) { - String jobId = (String) ((Map) job.get("config")).get("id"); + for (Object item : jobs) { + Map job = (Map) item; + String jobId = (String) ((Map) job.get("config")).get("id"); if (jobId.equals(targetJobId)) { return job; } diff --git a/x-pack/qa/reindex-tests-with-security/src/test/java/org/elasticsearch/xpack/security/ReindexWithSecurityIT.java b/x-pack/qa/reindex-tests-with-security/src/test/java/org/elasticsearch/xpack/security/ReindexWithSecurityIT.java index 722f39949a41..e2681098ddb2 100644 --- a/x-pack/qa/reindex-tests-with-security/src/test/java/org/elasticsearch/xpack/security/ReindexWithSecurityIT.java +++ b/x-pack/qa/reindex-tests-with-security/src/test/java/org/elasticsearch/xpack/security/ReindexWithSecurityIT.java @@ -6,14 +6,18 @@ */ package org.elasticsearch.xpack.security; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; import org.elasticsearch.ElasticsearchStatusException; import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest; import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest.AliasActions; -import org.elasticsearch.action.admin.indices.refresh.RefreshRequest; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.support.master.AcknowledgedResponse; +import org.elasticsearch.client.Request; import org.elasticsearch.client.RequestOptions; +import org.elasticsearch.client.Response; import org.elasticsearch.client.RestHighLevelClient; +import org.elasticsearch.common.Strings; import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; @@ -24,6 +28,7 @@ import org.elasticsearch.index.reindex.DeleteByQueryRequest; import org.elasticsearch.index.reindex.ReindexRequest; import org.elasticsearch.index.reindex.UpdateByQueryRequest; import org.elasticsearch.test.rest.ESRestTestCase; +import org.elasticsearch.xcontent.XContentBuilder; import org.junit.AfterClass; import org.junit.BeforeClass; @@ -33,6 +38,7 @@ import java.net.URL; import java.nio.file.Path; import java.util.Collections; +import static org.elasticsearch.xcontent.XContentFactory.jsonBuilder; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; @@ -173,14 +179,19 @@ public class ReindexWithSecurityIT extends ESRestTestCase { request.addAliasAction(AliasActions.add().index(index).alias("alias")); } } - AcknowledgedResponse response = restClient.indices().updateAliases(request, RequestOptions.DEFAULT); + Request restRequest = new Request("POST", "/_aliases"); + XContentBuilder builder = jsonBuilder(); + request.toXContent(builder, null); + restRequest.setEntity(new StringEntity(Strings.toString(builder), ContentType.APPLICATION_JSON)); + Response restResponse = restClient.getLowLevelClient().performRequest(restRequest); + AcknowledgedResponse response = AcknowledgedResponse.fromXContent(responseAsParser(restResponse)); assertThat(response.isAcknowledged(), is(true)); } for (String index : indices) { restClient.index(new IndexRequest(index).source("field", "value"), RequestOptions.DEFAULT); } - restClient.indices().refresh(new RefreshRequest(indices), RequestOptions.DEFAULT); + refresh(restClient.getLowLevelClient(), String.join(",", indices)); } private class TestRestHighLevelClient extends RestHighLevelClient { diff --git a/x-pack/qa/repository-old-versions/src/test/java/org/elasticsearch/oldrepos/OldRepositoryAccessIT.java b/x-pack/qa/repository-old-versions/src/test/java/org/elasticsearch/oldrepos/OldRepositoryAccessIT.java index 2ce6e3ee7a80..fad7f93e6e2c 100644 --- a/x-pack/qa/repository-old-versions/src/test/java/org/elasticsearch/oldrepos/OldRepositoryAccessIT.java +++ b/x-pack/qa/repository-old-versions/src/test/java/org/elasticsearch/oldrepos/OldRepositoryAccessIT.java @@ -8,6 +8,8 @@ package org.elasticsearch.oldrepos; import org.apache.http.HttpHost; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; import org.elasticsearch.Version; import org.elasticsearch.action.admin.cluster.repositories.put.PutRepositoryRequest; import org.elasticsearch.action.admin.cluster.snapshots.get.GetSnapshotsRequest; @@ -18,15 +20,14 @@ import org.elasticsearch.action.admin.cluster.snapshots.status.SnapshotsStatusRe import org.elasticsearch.action.admin.cluster.snapshots.status.SnapshotsStatusResponse; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; +import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.client.Request; import org.elasticsearch.client.RequestOptions; +import org.elasticsearch.client.Response; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; -import org.elasticsearch.client.indices.CloseIndexRequest; -import org.elasticsearch.client.indices.GetMappingsRequest; -import org.elasticsearch.client.indices.PutMappingRequest; +import org.elasticsearch.client.core.ShardsAcknowledgedResponse; import org.elasticsearch.cluster.SnapshotsInProgress; -import org.elasticsearch.cluster.metadata.MappingMetadata; import org.elasticsearch.cluster.routing.Murmur3HashFunction; import org.elasticsearch.common.Strings; import org.elasticsearch.common.document.DocumentField; @@ -270,15 +271,10 @@ public class OldRepositoryAccessIT extends ESRestTestCase { ); // close indices - assertTrue(client.indices().close(new CloseIndexRequest("restored_" + indexName), RequestOptions.DEFAULT).isShardsAcknowledged()); - assertTrue( - client.indices().close(new CloseIndexRequest("mounted_full_copy_" + indexName), RequestOptions.DEFAULT).isShardsAcknowledged() - ); - assertTrue( - client.indices() - .close(new CloseIndexRequest("mounted_shared_cache_" + indexName), RequestOptions.DEFAULT) - .isShardsAcknowledged() - ); + RestClient llClient = client.getLowLevelClient(); + assertTrue(closeIndex(llClient, "restored_" + indexName).isShardsAcknowledged()); + assertTrue(closeIndex(llClient, "mounted_full_copy_" + indexName).isShardsAcknowledged()); + assertTrue(closeIndex(llClient, "mounted_shared_cache_" + indexName).isShardsAcknowledged()); // restore / mount again restoreMountAndVerify( @@ -329,16 +325,15 @@ public class OldRepositoryAccessIT extends ESRestTestCase { ensureGreen("restored_" + indexName); - MappingMetadata mapping = client.indices() - .getMapping(new GetMappingsRequest().indices("restored_" + indexName), RequestOptions.DEFAULT) - .mappings() - .get("restored_" + indexName); - logger.info("mapping for {}: {}", mapping.type(), mapping.source().string()); - Map root = mapping.sourceAsMap(); - assertThat(root, hasKey("_meta")); - assertThat(root.get("_meta"), instanceOf(Map.class)); + String restoredIndex = "restored_" + indexName; + RestClient llClient = client.getLowLevelClient(); + var response = responseAsMap(llClient.performRequest(new Request("GET", "/" + restoredIndex + "/_mapping"))); + Map mapping = ObjectPath.evaluate(response, restoredIndex + ".mappings"); + logger.info("mapping for {}: {}", restoredIndex, mapping); + assertThat(mapping, hasKey("_meta")); + assertThat(mapping.get("_meta"), instanceOf(Map.class)); @SuppressWarnings("unchecked") - Map meta = (Map) root.get("_meta"); + Map meta = (Map) mapping.get("_meta"); assertThat(meta, hasKey("legacy_mappings")); assertThat(meta.get("legacy_mappings"), instanceOf(Map.class)); @SuppressWarnings("unchecked") @@ -453,9 +448,10 @@ public class OldRepositoryAccessIT extends ESRestTestCase { mappingBuilder.startObject().startObject("properties"); mappingBuilder.startObject("val").field("type", "long").endObject(); mappingBuilder.endObject().endObject(); - assertTrue( - client.indices().putMapping(new PutMappingRequest(index).source(mappingBuilder), RequestOptions.DEFAULT).isAcknowledged() - ); + Request putMappingRequest = new Request("PUT", "/" + index + "/_mapping"); + putMappingRequest.setEntity(new StringEntity(Strings.toString(mappingBuilder), ContentType.APPLICATION_JSON)); + Response response = client.getLowLevelClient().performRequest(putMappingRequest); + assertTrue(AcknowledgedResponse.fromXContent(responseAsParser(response)).isAcknowledged()); // search using reverse sort on val searchResponse = client.search( @@ -496,4 +492,10 @@ public class OldRepositoryAccessIT extends ESRestTestCase { private int getIdAsNumeric(String id) { return Integer.parseInt(id.substring("testdoc".length())); } + + static ShardsAcknowledgedResponse closeIndex(RestClient client, String index) throws IOException { + Request request = new Request("POST", "/" + index + "/_close"); + Response response = client.performRequest(request); + return ShardsAcknowledgedResponse.fromXContent(responseAsParser(response)); + } } diff --git a/x-pack/qa/rolling-upgrade-multi-cluster/src/test/java/org/elasticsearch/upgrades/CcrRollingUpgradeIT.java b/x-pack/qa/rolling-upgrade-multi-cluster/src/test/java/org/elasticsearch/upgrades/CcrRollingUpgradeIT.java index 1e04f932c43a..9380fb18f4e0 100644 --- a/x-pack/qa/rolling-upgrade-multi-cluster/src/test/java/org/elasticsearch/upgrades/CcrRollingUpgradeIT.java +++ b/x-pack/qa/rolling-upgrade-multi-cluster/src/test/java/org/elasticsearch/upgrades/CcrRollingUpgradeIT.java @@ -10,7 +10,6 @@ import org.elasticsearch.Version; import org.elasticsearch.client.Request; import org.elasticsearch.client.ResponseException; import org.elasticsearch.client.RestClient; -import org.elasticsearch.common.Strings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.elasticsearch.xcontent.ObjectPath; @@ -291,15 +290,6 @@ public class CcrRollingUpgradeIT extends AbstractMultiClusterUpgradeTestCase { createIndex(client, indexName, indexSettings.build()); } - private static void createIndex(RestClient client, String name, Settings settings) throws IOException { - Request request = new Request("PUT", "/" + name); - request.setJsonEntity(""" - { - "settings": %s - }""".formatted(Strings.toString(settings))); - client.performRequest(request); - } - private static void followIndex(RestClient client, String leaderCluster, String leaderIndex, String followIndex) throws IOException { final Request request = new Request("PUT", "/" + followIndex + "/_ccr/follow?wait_for_active_shards=1"); request.setJsonEntity(""" diff --git a/x-pack/qa/rolling-upgrade/src/test/java/org/elasticsearch/upgrades/MlTrainedModelsUpgradeIT.java b/x-pack/qa/rolling-upgrade/src/test/java/org/elasticsearch/upgrades/MlTrainedModelsUpgradeIT.java index 13b6958c5aa9..cd85ae65421c 100644 --- a/x-pack/qa/rolling-upgrade/src/test/java/org/elasticsearch/upgrades/MlTrainedModelsUpgradeIT.java +++ b/x-pack/qa/rolling-upgrade/src/test/java/org/elasticsearch/upgrades/MlTrainedModelsUpgradeIT.java @@ -53,7 +53,7 @@ public class MlTrainedModelsUpgradeIT extends AbstractUpgradeTestCase { assumeTrue("We should only test if old cluster is after trained models we GA", UPGRADE_FROM_VERSION.after(Version.V_7_13_0)); switch (CLUSTER_TYPE) { case OLD -> { - createIndex(INDEX_NAME); + createIndexWithName(INDEX_NAME); indexData(INDEX_NAME, 1000); createAndRunClassificationJob(); createAndRunRegressionJob(); @@ -218,7 +218,7 @@ public class MlTrainedModelsUpgradeIT extends AbstractUpgradeTestCase { client().performRequest(putRequest); } - void createIndex(String index) throws IOException { + void createIndexWithName(String index) throws IOException { String mapping = """ "properties": { "%s": { diff --git a/x-pack/qa/rolling-upgrade/src/test/java/org/elasticsearch/upgrades/TransformSurvivesUpgradeIT.java b/x-pack/qa/rolling-upgrade/src/test/java/org/elasticsearch/upgrades/TransformSurvivesUpgradeIT.java index 1ffc7093eb44..f35bb39c7d93 100644 --- a/x-pack/qa/rolling-upgrade/src/test/java/org/elasticsearch/upgrades/TransformSurvivesUpgradeIT.java +++ b/x-pack/qa/rolling-upgrade/src/test/java/org/elasticsearch/upgrades/TransformSurvivesUpgradeIT.java @@ -116,7 +116,7 @@ public class TransformSurvivesUpgradeIT extends AbstractUpgradeTestCase { } private void createAndStartContinuousTransform() throws Exception { - createIndex(CONTINUOUS_TRANSFORM_SOURCE); + createIndexWithName(CONTINUOUS_TRANSFORM_SOURCE); long totalDocsWrittenSum = 0; for (TimeValue bucket : BUCKETS) { int docs = randomIntBetween(1, 25); @@ -339,7 +339,7 @@ public class TransformSurvivesUpgradeIT extends AbstractUpgradeTestCase { }, 60, TimeUnit.SECONDS); } - private void createIndex(String indexName) throws IOException { + private void createIndexWithName(String indexName) throws IOException { // create mapping try (XContentBuilder builder = jsonBuilder()) { builder.startObject(); diff --git a/x-pack/qa/smoke-test-plugins-ssl/src/test/java/org/elasticsearch/smoketest/SmokeTestMonitoringWithSecurityIT.java b/x-pack/qa/smoke-test-plugins-ssl/src/test/java/org/elasticsearch/smoketest/SmokeTestMonitoringWithSecurityIT.java index 42652ea9c971..5dbe708de001 100644 --- a/x-pack/qa/smoke-test-plugins-ssl/src/test/java/org/elasticsearch/smoketest/SmokeTestMonitoringWithSecurityIT.java +++ b/x-pack/qa/smoke-test-plugins-ssl/src/test/java/org/elasticsearch/smoketest/SmokeTestMonitoringWithSecurityIT.java @@ -16,9 +16,6 @@ import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.Response; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; -import org.elasticsearch.client.indices.GetIndexRequest; -import org.elasticsearch.client.indices.GetIndexTemplatesRequest; -import org.elasticsearch.client.indices.GetIndexTemplatesResponse; import org.elasticsearch.common.settings.MockSecureSettings; import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; @@ -191,21 +188,23 @@ public class SmokeTestMonitoringWithSecurityIT extends ESRestTestCase { RestHighLevelClient client = newHighLevelClient(); // Checks that the monitoring index templates have been installed - GetIndexTemplatesRequest templateRequest = new GetIndexTemplatesRequest(MONITORING_PATTERN); + Request templateRequest = new Request("GET", "/_index_template/" + MONITORING_PATTERN); assertBusy(() -> { try { - GetIndexTemplatesResponse response = client.indices().getIndexTemplate(templateRequest, RequestOptions.DEFAULT); - assertThat(response.getIndexTemplates().size(), greaterThanOrEqualTo(2)); + var response = responseAsMap(client.getLowLevelClient().performRequest(templateRequest)); + List templates = ObjectPath.evaluate(response, "index_templates"); + assertThat(templates.size(), greaterThanOrEqualTo(2)); } catch (Exception e) { fail("template not ready yet: " + e.getMessage()); } }); - GetIndexRequest indexRequest = new GetIndexRequest(MONITORING_PATTERN); + Request indexRequest = new Request("HEAD", MONITORING_PATTERN); // Waits for monitoring indices to be created assertBusy(() -> { try { - assertThat(client.indices().exists(indexRequest, RequestOptions.DEFAULT), equalTo(true)); + Response response = client.getLowLevelClient().performRequest(indexRequest); + assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); } catch (Exception e) { fail("monitoring index not created yet: " + e.getMessage()); }