diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/AsyncSearchRequestConverters.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/AsyncSearchRequestConverters.java deleted file mode 100644 index 5430e6a36c84b..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/AsyncSearchRequestConverters.java +++ /dev/null @@ -1,96 +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.HttpPost; -import org.elasticsearch.action.search.SearchRequest; -import org.elasticsearch.client.RequestConverters.Params; -import org.elasticsearch.client.asyncsearch.DeleteAsyncSearchRequest; -import org.elasticsearch.client.asyncsearch.GetAsyncSearchRequest; -import org.elasticsearch.client.asyncsearch.SubmitAsyncSearchRequest; -import org.elasticsearch.rest.action.search.RestSearchAction; - -import java.io.IOException; -import java.util.Locale; - -import static org.elasticsearch.client.RequestConverters.REQUEST_BODY_CONTENT_TYPE; - -final class AsyncSearchRequestConverters { - - static Request submitAsyncSearch(SubmitAsyncSearchRequest asyncSearchRequest) throws IOException { - String endpoint = new RequestConverters.EndpointBuilder().addCommaSeparatedPathParts(asyncSearchRequest.getIndices()) - .addPathPartAsIs("_async_search") - .build(); - Request request = new Request(HttpPost.METHOD_NAME, endpoint); - Params params = new RequestConverters.Params(); - // add all typical search params and search request source as body - addSearchRequestParams(params, asyncSearchRequest); - if (asyncSearchRequest.getSearchSource() != null) { - request.setEntity(RequestConverters.createEntity(asyncSearchRequest.getSearchSource(), REQUEST_BODY_CONTENT_TYPE)); - } - // set async search submit specific parameters - if (asyncSearchRequest.isKeepOnCompletion() != null) { - params.putParam("keep_on_completion", asyncSearchRequest.isKeepOnCompletion().toString()); - } - if (asyncSearchRequest.getKeepAlive() != null) { - params.putParam("keep_alive", asyncSearchRequest.getKeepAlive().getStringRep()); - } - if (asyncSearchRequest.getWaitForCompletionTimeout() != null) { - params.putParam("wait_for_completion_timeout", asyncSearchRequest.getWaitForCompletionTimeout().getStringRep()); - } - request.addParameters(params.asMap()); - return request; - } - - static void addSearchRequestParams(Params params, SubmitAsyncSearchRequest request) { - params.putParam(RestSearchAction.TYPED_KEYS_PARAM, "true"); - params.withRouting(request.getRouting()); - params.withPreference(request.getPreference()); - if (SearchRequest.DEFAULT_INDICES_OPTIONS.equals(request.getIndicesOptions()) == false) { - params.withIndicesOptions(request.getIndicesOptions()); - } - params.withSearchType(request.getSearchType().name().toLowerCase(Locale.ROOT)); - params.withMaxConcurrentShardRequests(request.getMaxConcurrentShardRequests()); - if (request.getRequestCache() != null) { - params.withRequestCache(request.getRequestCache()); - } - if (request.getAllowPartialSearchResults() != null) { - params.withAllowPartialResults(request.getAllowPartialSearchResults()); - } - if (request.getBatchedReduceSize() != null) { - params.withBatchedReduceSize(request.getBatchedReduceSize()); - } - } - - static Request getAsyncSearch(GetAsyncSearchRequest asyncSearchRequest) { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_async_search") - .addPathPart(asyncSearchRequest.getId()) - .build(); - Request request = new Request(HttpGet.METHOD_NAME, endpoint); - Params params = new RequestConverters.Params(); - params.putParam(RestSearchAction.TYPED_KEYS_PARAM, "true"); - if (asyncSearchRequest.getKeepAlive() != null) { - params.putParam("keep_alive", asyncSearchRequest.getKeepAlive().getStringRep()); - } - if (asyncSearchRequest.getWaitForCompletion() != null) { - params.putParam("wait_for_completion_timeout", asyncSearchRequest.getWaitForCompletion().getStringRep()); - } - request.addParameters(params.asMap()); - return request; - } - - static Request deleteAsyncSearch(DeleteAsyncSearchRequest deleteAsyncSearchRequest) { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_async_search") - .addPathPart(deleteAsyncSearchRequest.getId()) - .build(); - return new Request(HttpDelete.METHOD_NAME, endpoint); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/CcrRequestConverters.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/CcrRequestConverters.java deleted file mode 100644 index a558c2ff604fa..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/CcrRequestConverters.java +++ /dev/null @@ -1,139 +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.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.elasticsearch.client.ccr.CcrStatsRequest; -import org.elasticsearch.client.ccr.DeleteAutoFollowPatternRequest; -import org.elasticsearch.client.ccr.FollowInfoRequest; -import org.elasticsearch.client.ccr.FollowStatsRequest; -import org.elasticsearch.client.ccr.ForgetFollowerRequest; -import org.elasticsearch.client.ccr.GetAutoFollowPatternRequest; -import org.elasticsearch.client.ccr.PauseAutoFollowPatternRequest; -import org.elasticsearch.client.ccr.PauseFollowRequest; -import org.elasticsearch.client.ccr.PutAutoFollowPatternRequest; -import org.elasticsearch.client.ccr.PutFollowRequest; -import org.elasticsearch.client.ccr.ResumeAutoFollowPatternRequest; -import org.elasticsearch.client.ccr.ResumeFollowRequest; -import org.elasticsearch.client.ccr.UnfollowRequest; - -import java.io.IOException; - -import static org.elasticsearch.client.RequestConverters.REQUEST_BODY_CONTENT_TYPE; -import static org.elasticsearch.client.RequestConverters.createEntity; - -final class CcrRequestConverters { - - static Request putFollow(PutFollowRequest putFollowRequest) throws IOException { - String endpoint = new RequestConverters.EndpointBuilder().addPathPart(putFollowRequest.getFollowerIndex()) - .addPathPartAsIs("_ccr", "follow") - .build(); - Request request = new Request(HttpPut.METHOD_NAME, endpoint); - RequestConverters.Params parameters = new RequestConverters.Params(); - parameters.withWaitForActiveShards(putFollowRequest.waitForActiveShards()); - request.setEntity(createEntity(putFollowRequest, REQUEST_BODY_CONTENT_TYPE)); - request.addParameters(parameters.asMap()); - return request; - } - - static Request pauseFollow(PauseFollowRequest pauseFollowRequest) { - String endpoint = new RequestConverters.EndpointBuilder().addPathPart(pauseFollowRequest.getFollowerIndex()) - .addPathPartAsIs("_ccr", "pause_follow") - .build(); - return new Request(HttpPost.METHOD_NAME, endpoint); - } - - static Request resumeFollow(ResumeFollowRequest resumeFollowRequest) throws IOException { - String endpoint = new RequestConverters.EndpointBuilder().addPathPart(resumeFollowRequest.getFollowerIndex()) - .addPathPartAsIs("_ccr", "resume_follow") - .build(); - Request request = new Request(HttpPost.METHOD_NAME, endpoint); - request.setEntity(createEntity(resumeFollowRequest, REQUEST_BODY_CONTENT_TYPE)); - return request; - } - - static Request unfollow(UnfollowRequest unfollowRequest) { - String endpoint = new RequestConverters.EndpointBuilder().addPathPart(unfollowRequest.getFollowerIndex()) - .addPathPartAsIs("_ccr", "unfollow") - .build(); - return new Request(HttpPost.METHOD_NAME, endpoint); - } - - static Request forgetFollower(final ForgetFollowerRequest forgetFollowerRequest) throws IOException { - final String endpoint = new RequestConverters.EndpointBuilder().addPathPart(forgetFollowerRequest.leaderIndex()) - .addPathPartAsIs("_ccr") - .addPathPartAsIs("forget_follower") - .build(); - final Request request = new Request(HttpPost.METHOD_NAME, endpoint); - request.setEntity(createEntity(forgetFollowerRequest, REQUEST_BODY_CONTENT_TYPE)); - return request; - } - - static Request putAutoFollowPattern(PutAutoFollowPatternRequest putAutoFollowPatternRequest) throws IOException { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_ccr", "auto_follow") - .addPathPart(putAutoFollowPatternRequest.getName()) - .build(); - Request request = new Request(HttpPut.METHOD_NAME, endpoint); - request.setEntity(createEntity(putAutoFollowPatternRequest, REQUEST_BODY_CONTENT_TYPE)); - return request; - } - - static Request deleteAutoFollowPattern(DeleteAutoFollowPatternRequest deleteAutoFollowPatternRequest) { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_ccr", "auto_follow") - .addPathPart(deleteAutoFollowPatternRequest.getName()) - .build(); - return new Request(HttpDelete.METHOD_NAME, endpoint); - } - - static Request getAutoFollowPattern(GetAutoFollowPatternRequest getAutoFollowPatternRequest) { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_ccr", "auto_follow") - .addPathPart(getAutoFollowPatternRequest.getName()) - .build(); - return new Request(HttpGet.METHOD_NAME, endpoint); - } - - static Request pauseAutoFollowPattern(PauseAutoFollowPatternRequest pauseAutoFollowPatternRequest) throws IOException { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_ccr", "auto_follow") - .addPathPart(pauseAutoFollowPatternRequest.getName()) - .addPathPartAsIs("pause") - .build(); - return new Request(HttpPost.METHOD_NAME, endpoint); - } - - static Request resumeAutoFollowPattern(ResumeAutoFollowPatternRequest resumeAutoFollowPatternRequest) throws IOException { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_ccr", "auto_follow") - .addPathPart(resumeAutoFollowPatternRequest.getName()) - .addPathPartAsIs("resume") - .build(); - return new Request(HttpPost.METHOD_NAME, endpoint); - } - - static Request getCcrStats(CcrStatsRequest ccrStatsRequest) { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_ccr", "stats").build(); - return new Request(HttpGet.METHOD_NAME, endpoint); - } - - static Request getFollowStats(FollowStatsRequest followStatsRequest) { - String endpoint = new RequestConverters.EndpointBuilder().addPathPart(followStatsRequest.getFollowerIndex()) - .addPathPartAsIs("_ccr", "stats") - .build(); - return new Request(HttpGet.METHOD_NAME, endpoint); - } - - static Request getFollowInfo(FollowInfoRequest followInfoRequest) { - String endpoint = new RequestConverters.EndpointBuilder().addPathPart(followInfoRequest.getFollowerIndex()) - .addPathPartAsIs("_ccr", "info") - .build(); - return new Request(HttpGet.METHOD_NAME, endpoint); - } - -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/EnrichRequestConverters.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/EnrichRequestConverters.java deleted file mode 100644 index a00ae7624696d..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/EnrichRequestConverters.java +++ /dev/null @@ -1,67 +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.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.elasticsearch.client.enrich.DeletePolicyRequest; -import org.elasticsearch.client.enrich.ExecutePolicyRequest; -import org.elasticsearch.client.enrich.GetPolicyRequest; -import org.elasticsearch.client.enrich.PutPolicyRequest; -import org.elasticsearch.client.enrich.StatsRequest; - -import java.io.IOException; - -import static org.elasticsearch.client.RequestConverters.REQUEST_BODY_CONTENT_TYPE; -import static org.elasticsearch.client.RequestConverters.createEntity; - -final class EnrichRequestConverters { - - static Request putPolicy(PutPolicyRequest putPolicyRequest) throws IOException { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_enrich", "policy") - .addPathPart(putPolicyRequest.getName()) - .build(); - Request request = new Request(HttpPut.METHOD_NAME, endpoint); - request.setEntity(createEntity(putPolicyRequest, REQUEST_BODY_CONTENT_TYPE)); - return request; - } - - static Request deletePolicy(DeletePolicyRequest deletePolicyRequest) { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_enrich", "policy") - .addPathPart(deletePolicyRequest.getName()) - .build(); - return new Request(HttpDelete.METHOD_NAME, endpoint); - } - - static Request getPolicy(GetPolicyRequest getPolicyRequest) { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_enrich", "policy") - .addCommaSeparatedPathParts(getPolicyRequest.getNames()) - .build(); - return new Request(HttpGet.METHOD_NAME, endpoint); - } - - static Request stats(StatsRequest statsRequest) { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_enrich", "_stats").build(); - return new Request(HttpGet.METHOD_NAME, endpoint); - } - - static Request executePolicy(ExecutePolicyRequest executePolicyRequest) { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_enrich", "policy") - .addPathPart(executePolicyRequest.getName()) - .addPathPartAsIs("_execute") - .build(); - Request request = new Request(HttpPost.METHOD_NAME, endpoint); - if (executePolicyRequest.getWaitForCompletion() != null) { - request.addParameter("wait_for_completion", executePolicyRequest.getWaitForCompletion().toString()); - } - return request; - } - -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/GraphRequestConverters.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/GraphRequestConverters.java deleted file mode 100644 index 668654f301fca..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/GraphRequestConverters.java +++ /dev/null @@ -1,26 +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.HttpGet; -import org.elasticsearch.client.graph.GraphExploreRequest; - -import java.io.IOException; - -final class GraphRequestConverters { - - private GraphRequestConverters() {} - - static Request explore(GraphExploreRequest exploreRequest) throws IOException { - String endpoint = RequestConverters.endpoint(exploreRequest.indices(), "_graph/explore"); - Request request = new Request(HttpGet.METHOD_NAME, endpoint); - request.setEntity(RequestConverters.createEntity(exploreRequest, RequestConverters.REQUEST_BODY_CONTENT_TYPE)); - return request; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/LicenseRequestConverters.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/LicenseRequestConverters.java deleted file mode 100644 index c5caa6fccc3a6..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/LicenseRequestConverters.java +++ /dev/null @@ -1,92 +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.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.elasticsearch.client.license.DeleteLicenseRequest; -import org.elasticsearch.client.license.GetLicenseRequest; -import org.elasticsearch.client.license.PutLicenseRequest; -import org.elasticsearch.client.license.StartBasicRequest; -import org.elasticsearch.client.license.StartTrialRequest; - -final class LicenseRequestConverters { - - private LicenseRequestConverters() {} - - static Request putLicense(PutLicenseRequest putLicenseRequest) { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_license").build(); - Request request = new Request(HttpPut.METHOD_NAME, endpoint); - RequestConverters.Params parameters = new RequestConverters.Params(); - parameters.withTimeout(putLicenseRequest.timeout()); - parameters.withMasterTimeout(putLicenseRequest.masterNodeTimeout()); - if (putLicenseRequest.isAcknowledge()) { - parameters.putParam("acknowledge", "true"); - } - request.addParameters(parameters.asMap()); - request.setJsonEntity(putLicenseRequest.getLicenseDefinition()); - return request; - } - - static Request getLicense(GetLicenseRequest getLicenseRequest) { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_license").build(); - Request request = new Request(HttpGet.METHOD_NAME, endpoint); - RequestConverters.Params parameters = new RequestConverters.Params(); - parameters.withLocal(getLicenseRequest.isLocal()); - request.addParameters(parameters.asMap()); - return request; - } - - static Request deleteLicense(DeleteLicenseRequest deleteLicenseRequest) { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_license").build(); - Request request = new Request(HttpDelete.METHOD_NAME, endpoint); - RequestConverters.Params parameters = new RequestConverters.Params(); - parameters.withTimeout(deleteLicenseRequest.timeout()); - parameters.withMasterTimeout(deleteLicenseRequest.masterNodeTimeout()); - request.addParameters(parameters.asMap()); - return request; - } - - static Request startTrial(StartTrialRequest startTrialRequest) { - final String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_license", "start_trial").build(); - final Request request = new Request(HttpPost.METHOD_NAME, endpoint); - - RequestConverters.Params parameters = new RequestConverters.Params(); - parameters.putParam("acknowledge", Boolean.toString(startTrialRequest.isAcknowledge())); - if (startTrialRequest.getLicenseType() != null) { - parameters.putParam("type", startTrialRequest.getLicenseType()); - } - request.addParameters(parameters.asMap()); - return request; - } - - static Request startBasic(StartBasicRequest startBasicRequest) { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_license", "start_basic").build(); - Request request = new Request(HttpPost.METHOD_NAME, endpoint); - RequestConverters.Params parameters = new RequestConverters.Params(); - parameters.withTimeout(startBasicRequest.timeout()); - parameters.withMasterTimeout(startBasicRequest.masterNodeTimeout()); - if (startBasicRequest.isAcknowledge()) { - parameters.putParam("acknowledge", "true"); - } - request.addParameters(parameters.asMap()); - return request; - } - - static Request getLicenseTrialStatus() { - return new Request(HttpGet.METHOD_NAME, "/_license/trial_status"); - } - - static Request getLicenseBasicStatus() { - return new Request(HttpGet.METHOD_NAME, "/_license/basic_status"); - } - -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/RollupRequestConverters.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/RollupRequestConverters.java deleted file mode 100644 index b0177c1c57f73..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/RollupRequestConverters.java +++ /dev/null @@ -1,96 +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.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.elasticsearch.action.search.SearchRequest; -import org.elasticsearch.client.rollup.DeleteRollupJobRequest; -import org.elasticsearch.client.rollup.GetRollupCapsRequest; -import org.elasticsearch.client.rollup.GetRollupIndexCapsRequest; -import org.elasticsearch.client.rollup.GetRollupJobRequest; -import org.elasticsearch.client.rollup.PutRollupJobRequest; -import org.elasticsearch.client.rollup.StartRollupJobRequest; -import org.elasticsearch.client.rollup.StopRollupJobRequest; - -import java.io.IOException; - -import static org.elasticsearch.client.RequestConverters.REQUEST_BODY_CONTENT_TYPE; -import static org.elasticsearch.client.RequestConverters.createEntity; - -final class RollupRequestConverters { - - private RollupRequestConverters() {} - - static Request putJob(final PutRollupJobRequest putRollupJobRequest) throws IOException { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_rollup", "job") - .addPathPart(putRollupJobRequest.getConfig().getId()) - .build(); - Request request = new Request(HttpPut.METHOD_NAME, endpoint); - request.setEntity(createEntity(putRollupJobRequest, REQUEST_BODY_CONTENT_TYPE)); - return request; - } - - static Request startJob(final StartRollupJobRequest startRollupJobRequest) throws IOException { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_rollup", "job") - .addPathPart(startRollupJobRequest.getJobId()) - .addPathPartAsIs("_start") - .build(); - return new Request(HttpPost.METHOD_NAME, endpoint); - } - - static Request stopJob(final StopRollupJobRequest stopRollupJobRequest) throws IOException { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_rollup", "job") - .addPathPart(stopRollupJobRequest.getJobId()) - .addPathPartAsIs("_stop") - .build(); - - Request request = new Request(HttpPost.METHOD_NAME, endpoint); - RequestConverters.Params parameters = new RequestConverters.Params(); - parameters.withTimeout(stopRollupJobRequest.timeout()); - if (stopRollupJobRequest.waitForCompletion() != null) { - parameters.withWaitForCompletion(stopRollupJobRequest.waitForCompletion()); - } - request.addParameters(parameters.asMap()); - return request; - } - - static Request getJob(final GetRollupJobRequest getRollupJobRequest) { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_rollup", "job") - .addPathPart(getRollupJobRequest.getJobId()) - .build(); - return new Request(HttpGet.METHOD_NAME, endpoint); - } - - static Request deleteJob(final DeleteRollupJobRequest deleteRollupJobRequest) throws IOException { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_rollup", "job") - .addPathPart(deleteRollupJobRequest.getId()) - .build(); - return new Request(HttpDelete.METHOD_NAME, endpoint); - } - - static Request search(final SearchRequest request) throws IOException { - return RequestConverters.search(request, "_rollup_search"); - } - - static Request getRollupCaps(final GetRollupCapsRequest getRollupCapsRequest) throws IOException { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_rollup", "data") - .addPathPart(getRollupCapsRequest.getIndexPattern()) - .build(); - return new Request(HttpGet.METHOD_NAME, endpoint); - } - - static Request getRollupIndexCaps(final GetRollupIndexCapsRequest getRollupIndexCapsRequest) throws IOException { - String endpoint = new RequestConverters.EndpointBuilder().addCommaSeparatedPathParts(getRollupIndexCapsRequest.indices()) - .addPathPartAsIs("_rollup", "data") - .build(); - return new Request(HttpGet.METHOD_NAME, endpoint); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/TextStructureRequestConverters.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/TextStructureRequestConverters.java deleted file mode 100644 index 2d2438d705162..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/TextStructureRequestConverters.java +++ /dev/null @@ -1,84 +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.HttpEntity; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.nio.entity.NByteArrayEntity; -import org.apache.lucene.util.BytesRef; -import org.elasticsearch.client.RequestConverters.EndpointBuilder; -import org.elasticsearch.client.textstructure.FindStructureRequest; -import org.elasticsearch.common.Strings; -import org.elasticsearch.common.bytes.BytesReference; -import org.elasticsearch.xcontent.XContentType; - -import static org.elasticsearch.client.RequestConverters.createContentType; - -final class TextStructureRequestConverters { - - private TextStructureRequestConverters() {} - - static Request findFileStructure(FindStructureRequest findStructureRequest) { - String endpoint = new EndpointBuilder().addPathPartAsIs("_text_structure").addPathPartAsIs("find_structure").build(); - Request request = new Request(HttpPost.METHOD_NAME, endpoint); - - RequestConverters.Params params = new RequestConverters.Params(); - if (findStructureRequest.getLinesToSample() != null) { - params.putParam(FindStructureRequest.LINES_TO_SAMPLE.getPreferredName(), findStructureRequest.getLinesToSample().toString()); - } - if (findStructureRequest.getTimeout() != null) { - params.putParam(FindStructureRequest.TIMEOUT.getPreferredName(), findStructureRequest.getTimeout().toString()); - } - if (findStructureRequest.getCharset() != null) { - params.putParam(FindStructureRequest.CHARSET.getPreferredName(), findStructureRequest.getCharset()); - } - if (findStructureRequest.getFormat() != null) { - params.putParam(FindStructureRequest.FORMAT.getPreferredName(), findStructureRequest.getFormat().toString()); - } - if (findStructureRequest.getColumnNames() != null) { - params.putParam( - FindStructureRequest.COLUMN_NAMES.getPreferredName(), - Strings.collectionToCommaDelimitedString(findStructureRequest.getColumnNames()) - ); - } - if (findStructureRequest.getHasHeaderRow() != null) { - params.putParam(FindStructureRequest.HAS_HEADER_ROW.getPreferredName(), findStructureRequest.getHasHeaderRow().toString()); - } - if (findStructureRequest.getDelimiter() != null) { - params.putParam(FindStructureRequest.DELIMITER.getPreferredName(), findStructureRequest.getDelimiter().toString()); - } - if (findStructureRequest.getQuote() != null) { - params.putParam(FindStructureRequest.QUOTE.getPreferredName(), findStructureRequest.getQuote().toString()); - } - if (findStructureRequest.getShouldTrimFields() != null) { - params.putParam( - FindStructureRequest.SHOULD_TRIM_FIELDS.getPreferredName(), - findStructureRequest.getShouldTrimFields().toString() - ); - } - if (findStructureRequest.getGrokPattern() != null) { - params.putParam(FindStructureRequest.GROK_PATTERN.getPreferredName(), findStructureRequest.getGrokPattern()); - } - if (findStructureRequest.getTimestampFormat() != null) { - params.putParam(FindStructureRequest.TIMESTAMP_FORMAT.getPreferredName(), findStructureRequest.getTimestampFormat()); - } - if (findStructureRequest.getTimestampField() != null) { - params.putParam(FindStructureRequest.TIMESTAMP_FIELD.getPreferredName(), findStructureRequest.getTimestampField()); - } - if (findStructureRequest.getExplain() != null) { - params.putParam(FindStructureRequest.EXPLAIN.getPreferredName(), findStructureRequest.getExplain().toString()); - } - request.addParameters(params.asMap()); - BytesReference sample = findStructureRequest.getSample(); - BytesRef source = sample.toBytesRef(); - HttpEntity byteEntity = new NByteArrayEntity(source.bytes, source.offset, source.length, createContentType(XContentType.JSON)); - request.setEntity(byteEntity); - return request; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/WatcherRequestConverters.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/WatcherRequestConverters.java deleted file mode 100644 index 456bf8b0d3fda..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/WatcherRequestConverters.java +++ /dev/null @@ -1,154 +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.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.entity.ContentType; -import org.apache.http.nio.entity.NByteArrayEntity; -import org.elasticsearch.client.watcher.AckWatchRequest; -import org.elasticsearch.client.watcher.ActivateWatchRequest; -import org.elasticsearch.client.watcher.DeactivateWatchRequest; -import org.elasticsearch.client.watcher.DeleteWatchRequest; -import org.elasticsearch.client.watcher.ExecuteWatchRequest; -import org.elasticsearch.client.watcher.GetWatchRequest; -import org.elasticsearch.client.watcher.PutWatchRequest; -import org.elasticsearch.client.watcher.StartWatchServiceRequest; -import org.elasticsearch.client.watcher.StopWatchServiceRequest; -import org.elasticsearch.client.watcher.WatcherStatsRequest; -import org.elasticsearch.common.bytes.BytesReference; -import org.elasticsearch.xcontent.XContentType; - -import java.io.IOException; - -final class WatcherRequestConverters { - - private WatcherRequestConverters() {} - - static Request startWatchService(StartWatchServiceRequest startWatchServiceRequest) { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_watcher").addPathPartAsIs("_start").build(); - - return new Request(HttpPost.METHOD_NAME, endpoint); - } - - static Request stopWatchService(StopWatchServiceRequest stopWatchServiceRequest) { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_watcher").addPathPartAsIs("_stop").build(); - - return new Request(HttpPost.METHOD_NAME, endpoint); - } - - static Request putWatch(PutWatchRequest putWatchRequest) { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_watcher", "watch") - .addPathPart(putWatchRequest.getId()) - .build(); - - Request request = new Request(HttpPut.METHOD_NAME, endpoint); - RequestConverters.Params params = new RequestConverters.Params().withIfSeqNo(putWatchRequest.ifSeqNo()) - .withIfPrimaryTerm(putWatchRequest.ifPrimaryTerm()); - if (putWatchRequest.isActive() == false) { - params.putParam("active", "false"); - } - request.addParameters(params.asMap()); - ContentType contentType = RequestConverters.createContentType(putWatchRequest.xContentType()); - BytesReference source = putWatchRequest.getSource(); - request.setEntity(new NByteArrayEntity(source.toBytesRef().bytes, 0, source.length(), contentType)); - return request; - } - - static Request getWatch(GetWatchRequest getWatchRequest) { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_watcher", "watch") - .addPathPart(getWatchRequest.getId()) - .build(); - - return new Request(HttpGet.METHOD_NAME, endpoint); - } - - static Request deactivateWatch(DeactivateWatchRequest deactivateWatchRequest) { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_watcher") - .addPathPartAsIs("watch") - .addPathPart(deactivateWatchRequest.getWatchId()) - .addPathPartAsIs("_deactivate") - .build(); - return new Request(HttpPut.METHOD_NAME, endpoint); - } - - static Request deleteWatch(DeleteWatchRequest deleteWatchRequest) { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_watcher", "watch") - .addPathPart(deleteWatchRequest.getId()) - .build(); - - Request request = new Request(HttpDelete.METHOD_NAME, endpoint); - return request; - } - - static Request executeWatch(ExecuteWatchRequest executeWatchRequest) throws IOException { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_watcher", "watch") - .addPathPart(executeWatchRequest.getId()) // will ignore if ID is null - .addPathPartAsIs("_execute") - .build(); - - Request request = new Request(HttpPost.METHOD_NAME, endpoint); - RequestConverters.Params params = new RequestConverters.Params(); - if (executeWatchRequest.isDebug()) { - params.putParam("debug", "true"); - } - if (executeWatchRequest.ignoreCondition()) { - params.putParam("ignore_condition", "true"); - } - if (executeWatchRequest.recordExecution()) { - params.putParam("record_execution", "true"); - } - request.addParameters(params.asMap()); - request.setEntity(RequestConverters.createEntity(executeWatchRequest, XContentType.JSON)); - return request; - } - - public static Request ackWatch(AckWatchRequest ackWatchRequest) { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_watcher", "watch") - .addPathPart(ackWatchRequest.getWatchId()) - .addPathPartAsIs("_ack") - .addCommaSeparatedPathParts(ackWatchRequest.getActionIds()) - .build(); - Request request = new Request(HttpPut.METHOD_NAME, endpoint); - return request; - } - - static Request activateWatch(ActivateWatchRequest activateWatchRequest) { - String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_watcher", "watch") - .addPathPart(activateWatchRequest.getWatchId()) - .addPathPartAsIs("_activate") - .build(); - Request request = new Request(HttpPut.METHOD_NAME, endpoint); - return request; - } - - static Request watcherStats(WatcherStatsRequest watcherStatsRequest) { - RequestConverters.EndpointBuilder builder = new RequestConverters.EndpointBuilder().addPathPartAsIs("_watcher", "stats"); - String endpoint = builder.build(); - Request request = new Request(HttpGet.METHOD_NAME, endpoint); - RequestConverters.Params parameters = new RequestConverters.Params(); - StringBuilder metric = new StringBuilder(); - if (watcherStatsRequest.includeCurrentWatches()) { - metric.append("current_watches"); - } - if (watcherStatsRequest.includeQueuedWatches()) { - if (metric.length() > 0) { - metric.append(","); - } - metric.append("queued_watches"); - } - if (metric.length() > 0) { - parameters.putParam("metric", metric.toString()); - } - request.addParameters(parameters.asMap()); - return request; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/AutoFollowStats.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/AutoFollowStats.java deleted file mode 100644 index 34ab9f3b972a1..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/AutoFollowStats.java +++ /dev/null @@ -1,150 +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.ccr; - -import org.elasticsearch.ElasticsearchException; -import org.elasticsearch.common.util.Maps; -import org.elasticsearch.core.Tuple; -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; - -import java.util.AbstractMap; -import java.util.List; -import java.util.Map; -import java.util.NavigableMap; - -public final class AutoFollowStats { - - static final ParseField NUMBER_OF_SUCCESSFUL_INDICES_AUTO_FOLLOWED = new ParseField("number_of_successful_follow_indices"); - static final ParseField NUMBER_OF_FAILED_INDICES_AUTO_FOLLOWED = new ParseField("number_of_failed_follow_indices"); - static final ParseField NUMBER_OF_FAILED_REMOTE_CLUSTER_STATE_REQUESTS = new ParseField( - "number_of_failed_remote_cluster_state_requests" - ); - static final ParseField RECENT_AUTO_FOLLOW_ERRORS = new ParseField("recent_auto_follow_errors"); - static final ParseField LEADER_INDEX = new ParseField("leader_index"); - static final ParseField TIMESTAMP = new ParseField("timestamp"); - static final ParseField AUTO_FOLLOW_EXCEPTION = new ParseField("auto_follow_exception"); - static final ParseField AUTO_FOLLOWED_CLUSTERS = new ParseField("auto_followed_clusters"); - static final ParseField CLUSTER_NAME = new ParseField("cluster_name"); - static final ParseField TIME_SINCE_LAST_CHECK_MILLIS = new ParseField("time_since_last_check_millis"); - static final ParseField LAST_SEEN_METADATA_VERSION = new ParseField("last_seen_metadata_version"); - - @SuppressWarnings("unchecked") - static final ConstructingObjectParser STATS_PARSER = new ConstructingObjectParser<>( - "auto_follow_stats", - true, - args -> new AutoFollowStats( - (Long) args[0], - (Long) args[1], - (Long) args[2], - ((List>>) args[3]).stream() - .collect(Maps.toUnmodifiableSortedMap(Map.Entry::getKey, Map.Entry::getValue)), - ((List>) args[4]).stream() - .collect(Maps.toUnmodifiableSortedMap(Map.Entry::getKey, Map.Entry::getValue)) - ) - ); - - static final ConstructingObjectParser>, Void> AUTO_FOLLOW_EXCEPTIONS_PARSER = - new ConstructingObjectParser<>( - "auto_follow_stats_errors", - true, - args -> new AbstractMap.SimpleEntry<>((String) args[0], Tuple.tuple((Long) args[1], (ElasticsearchException) args[2])) - ); - - private static final ConstructingObjectParser, Void> AUTO_FOLLOWED_CLUSTERS_PARSER = - new ConstructingObjectParser<>( - "auto_followed_clusters", - true, - args -> new AbstractMap.SimpleEntry<>((String) args[0], new AutoFollowedCluster((Long) args[1], (Long) args[2])) - ); - - static { - AUTO_FOLLOW_EXCEPTIONS_PARSER.declareString(ConstructingObjectParser.constructorArg(), LEADER_INDEX); - AUTO_FOLLOW_EXCEPTIONS_PARSER.declareLong(ConstructingObjectParser.constructorArg(), TIMESTAMP); - AUTO_FOLLOW_EXCEPTIONS_PARSER.declareObject( - ConstructingObjectParser.constructorArg(), - (p, c) -> ElasticsearchException.fromXContent(p), - AUTO_FOLLOW_EXCEPTION - ); - - AUTO_FOLLOWED_CLUSTERS_PARSER.declareString(ConstructingObjectParser.constructorArg(), CLUSTER_NAME); - AUTO_FOLLOWED_CLUSTERS_PARSER.declareLong(ConstructingObjectParser.constructorArg(), TIME_SINCE_LAST_CHECK_MILLIS); - AUTO_FOLLOWED_CLUSTERS_PARSER.declareLong(ConstructingObjectParser.constructorArg(), LAST_SEEN_METADATA_VERSION); - - STATS_PARSER.declareLong(ConstructingObjectParser.constructorArg(), NUMBER_OF_FAILED_INDICES_AUTO_FOLLOWED); - STATS_PARSER.declareLong(ConstructingObjectParser.constructorArg(), NUMBER_OF_FAILED_REMOTE_CLUSTER_STATE_REQUESTS); - STATS_PARSER.declareLong(ConstructingObjectParser.constructorArg(), NUMBER_OF_SUCCESSFUL_INDICES_AUTO_FOLLOWED); - STATS_PARSER.declareObjectArray( - ConstructingObjectParser.constructorArg(), - AUTO_FOLLOW_EXCEPTIONS_PARSER, - RECENT_AUTO_FOLLOW_ERRORS - ); - STATS_PARSER.declareObjectArray(ConstructingObjectParser.constructorArg(), AUTO_FOLLOWED_CLUSTERS_PARSER, AUTO_FOLLOWED_CLUSTERS); - } - - private final long numberOfFailedFollowIndices; - private final long numberOfFailedRemoteClusterStateRequests; - private final long numberOfSuccessfulFollowIndices; - private final NavigableMap> recentAutoFollowErrors; - private final NavigableMap autoFollowedClusters; - - AutoFollowStats( - long numberOfFailedFollowIndices, - long numberOfFailedRemoteClusterStateRequests, - long numberOfSuccessfulFollowIndices, - NavigableMap> recentAutoFollowErrors, - NavigableMap autoFollowedClusters - ) { - this.numberOfFailedFollowIndices = numberOfFailedFollowIndices; - this.numberOfFailedRemoteClusterStateRequests = numberOfFailedRemoteClusterStateRequests; - this.numberOfSuccessfulFollowIndices = numberOfSuccessfulFollowIndices; - this.recentAutoFollowErrors = recentAutoFollowErrors; - this.autoFollowedClusters = autoFollowedClusters; - } - - public long getNumberOfFailedFollowIndices() { - return numberOfFailedFollowIndices; - } - - public long getNumberOfFailedRemoteClusterStateRequests() { - return numberOfFailedRemoteClusterStateRequests; - } - - public long getNumberOfSuccessfulFollowIndices() { - return numberOfSuccessfulFollowIndices; - } - - public NavigableMap> getRecentAutoFollowErrors() { - return recentAutoFollowErrors; - } - - public NavigableMap getAutoFollowedClusters() { - return autoFollowedClusters; - } - - public static class AutoFollowedCluster { - - private final long timeSinceLastCheckMillis; - private final long lastSeenMetadataVersion; - - public AutoFollowedCluster(long timeSinceLastCheckMillis, long lastSeenMetadataVersion) { - this.timeSinceLastCheckMillis = timeSinceLastCheckMillis; - this.lastSeenMetadataVersion = lastSeenMetadataVersion; - } - - public long getTimeSinceLastCheckMillis() { - return timeSinceLastCheckMillis; - } - - public long getLastSeenMetadataVersion() { - return lastSeenMetadataVersion; - } - } - -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/CcrStatsRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/CcrStatsRequest.java deleted file mode 100644 index 1c82012211bfe..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/CcrStatsRequest.java +++ /dev/null @@ -1,13 +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.ccr; - -import org.elasticsearch.client.Validatable; - -public final class CcrStatsRequest implements Validatable {} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/CcrStatsResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/CcrStatsResponse.java deleted file mode 100644 index 21105916043e3..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/CcrStatsResponse.java +++ /dev/null @@ -1,50 +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.ccr; - -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentParser; - -public final class CcrStatsResponse { - - static final ParseField AUTO_FOLLOW_STATS_FIELD = new ParseField("auto_follow_stats"); - static final ParseField FOLLOW_STATS_FIELD = new ParseField("follow_stats"); - - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>("indices", true, args -> { - AutoFollowStats autoFollowStats = (AutoFollowStats) args[0]; - IndicesFollowStats indicesFollowStats = (IndicesFollowStats) args[1]; - return new CcrStatsResponse(autoFollowStats, indicesFollowStats); - }); - - static { - PARSER.declareObject(ConstructingObjectParser.constructorArg(), AutoFollowStats.STATS_PARSER, AUTO_FOLLOW_STATS_FIELD); - PARSER.declareObject(ConstructingObjectParser.constructorArg(), IndicesFollowStats.PARSER, FOLLOW_STATS_FIELD); - } - - public static CcrStatsResponse fromXContent(XContentParser parser) { - return PARSER.apply(parser, null); - } - - private final AutoFollowStats autoFollowStats; - private final IndicesFollowStats indicesFollowStats; - - public CcrStatsResponse(AutoFollowStats autoFollowStats, IndicesFollowStats indicesFollowStats) { - this.autoFollowStats = autoFollowStats; - this.indicesFollowStats = indicesFollowStats; - } - - public AutoFollowStats getAutoFollowStats() { - return autoFollowStats; - } - - public IndicesFollowStats getIndicesFollowStats() { - return indicesFollowStats; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/DeleteAutoFollowPatternRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/DeleteAutoFollowPatternRequest.java deleted file mode 100644 index 714ed298a9a97..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/DeleteAutoFollowPatternRequest.java +++ /dev/null @@ -1,26 +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.ccr; - -import org.elasticsearch.client.Validatable; - -import java.util.Objects; - -public final class DeleteAutoFollowPatternRequest implements Validatable { - - private final String name; - - public DeleteAutoFollowPatternRequest(String name) { - this.name = Objects.requireNonNull(name); - } - - public String getName() { - return name; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/FollowConfig.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/FollowConfig.java deleted file mode 100644 index 6c0c228ac40d8..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/FollowConfig.java +++ /dev/null @@ -1,256 +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.ccr; - -import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.common.unit.ByteSizeValue; -import org.elasticsearch.core.TimeValue; -import org.elasticsearch.xcontent.ObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.ToXContent; -import org.elasticsearch.xcontent.XContentBuilder; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.Objects; - -public class FollowConfig { - - static final ParseField SETTINGS = new ParseField("settings"); - static final ParseField MAX_READ_REQUEST_OPERATION_COUNT = new ParseField("max_read_request_operation_count"); - static final ParseField MAX_READ_REQUEST_SIZE = new ParseField("max_read_request_size"); - static final ParseField MAX_OUTSTANDING_READ_REQUESTS = new ParseField("max_outstanding_read_requests"); - static final ParseField MAX_WRITE_REQUEST_OPERATION_COUNT = new ParseField("max_write_request_operation_count"); - static final ParseField MAX_WRITE_REQUEST_SIZE = new ParseField("max_write_request_size"); - static final ParseField MAX_OUTSTANDING_WRITE_REQUESTS = new ParseField("max_outstanding_write_requests"); - static final ParseField MAX_WRITE_BUFFER_COUNT = new ParseField("max_write_buffer_count"); - static final ParseField MAX_WRITE_BUFFER_SIZE = new ParseField("max_write_buffer_size"); - static final ParseField MAX_RETRY_DELAY_FIELD = new ParseField("max_retry_delay"); - static final ParseField READ_POLL_TIMEOUT = new ParseField("read_poll_timeout"); - - private static final ObjectParser PARSER = new ObjectParser<>("follow_config", true, FollowConfig::new); - - static { - PARSER.declareObject(FollowConfig::setSettings, (p, c) -> Settings.fromXContent(p), SETTINGS); - PARSER.declareInt(FollowConfig::setMaxReadRequestOperationCount, MAX_READ_REQUEST_OPERATION_COUNT); - PARSER.declareInt(FollowConfig::setMaxOutstandingReadRequests, MAX_OUTSTANDING_READ_REQUESTS); - PARSER.declareField( - FollowConfig::setMaxReadRequestSize, - (p, c) -> ByteSizeValue.parseBytesSizeValue(p.text(), MAX_READ_REQUEST_SIZE.getPreferredName()), - MAX_READ_REQUEST_SIZE, - ObjectParser.ValueType.STRING - ); - PARSER.declareInt(FollowConfig::setMaxWriteRequestOperationCount, MAX_WRITE_REQUEST_OPERATION_COUNT); - PARSER.declareField( - FollowConfig::setMaxWriteRequestSize, - (p, c) -> ByteSizeValue.parseBytesSizeValue(p.text(), MAX_WRITE_REQUEST_SIZE.getPreferredName()), - MAX_WRITE_REQUEST_SIZE, - ObjectParser.ValueType.STRING - ); - PARSER.declareInt(FollowConfig::setMaxOutstandingWriteRequests, MAX_OUTSTANDING_WRITE_REQUESTS); - PARSER.declareInt(FollowConfig::setMaxWriteBufferCount, MAX_WRITE_BUFFER_COUNT); - PARSER.declareField( - FollowConfig::setMaxWriteBufferSize, - (p, c) -> ByteSizeValue.parseBytesSizeValue(p.text(), MAX_WRITE_BUFFER_SIZE.getPreferredName()), - MAX_WRITE_BUFFER_SIZE, - ObjectParser.ValueType.STRING - ); - PARSER.declareField( - FollowConfig::setMaxRetryDelay, - (p, c) -> TimeValue.parseTimeValue(p.text(), MAX_RETRY_DELAY_FIELD.getPreferredName()), - MAX_RETRY_DELAY_FIELD, - ObjectParser.ValueType.STRING - ); - PARSER.declareField( - FollowConfig::setReadPollTimeout, - (p, c) -> TimeValue.parseTimeValue(p.text(), READ_POLL_TIMEOUT.getPreferredName()), - READ_POLL_TIMEOUT, - ObjectParser.ValueType.STRING - ); - } - - static FollowConfig fromXContent(XContentParser parser) { - return PARSER.apply(parser, null); - } - - private Settings settings = Settings.EMPTY; - private Integer maxReadRequestOperationCount; - private Integer maxOutstandingReadRequests; - private ByteSizeValue maxReadRequestSize; - private Integer maxWriteRequestOperationCount; - private ByteSizeValue maxWriteRequestSize; - private Integer maxOutstandingWriteRequests; - private Integer maxWriteBufferCount; - private ByteSizeValue maxWriteBufferSize; - private TimeValue maxRetryDelay; - private TimeValue readPollTimeout; - - FollowConfig() {} - - public Settings getSettings() { - return settings; - } - - public void setSettings(final Settings settings) { - this.settings = Objects.requireNonNull(settings); - } - - public Integer getMaxReadRequestOperationCount() { - return maxReadRequestOperationCount; - } - - public void setMaxReadRequestOperationCount(Integer maxReadRequestOperationCount) { - this.maxReadRequestOperationCount = maxReadRequestOperationCount; - } - - public Integer getMaxOutstandingReadRequests() { - return maxOutstandingReadRequests; - } - - public void setMaxOutstandingReadRequests(Integer maxOutstandingReadRequests) { - this.maxOutstandingReadRequests = maxOutstandingReadRequests; - } - - public ByteSizeValue getMaxReadRequestSize() { - return maxReadRequestSize; - } - - public void setMaxReadRequestSize(ByteSizeValue maxReadRequestSize) { - this.maxReadRequestSize = maxReadRequestSize; - } - - public Integer getMaxWriteRequestOperationCount() { - return maxWriteRequestOperationCount; - } - - public void setMaxWriteRequestOperationCount(Integer maxWriteRequestOperationCount) { - this.maxWriteRequestOperationCount = maxWriteRequestOperationCount; - } - - public ByteSizeValue getMaxWriteRequestSize() { - return maxWriteRequestSize; - } - - public void setMaxWriteRequestSize(ByteSizeValue maxWriteRequestSize) { - this.maxWriteRequestSize = maxWriteRequestSize; - } - - public Integer getMaxOutstandingWriteRequests() { - return maxOutstandingWriteRequests; - } - - public void setMaxOutstandingWriteRequests(Integer maxOutstandingWriteRequests) { - this.maxOutstandingWriteRequests = maxOutstandingWriteRequests; - } - - public Integer getMaxWriteBufferCount() { - return maxWriteBufferCount; - } - - public void setMaxWriteBufferCount(Integer maxWriteBufferCount) { - this.maxWriteBufferCount = maxWriteBufferCount; - } - - public ByteSizeValue getMaxWriteBufferSize() { - return maxWriteBufferSize; - } - - public void setMaxWriteBufferSize(ByteSizeValue maxWriteBufferSize) { - this.maxWriteBufferSize = maxWriteBufferSize; - } - - public TimeValue getMaxRetryDelay() { - return maxRetryDelay; - } - - public void setMaxRetryDelay(TimeValue maxRetryDelay) { - this.maxRetryDelay = maxRetryDelay; - } - - public TimeValue getReadPollTimeout() { - return readPollTimeout; - } - - public void setReadPollTimeout(TimeValue readPollTimeout) { - this.readPollTimeout = readPollTimeout; - } - - void toXContentFragment(XContentBuilder builder, ToXContent.Params params) throws IOException { - if (settings.isEmpty() == false) { - builder.startObject(SETTINGS.getPreferredName()); - { - settings.toXContent(builder, params); - } - builder.endObject(); - } - if (maxReadRequestOperationCount != null) { - builder.field(MAX_READ_REQUEST_OPERATION_COUNT.getPreferredName(), maxReadRequestOperationCount); - } - if (maxReadRequestSize != null) { - builder.field(MAX_READ_REQUEST_SIZE.getPreferredName(), maxReadRequestSize.getStringRep()); - } - if (maxWriteRequestOperationCount != null) { - builder.field(MAX_WRITE_REQUEST_OPERATION_COUNT.getPreferredName(), maxWriteRequestOperationCount); - } - if (maxWriteRequestSize != null) { - builder.field(MAX_WRITE_REQUEST_SIZE.getPreferredName(), maxWriteRequestSize.getStringRep()); - } - if (maxWriteBufferCount != null) { - builder.field(MAX_WRITE_BUFFER_COUNT.getPreferredName(), maxWriteBufferCount); - } - if (maxWriteBufferSize != null) { - builder.field(MAX_WRITE_BUFFER_SIZE.getPreferredName(), maxWriteBufferSize.getStringRep()); - } - if (maxOutstandingReadRequests != null) { - builder.field(MAX_OUTSTANDING_READ_REQUESTS.getPreferredName(), maxOutstandingReadRequests); - } - if (maxOutstandingWriteRequests != null) { - builder.field(MAX_OUTSTANDING_WRITE_REQUESTS.getPreferredName(), maxOutstandingWriteRequests); - } - if (maxRetryDelay != null) { - builder.field(MAX_RETRY_DELAY_FIELD.getPreferredName(), maxRetryDelay.getStringRep()); - } - if (readPollTimeout != null) { - builder.field(READ_POLL_TIMEOUT.getPreferredName(), readPollTimeout.getStringRep()); - } - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - FollowConfig that = (FollowConfig) o; - return Objects.equals(maxReadRequestOperationCount, that.maxReadRequestOperationCount) - && Objects.equals(maxOutstandingReadRequests, that.maxOutstandingReadRequests) - && Objects.equals(maxReadRequestSize, that.maxReadRequestSize) - && Objects.equals(maxWriteRequestOperationCount, that.maxWriteRequestOperationCount) - && Objects.equals(maxWriteRequestSize, that.maxWriteRequestSize) - && Objects.equals(maxOutstandingWriteRequests, that.maxOutstandingWriteRequests) - && Objects.equals(maxWriteBufferCount, that.maxWriteBufferCount) - && Objects.equals(maxWriteBufferSize, that.maxWriteBufferSize) - && Objects.equals(maxRetryDelay, that.maxRetryDelay) - && Objects.equals(readPollTimeout, that.readPollTimeout); - } - - @Override - public int hashCode() { - return Objects.hash( - maxReadRequestOperationCount, - maxOutstandingReadRequests, - maxReadRequestSize, - maxWriteRequestOperationCount, - maxWriteRequestSize, - maxOutstandingWriteRequests, - maxWriteBufferCount, - maxWriteBufferSize, - maxRetryDelay, - readPollTimeout - ); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/FollowInfoRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/FollowInfoRequest.java deleted file mode 100644 index 495c9d4e26b69..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/FollowInfoRequest.java +++ /dev/null @@ -1,26 +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.ccr; - -import org.elasticsearch.client.Validatable; - -import java.util.Objects; - -public final class FollowInfoRequest implements Validatable { - - private final String followerIndex; - - public FollowInfoRequest(String followerIndex) { - this.followerIndex = Objects.requireNonNull(followerIndex); - } - - public String getFollowerIndex() { - return followerIndex; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/FollowInfoResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/FollowInfoResponse.java deleted file mode 100644 index 5d2dcef83cf7b..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/FollowInfoResponse.java +++ /dev/null @@ -1,173 +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.ccr; - -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentParser; - -import java.util.List; -import java.util.Objects; - -public final class FollowInfoResponse { - - static final ParseField FOLLOWER_INDICES_FIELD = new ParseField("follower_indices"); - - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "indices", - true, - args -> { - @SuppressWarnings("unchecked") - List infos = (List) args[0]; - return new FollowInfoResponse(infos); - } - ); - - static { - PARSER.declareObjectArray(ConstructingObjectParser.constructorArg(), FollowerInfo.PARSER, FOLLOWER_INDICES_FIELD); - } - - public static FollowInfoResponse fromXContent(XContentParser parser) { - return PARSER.apply(parser, null); - } - - private final List infos; - - FollowInfoResponse(List infos) { - this.infos = infos; - } - - public List getInfos() { - return infos; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - FollowInfoResponse that = (FollowInfoResponse) o; - return infos.equals(that.infos); - } - - @Override - public int hashCode() { - return Objects.hash(infos); - } - - public static final class FollowerInfo { - - static final ParseField FOLLOWER_INDEX_FIELD = new ParseField("follower_index"); - static final ParseField REMOTE_CLUSTER_FIELD = new ParseField("remote_cluster"); - static final ParseField LEADER_INDEX_FIELD = new ParseField("leader_index"); - static final ParseField STATUS_FIELD = new ParseField("status"); - static final ParseField PARAMETERS_FIELD = new ParseField("parameters"); - - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "follower_info", - true, - args -> { - return new FollowerInfo( - (String) args[0], - (String) args[1], - (String) args[2], - Status.fromString((String) args[3]), - (FollowConfig) args[4] - ); - } - ); - - static { - PARSER.declareString(ConstructingObjectParser.constructorArg(), FOLLOWER_INDEX_FIELD); - PARSER.declareString(ConstructingObjectParser.constructorArg(), REMOTE_CLUSTER_FIELD); - PARSER.declareString(ConstructingObjectParser.constructorArg(), LEADER_INDEX_FIELD); - PARSER.declareString(ConstructingObjectParser.constructorArg(), STATUS_FIELD); - PARSER.declareObject( - ConstructingObjectParser.optionalConstructorArg(), - (p, c) -> FollowConfig.fromXContent(p), - PARAMETERS_FIELD - ); - } - - private final String followerIndex; - private final String remoteCluster; - private final String leaderIndex; - private final Status status; - private final FollowConfig parameters; - - FollowerInfo(String followerIndex, String remoteCluster, String leaderIndex, Status status, FollowConfig parameters) { - this.followerIndex = followerIndex; - this.remoteCluster = remoteCluster; - this.leaderIndex = leaderIndex; - this.status = status; - this.parameters = parameters; - } - - public String getFollowerIndex() { - return followerIndex; - } - - public String getRemoteCluster() { - return remoteCluster; - } - - public String getLeaderIndex() { - return leaderIndex; - } - - public Status getStatus() { - return status; - } - - public FollowConfig getParameters() { - return parameters; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - FollowerInfo that = (FollowerInfo) o; - return Objects.equals(followerIndex, that.followerIndex) - && Objects.equals(remoteCluster, that.remoteCluster) - && Objects.equals(leaderIndex, that.leaderIndex) - && status == that.status - && Objects.equals(parameters, that.parameters); - } - - @Override - public int hashCode() { - return Objects.hash(followerIndex, remoteCluster, leaderIndex, status, parameters); - } - - } - - public enum Status { - - ACTIVE("active"), - PAUSED("paused"); - - private final String name; - - Status(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public static Status fromString(String value) { - return switch (value) { - case "active" -> Status.ACTIVE; - case "paused" -> Status.PAUSED; - default -> throw new IllegalArgumentException("unexpected status value [" + value + "]"); - }; - } - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/FollowStatsRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/FollowStatsRequest.java deleted file mode 100644 index ea1541a8a7068..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/FollowStatsRequest.java +++ /dev/null @@ -1,26 +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.ccr; - -import org.elasticsearch.client.Validatable; - -import java.util.Objects; - -public final class FollowStatsRequest implements Validatable { - - private final String followerIndex; - - public FollowStatsRequest(String followerIndex) { - this.followerIndex = Objects.requireNonNull(followerIndex); - } - - public String getFollowerIndex() { - return followerIndex; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/FollowStatsResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/FollowStatsResponse.java deleted file mode 100644 index 6123d8969cbf0..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/FollowStatsResponse.java +++ /dev/null @@ -1,28 +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.ccr; - -import org.elasticsearch.xcontent.XContentParser; - -public final class FollowStatsResponse { - - public static FollowStatsResponse fromXContent(XContentParser parser) { - return new FollowStatsResponse(IndicesFollowStats.PARSER.apply(parser, null)); - } - - private final IndicesFollowStats indicesFollowStats; - - public FollowStatsResponse(IndicesFollowStats indicesFollowStats) { - this.indicesFollowStats = indicesFollowStats; - } - - public IndicesFollowStats getIndicesFollowStats() { - return indicesFollowStats; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/ForgetFollowerRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/ForgetFollowerRequest.java deleted file mode 100644 index 2059648f150af..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/ForgetFollowerRequest.java +++ /dev/null @@ -1,79 +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.ccr; - -import org.elasticsearch.client.Validatable; -import org.elasticsearch.xcontent.ToXContentObject; -import org.elasticsearch.xcontent.XContentBuilder; - -import java.io.IOException; -import java.util.Objects; - -/** - * Represents a forget follower request. Note that this an expert API intended to be used only when unfollowing a follower index fails to - * remove the follower retention leases. Please be sure that you understand the purpose this API before using. - */ -public final class ForgetFollowerRequest implements ToXContentObject, Validatable { - - private final String followerCluster; - - private final String followerIndex; - - private final String followerIndexUUID; - - private final String leaderRemoteCluster; - - private final String leaderIndex; - - /** - * The name of the leader index. - * - * @return the name of the leader index - */ - public String leaderIndex() { - return leaderIndex; - } - - /** - * Construct a forget follower request. - * - * @param followerCluster the name of the cluster containing the follower index to forget - * @param followerIndex the name of follower index - * @param followerIndexUUID the UUID of the follower index - * @param leaderRemoteCluster the alias of the remote cluster containing the leader index from the perspective of the follower index - * @param leaderIndex the name of the leader index - */ - public ForgetFollowerRequest( - final String followerCluster, - final String followerIndex, - final String followerIndexUUID, - final String leaderRemoteCluster, - final String leaderIndex - ) { - this.followerCluster = Objects.requireNonNull(followerCluster); - this.followerIndex = Objects.requireNonNull(followerIndex); - this.followerIndexUUID = Objects.requireNonNull(followerIndexUUID); - this.leaderRemoteCluster = Objects.requireNonNull(leaderRemoteCluster); - this.leaderIndex = Objects.requireNonNull(leaderIndex); - } - - @Override - public XContentBuilder toXContent(final XContentBuilder builder, final Params params) throws IOException { - builder.startObject(); - { - builder.field("follower_cluster", followerCluster); - builder.field("follower_index", followerIndex); - builder.field("follower_index_uuid", followerIndexUUID); - builder.field("leader_remote_cluster", leaderRemoteCluster); - } - builder.endObject(); - return builder; - } - -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/GetAutoFollowPatternRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/GetAutoFollowPatternRequest.java deleted file mode 100644 index 750aa02e5096d..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/GetAutoFollowPatternRequest.java +++ /dev/null @@ -1,41 +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.ccr; - -import org.elasticsearch.client.Validatable; - -import java.util.Objects; - -/** - * Request class for get auto follow pattern api. - */ -public final class GetAutoFollowPatternRequest implements Validatable { - - private final String name; - - /** - * Get all auto follow patterns - */ - public GetAutoFollowPatternRequest() { - this.name = null; - } - - /** - * Get auto follow pattern with the specified name - * - * @param name The name of the auto follow pattern to get - */ - public GetAutoFollowPatternRequest(String name) { - this.name = Objects.requireNonNull(name); - } - - public String getName() { - return name; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/GetAutoFollowPatternResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/GetAutoFollowPatternResponse.java deleted file mode 100644 index d705e39a5b789..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/GetAutoFollowPatternResponse.java +++ /dev/null @@ -1,198 +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.ccr; - -import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.common.unit.ByteSizeValue; -import org.elasticsearch.common.util.Maps; -import org.elasticsearch.core.TimeValue; -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentParser; - -import java.util.AbstractMap; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.NavigableMap; -import java.util.Objects; - -public final class GetAutoFollowPatternResponse { - - static final ParseField PATTERNS_FIELD = new ParseField("patterns"); - static final ParseField NAME_FIELD = new ParseField("name"); - static final ParseField PATTERN_FIELD = new ParseField("pattern"); - - private static final ConstructingObjectParser, Void> ENTRY_PARSER = new ConstructingObjectParser<>( - "get_auto_follow_pattern_response", - true, - args -> new AbstractMap.SimpleEntry<>((String) args[0], (Pattern) args[1]) - ); - - static { - ENTRY_PARSER.declareString(ConstructingObjectParser.constructorArg(), NAME_FIELD); - ENTRY_PARSER.declareObject(ConstructingObjectParser.constructorArg(), Pattern.PARSER, PATTERN_FIELD); - } - - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "get_auto_follow_pattern_response", - true, - args -> { - @SuppressWarnings("unchecked") - List> entries = (List>) args[0]; - return new GetAutoFollowPatternResponse( - entries.stream().collect(Maps.toUnmodifiableSortedMap(Map.Entry::getKey, Map.Entry::getValue)) - ); - } - ); - - static { - PARSER.declareObjectArray(ConstructingObjectParser.constructorArg(), ENTRY_PARSER, PATTERNS_FIELD); - } - - public static GetAutoFollowPatternResponse fromXContent(final XContentParser parser) { - return PARSER.apply(parser, null); - } - - private final NavigableMap patterns; - - GetAutoFollowPatternResponse(NavigableMap patterns) { - this.patterns = Collections.unmodifiableNavigableMap(patterns); - } - - public NavigableMap getPatterns() { - return patterns; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - GetAutoFollowPatternResponse that = (GetAutoFollowPatternResponse) o; - return Objects.equals(patterns, that.patterns); - } - - @Override - public int hashCode() { - return Objects.hash(patterns); - } - - public static class Pattern extends FollowConfig { - - @SuppressWarnings("unchecked") - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "pattern", - true, - args -> new Pattern( - (String) args[0], - (List) args[1], - args[2] == null ? Collections.emptyList() : (List) args[2], - (String) args[3] - ) - ); - - static { - PARSER.declareString(ConstructingObjectParser.constructorArg(), PutFollowRequest.REMOTE_CLUSTER_FIELD); - PARSER.declareStringArray(ConstructingObjectParser.constructorArg(), PutAutoFollowPatternRequest.LEADER_PATTERNS_FIELD); - PARSER.declareStringArray( - ConstructingObjectParser.optionalConstructorArg(), - PutAutoFollowPatternRequest.LEADER_EXCLUSION_PATTERNS_FIELD - ); - PARSER.declareString(ConstructingObjectParser.optionalConstructorArg(), PutAutoFollowPatternRequest.FOLLOW_PATTERN_FIELD); - PARSER.declareObject(Pattern::setSettings, (p, c) -> Settings.fromXContent(p), PutAutoFollowPatternRequest.SETTINGS); - PARSER.declareInt(Pattern::setMaxReadRequestOperationCount, FollowConfig.MAX_READ_REQUEST_OPERATION_COUNT); - PARSER.declareField( - Pattern::setMaxReadRequestSize, - (p, c) -> ByteSizeValue.parseBytesSizeValue(p.text(), FollowConfig.MAX_READ_REQUEST_SIZE.getPreferredName()), - PutFollowRequest.MAX_READ_REQUEST_SIZE, - ObjectParser.ValueType.STRING - ); - PARSER.declareInt(Pattern::setMaxOutstandingReadRequests, FollowConfig.MAX_OUTSTANDING_READ_REQUESTS); - PARSER.declareInt(Pattern::setMaxWriteRequestOperationCount, FollowConfig.MAX_WRITE_REQUEST_OPERATION_COUNT); - PARSER.declareField( - Pattern::setMaxWriteRequestSize, - (p, c) -> ByteSizeValue.parseBytesSizeValue(p.text(), FollowConfig.MAX_WRITE_REQUEST_SIZE.getPreferredName()), - PutFollowRequest.MAX_WRITE_REQUEST_SIZE, - ObjectParser.ValueType.STRING - ); - PARSER.declareInt(Pattern::setMaxOutstandingWriteRequests, FollowConfig.MAX_OUTSTANDING_WRITE_REQUESTS); - PARSER.declareInt(Pattern::setMaxWriteBufferCount, FollowConfig.MAX_WRITE_BUFFER_COUNT); - PARSER.declareField( - Pattern::setMaxWriteBufferSize, - (p, c) -> ByteSizeValue.parseBytesSizeValue(p.text(), FollowConfig.MAX_WRITE_BUFFER_SIZE.getPreferredName()), - PutFollowRequest.MAX_WRITE_BUFFER_SIZE, - ObjectParser.ValueType.STRING - ); - PARSER.declareField( - Pattern::setMaxRetryDelay, - (p, c) -> TimeValue.parseTimeValue(p.text(), FollowConfig.MAX_RETRY_DELAY_FIELD.getPreferredName()), - PutFollowRequest.MAX_RETRY_DELAY_FIELD, - ObjectParser.ValueType.STRING - ); - PARSER.declareField( - Pattern::setReadPollTimeout, - (p, c) -> TimeValue.parseTimeValue(p.text(), FollowConfig.READ_POLL_TIMEOUT.getPreferredName()), - PutFollowRequest.READ_POLL_TIMEOUT, - ObjectParser.ValueType.STRING - ); - } - - private final String remoteCluster; - private final List leaderIndexPatterns; - private final List leaderIndexExclusionPatterns; - private final String followIndexNamePattern; - - Pattern( - String remoteCluster, - List leaderIndexPatterns, - List leaderIndexExclusionPatterns, - String followIndexNamePattern - ) { - this.remoteCluster = remoteCluster; - this.leaderIndexPatterns = leaderIndexPatterns; - this.leaderIndexExclusionPatterns = leaderIndexExclusionPatterns; - this.followIndexNamePattern = followIndexNamePattern; - } - - public String getRemoteCluster() { - return remoteCluster; - } - - public List getLeaderIndexPatterns() { - return leaderIndexPatterns; - } - - public List getLeaderIndexExclusionPatterns() { - return leaderIndexExclusionPatterns; - } - - public String getFollowIndexNamePattern() { - return followIndexNamePattern; - } - - @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; - Pattern pattern = (Pattern) o; - return Objects.equals(remoteCluster, pattern.remoteCluster) - && Objects.equals(leaderIndexPatterns, pattern.leaderIndexPatterns) - && Objects.equals(leaderIndexExclusionPatterns, pattern.leaderIndexExclusionPatterns) - && Objects.equals(followIndexNamePattern, pattern.followIndexNamePattern); - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), remoteCluster, leaderIndexPatterns, leaderIndexExclusionPatterns, followIndexNamePattern); - } - } - -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/IndicesFollowStats.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/IndicesFollowStats.java deleted file mode 100644 index a5ecb9edb01c1..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/IndicesFollowStats.java +++ /dev/null @@ -1,405 +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.ccr; - -import org.elasticsearch.ElasticsearchException; -import org.elasticsearch.common.util.Maps; -import org.elasticsearch.core.Tuple; -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; - -import java.util.AbstractMap; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.NavigableMap; -import java.util.TreeMap; -import java.util.stream.Collectors; - -public final class IndicesFollowStats { - - static final ParseField INDICES_FIELD = new ParseField("indices"); - static final ParseField INDEX_FIELD = new ParseField("index"); - static final ParseField SHARDS_FIELD = new ParseField("shards"); - - private static final ConstructingObjectParser>, Void> ENTRY_PARSER = - new ConstructingObjectParser<>("entry", true, args -> { - String index = (String) args[0]; - @SuppressWarnings("unchecked") - List shardFollowStats = (List) args[1]; - return new Tuple<>(index, shardFollowStats); - }); - - static { - ENTRY_PARSER.declareString(ConstructingObjectParser.constructorArg(), INDEX_FIELD); - ENTRY_PARSER.declareObjectArray(ConstructingObjectParser.constructorArg(), ShardFollowStats.PARSER, SHARDS_FIELD); - } - - static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>("indices", true, args -> { - @SuppressWarnings("unchecked") - List>> entries = (List>>) args[0]; - Map> shardFollowStats = entries.stream().collect(Collectors.toMap(Tuple::v1, Tuple::v2)); - return new IndicesFollowStats(new TreeMap<>(shardFollowStats)); - }); - - static { - PARSER.declareObjectArray(ConstructingObjectParser.constructorArg(), ENTRY_PARSER, INDICES_FIELD); - } - - private final NavigableMap> shardFollowStats; - - IndicesFollowStats(NavigableMap> shardFollowStats) { - this.shardFollowStats = Collections.unmodifiableNavigableMap(shardFollowStats); - } - - public List getShardFollowStats(String index) { - return shardFollowStats.get(index); - } - - public Map> getShardFollowStats() { - return shardFollowStats; - } - - public static final class ShardFollowStats { - - static final ParseField LEADER_CLUSTER = new ParseField("remote_cluster"); - static final ParseField LEADER_INDEX = new ParseField("leader_index"); - static final ParseField FOLLOWER_INDEX = new ParseField("follower_index"); - static final ParseField SHARD_ID = new ParseField("shard_id"); - static final ParseField LEADER_GLOBAL_CHECKPOINT_FIELD = new ParseField("leader_global_checkpoint"); - static final ParseField LEADER_MAX_SEQ_NO_FIELD = new ParseField("leader_max_seq_no"); - static final ParseField FOLLOWER_GLOBAL_CHECKPOINT_FIELD = new ParseField("follower_global_checkpoint"); - static final ParseField FOLLOWER_MAX_SEQ_NO_FIELD = new ParseField("follower_max_seq_no"); - static final ParseField LAST_REQUESTED_SEQ_NO_FIELD = new ParseField("last_requested_seq_no"); - static final ParseField OUTSTANDING_READ_REQUESTS = new ParseField("outstanding_read_requests"); - static final ParseField OUTSTANDING_WRITE_REQUESTS = new ParseField("outstanding_write_requests"); - static final ParseField WRITE_BUFFER_OPERATION_COUNT_FIELD = new ParseField("write_buffer_operation_count"); - static final ParseField WRITE_BUFFER_SIZE_IN_BYTES_FIELD = new ParseField("write_buffer_size_in_bytes"); - static final ParseField FOLLOWER_MAPPING_VERSION_FIELD = new ParseField("follower_mapping_version"); - static final ParseField FOLLOWER_SETTINGS_VERSION_FIELD = new ParseField("follower_settings_version"); - static final ParseField FOLLOWER_ALIASES_VERSION_FIELD = new ParseField("follower_aliases_version"); - static final ParseField TOTAL_READ_TIME_MILLIS_FIELD = new ParseField("total_read_time_millis"); - static final ParseField TOTAL_READ_REMOTE_EXEC_TIME_MILLIS_FIELD = new ParseField("total_read_remote_exec_time_millis"); - static final ParseField SUCCESSFUL_READ_REQUESTS_FIELD = new ParseField("successful_read_requests"); - static final ParseField FAILED_READ_REQUESTS_FIELD = new ParseField("failed_read_requests"); - static final ParseField OPERATIONS_READ_FIELD = new ParseField("operations_read"); - static final ParseField BYTES_READ = new ParseField("bytes_read"); - static final ParseField TOTAL_WRITE_TIME_MILLIS_FIELD = new ParseField("total_write_time_millis"); - static final ParseField SUCCESSFUL_WRITE_REQUESTS_FIELD = new ParseField("successful_write_requests"); - static final ParseField FAILED_WRITE_REQUEST_FIELD = new ParseField("failed_write_requests"); - static final ParseField OPERATIONS_WRITTEN = new ParseField("operations_written"); - static final ParseField READ_EXCEPTIONS = new ParseField("read_exceptions"); - static final ParseField TIME_SINCE_LAST_READ_MILLIS_FIELD = new ParseField("time_since_last_read_millis"); - static final ParseField FATAL_EXCEPTION = new ParseField("fatal_exception"); - - @SuppressWarnings("unchecked") - static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "shard-follow-stats", - true, - args -> new ShardFollowStats( - (String) args[0], - (String) args[1], - (String) args[2], - (int) args[3], - (long) args[4], - (long) args[5], - (long) args[6], - (long) args[7], - (long) args[8], - (int) args[9], - (int) args[10], - (int) args[11], - (long) args[12], - (long) args[13], - (long) args[14], - (long) args[15], - (long) args[16], - (long) args[17], - (long) args[18], - (long) args[19], - (long) args[20], - (long) args[21], - (long) args[22], - (long) args[23], - (long) args[24], - (long) args[25], - (long) args[26], - ((List>>) args[27]).stream() - .collect(Maps.toUnmodifiableSortedMap(Map.Entry::getKey, Map.Entry::getValue)), - (ElasticsearchException) args[28] - ) - ); - - static final ConstructingObjectParser>, Void> READ_EXCEPTIONS_ENTRY_PARSER = - new ConstructingObjectParser<>( - "shard-follow-stats-read-exceptions-entry", - true, - args -> new AbstractMap.SimpleEntry<>((long) args[0], Tuple.tuple((Integer) args[1], (ElasticsearchException) args[2])) - ); - - static { - PARSER.declareString(ConstructingObjectParser.constructorArg(), LEADER_CLUSTER); - PARSER.declareString(ConstructingObjectParser.constructorArg(), LEADER_INDEX); - PARSER.declareString(ConstructingObjectParser.constructorArg(), FOLLOWER_INDEX); - PARSER.declareInt(ConstructingObjectParser.constructorArg(), SHARD_ID); - PARSER.declareLong(ConstructingObjectParser.constructorArg(), LEADER_GLOBAL_CHECKPOINT_FIELD); - PARSER.declareLong(ConstructingObjectParser.constructorArg(), LEADER_MAX_SEQ_NO_FIELD); - PARSER.declareLong(ConstructingObjectParser.constructorArg(), FOLLOWER_GLOBAL_CHECKPOINT_FIELD); - PARSER.declareLong(ConstructingObjectParser.constructorArg(), FOLLOWER_MAX_SEQ_NO_FIELD); - PARSER.declareLong(ConstructingObjectParser.constructorArg(), LAST_REQUESTED_SEQ_NO_FIELD); - PARSER.declareInt(ConstructingObjectParser.constructorArg(), OUTSTANDING_READ_REQUESTS); - PARSER.declareInt(ConstructingObjectParser.constructorArg(), OUTSTANDING_WRITE_REQUESTS); - PARSER.declareInt(ConstructingObjectParser.constructorArg(), WRITE_BUFFER_OPERATION_COUNT_FIELD); - PARSER.declareLong(ConstructingObjectParser.constructorArg(), WRITE_BUFFER_SIZE_IN_BYTES_FIELD); - PARSER.declareLong(ConstructingObjectParser.constructorArg(), FOLLOWER_MAPPING_VERSION_FIELD); - PARSER.declareLong(ConstructingObjectParser.constructorArg(), FOLLOWER_SETTINGS_VERSION_FIELD); - PARSER.declareLong(ConstructingObjectParser.constructorArg(), FOLLOWER_ALIASES_VERSION_FIELD); - PARSER.declareLong(ConstructingObjectParser.constructorArg(), TOTAL_READ_TIME_MILLIS_FIELD); - PARSER.declareLong(ConstructingObjectParser.constructorArg(), TOTAL_READ_REMOTE_EXEC_TIME_MILLIS_FIELD); - PARSER.declareLong(ConstructingObjectParser.constructorArg(), SUCCESSFUL_READ_REQUESTS_FIELD); - PARSER.declareLong(ConstructingObjectParser.constructorArg(), FAILED_READ_REQUESTS_FIELD); - PARSER.declareLong(ConstructingObjectParser.constructorArg(), OPERATIONS_READ_FIELD); - PARSER.declareLong(ConstructingObjectParser.constructorArg(), BYTES_READ); - PARSER.declareLong(ConstructingObjectParser.constructorArg(), TOTAL_WRITE_TIME_MILLIS_FIELD); - PARSER.declareLong(ConstructingObjectParser.constructorArg(), SUCCESSFUL_WRITE_REQUESTS_FIELD); - PARSER.declareLong(ConstructingObjectParser.constructorArg(), FAILED_WRITE_REQUEST_FIELD); - PARSER.declareLong(ConstructingObjectParser.constructorArg(), OPERATIONS_WRITTEN); - PARSER.declareLong(ConstructingObjectParser.constructorArg(), TIME_SINCE_LAST_READ_MILLIS_FIELD); - PARSER.declareObjectArray(ConstructingObjectParser.constructorArg(), READ_EXCEPTIONS_ENTRY_PARSER, READ_EXCEPTIONS); - PARSER.declareObject( - ConstructingObjectParser.optionalConstructorArg(), - (p, c) -> ElasticsearchException.fromXContent(p), - FATAL_EXCEPTION - ); - } - - static final ParseField READ_EXCEPTIONS_ENTRY_FROM_SEQ_NO = new ParseField("from_seq_no"); - static final ParseField READ_EXCEPTIONS_RETRIES = new ParseField("retries"); - static final ParseField READ_EXCEPTIONS_ENTRY_EXCEPTION = new ParseField("exception"); - - static { - READ_EXCEPTIONS_ENTRY_PARSER.declareLong(ConstructingObjectParser.constructorArg(), READ_EXCEPTIONS_ENTRY_FROM_SEQ_NO); - READ_EXCEPTIONS_ENTRY_PARSER.declareInt(ConstructingObjectParser.constructorArg(), READ_EXCEPTIONS_RETRIES); - READ_EXCEPTIONS_ENTRY_PARSER.declareObject( - ConstructingObjectParser.constructorArg(), - (p, c) -> ElasticsearchException.fromXContent(p), - READ_EXCEPTIONS_ENTRY_EXCEPTION - ); - } - - private final String remoteCluster; - private final String leaderIndex; - private final String followerIndex; - private final int shardId; - private final long leaderGlobalCheckpoint; - private final long leaderMaxSeqNo; - private final long followerGlobalCheckpoint; - private final long followerMaxSeqNo; - private final long lastRequestedSeqNo; - private final int outstandingReadRequests; - private final int outstandingWriteRequests; - private final int writeBufferOperationCount; - private final long writeBufferSizeInBytes; - private final long followerMappingVersion; - private final long followerSettingsVersion; - private final long followerAliasesVersion; - private final long totalReadTimeMillis; - private final long totalReadRemoteExecTimeMillis; - private final long successfulReadRequests; - private final long failedReadRequests; - private final long operationsReads; - private final long bytesRead; - private final long totalWriteTimeMillis; - private final long successfulWriteRequests; - private final long failedWriteRequests; - private final long operationWritten; - private final long timeSinceLastReadMillis; - private final NavigableMap> readExceptions; - private final ElasticsearchException fatalException; - - ShardFollowStats( - String remoteCluster, - String leaderIndex, - String followerIndex, - int shardId, - long leaderGlobalCheckpoint, - long leaderMaxSeqNo, - long followerGlobalCheckpoint, - long followerMaxSeqNo, - long lastRequestedSeqNo, - int outstandingReadRequests, - int outstandingWriteRequests, - int writeBufferOperationCount, - long writeBufferSizeInBytes, - long followerMappingVersion, - long followerSettingsVersion, - long followerAliasesVersion, - long totalReadTimeMillis, - long totalReadRemoteExecTimeMillis, - long successfulReadRequests, - long failedReadRequests, - long operationsReads, - long bytesRead, - long totalWriteTimeMillis, - long successfulWriteRequests, - long failedWriteRequests, - long operationWritten, - long timeSinceLastReadMillis, - NavigableMap> readExceptions, - ElasticsearchException fatalException - ) { - this.remoteCluster = remoteCluster; - this.leaderIndex = leaderIndex; - this.followerIndex = followerIndex; - this.shardId = shardId; - this.leaderGlobalCheckpoint = leaderGlobalCheckpoint; - this.leaderMaxSeqNo = leaderMaxSeqNo; - this.followerGlobalCheckpoint = followerGlobalCheckpoint; - this.followerMaxSeqNo = followerMaxSeqNo; - this.lastRequestedSeqNo = lastRequestedSeqNo; - this.outstandingReadRequests = outstandingReadRequests; - this.outstandingWriteRequests = outstandingWriteRequests; - this.writeBufferOperationCount = writeBufferOperationCount; - this.writeBufferSizeInBytes = writeBufferSizeInBytes; - this.followerMappingVersion = followerMappingVersion; - this.followerSettingsVersion = followerSettingsVersion; - this.followerAliasesVersion = followerAliasesVersion; - this.totalReadTimeMillis = totalReadTimeMillis; - this.totalReadRemoteExecTimeMillis = totalReadRemoteExecTimeMillis; - this.successfulReadRequests = successfulReadRequests; - this.failedReadRequests = failedReadRequests; - this.operationsReads = operationsReads; - this.bytesRead = bytesRead; - this.totalWriteTimeMillis = totalWriteTimeMillis; - this.successfulWriteRequests = successfulWriteRequests; - this.failedWriteRequests = failedWriteRequests; - this.operationWritten = operationWritten; - this.timeSinceLastReadMillis = timeSinceLastReadMillis; - this.readExceptions = readExceptions; - this.fatalException = fatalException; - } - - public String getRemoteCluster() { - return remoteCluster; - } - - public String getLeaderIndex() { - return leaderIndex; - } - - public String getFollowerIndex() { - return followerIndex; - } - - public int getShardId() { - return shardId; - } - - public long getLeaderGlobalCheckpoint() { - return leaderGlobalCheckpoint; - } - - public long getLeaderMaxSeqNo() { - return leaderMaxSeqNo; - } - - public long getFollowerGlobalCheckpoint() { - return followerGlobalCheckpoint; - } - - public long getFollowerMaxSeqNo() { - return followerMaxSeqNo; - } - - public long getLastRequestedSeqNo() { - return lastRequestedSeqNo; - } - - public int getOutstandingReadRequests() { - return outstandingReadRequests; - } - - public int getOutstandingWriteRequests() { - return outstandingWriteRequests; - } - - public int getWriteBufferOperationCount() { - return writeBufferOperationCount; - } - - public long getWriteBufferSizeInBytes() { - return writeBufferSizeInBytes; - } - - public long getFollowerMappingVersion() { - return followerMappingVersion; - } - - public long getFollowerSettingsVersion() { - return followerSettingsVersion; - } - - public long getFollowerAliasesVersion() { - return followerAliasesVersion; - } - - public long getTotalReadTimeMillis() { - return totalReadTimeMillis; - } - - public long getTotalReadRemoteExecTimeMillis() { - return totalReadRemoteExecTimeMillis; - } - - public long getSuccessfulReadRequests() { - return successfulReadRequests; - } - - public long getFailedReadRequests() { - return failedReadRequests; - } - - public long getOperationsReads() { - return operationsReads; - } - - public long getBytesRead() { - return bytesRead; - } - - public long getTotalWriteTimeMillis() { - return totalWriteTimeMillis; - } - - public long getSuccessfulWriteRequests() { - return successfulWriteRequests; - } - - public long getFailedWriteRequests() { - return failedWriteRequests; - } - - public long getOperationWritten() { - return operationWritten; - } - - public long getTimeSinceLastReadMillis() { - return timeSinceLastReadMillis; - } - - public NavigableMap> getReadExceptions() { - return readExceptions; - } - - public ElasticsearchException getFatalException() { - return fatalException; - } - } - -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/PauseAutoFollowPatternRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/PauseAutoFollowPatternRequest.java deleted file mode 100644 index 2ff6c178c8866..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/PauseAutoFollowPatternRequest.java +++ /dev/null @@ -1,34 +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.ccr; - -import org.elasticsearch.client.Validatable; - -import java.util.Objects; - -/** - * Request class for pause auto follow pattern api. - */ -public final class PauseAutoFollowPatternRequest implements Validatable { - - private final String name; - - /** - * Pause auto follow pattern with the specified name - * - * @param name The name of the auto follow pattern to pause - */ - public PauseAutoFollowPatternRequest(String name) { - this.name = Objects.requireNonNull(name); - } - - public String getName() { - return name; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/PauseFollowRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/PauseFollowRequest.java deleted file mode 100644 index 9fea81959557f..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/PauseFollowRequest.java +++ /dev/null @@ -1,26 +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.ccr; - -import org.elasticsearch.client.Validatable; - -import java.util.Objects; - -public final class PauseFollowRequest implements Validatable { - - private final String followerIndex; - - public PauseFollowRequest(String followerIndex) { - this.followerIndex = Objects.requireNonNull(followerIndex); - } - - public String getFollowerIndex() { - return followerIndex; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/PutAutoFollowPatternRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/PutAutoFollowPatternRequest.java deleted file mode 100644 index 9918d7bb84231..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/PutAutoFollowPatternRequest.java +++ /dev/null @@ -1,113 +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.ccr; - -import org.elasticsearch.client.Validatable; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.ToXContentObject; -import org.elasticsearch.xcontent.XContentBuilder; - -import java.io.IOException; -import java.util.Collections; -import java.util.List; -import java.util.Objects; - -public final class PutAutoFollowPatternRequest extends FollowConfig implements Validatable, ToXContentObject { - - static final ParseField LEADER_PATTERNS_FIELD = new ParseField("leader_index_patterns"); - static final ParseField LEADER_EXCLUSION_PATTERNS_FIELD = new ParseField("leader_index_exclusion_patterns"); - static final ParseField FOLLOW_PATTERN_FIELD = new ParseField("follow_index_pattern"); - - private final String name; - private final String remoteCluster; - private final List leaderIndexPatterns; - private final List leaderIndexExclusionPatterns; - private String followIndexNamePattern; - - public PutAutoFollowPatternRequest(String name, String remoteCluster, List leaderIndexPatterns) { - this(name, remoteCluster, leaderIndexPatterns, Collections.emptyList()); - } - - public PutAutoFollowPatternRequest( - String name, - String remoteCluster, - List leaderIndexPatterns, - List leaderIndexExclusionPatterns - ) { - this.name = Objects.requireNonNull(name); - this.remoteCluster = Objects.requireNonNull(remoteCluster); - this.leaderIndexPatterns = Objects.requireNonNull(leaderIndexPatterns); - this.leaderIndexExclusionPatterns = Objects.requireNonNull(leaderIndexExclusionPatterns); - } - - public String getName() { - return name; - } - - public String getRemoteCluster() { - return remoteCluster; - } - - public List getLeaderIndexPatterns() { - return leaderIndexPatterns; - } - - public List getLeaderIndexExclusionPatterns() { - return leaderIndexExclusionPatterns; - } - - public String getFollowIndexNamePattern() { - return followIndexNamePattern; - } - - public void setFollowIndexNamePattern(String followIndexNamePattern) { - this.followIndexNamePattern = followIndexNamePattern; - } - - @Override - public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(); - builder.field(PutFollowRequest.REMOTE_CLUSTER_FIELD.getPreferredName(), remoteCluster); - builder.stringListField(LEADER_PATTERNS_FIELD.getPreferredName(), leaderIndexPatterns); - if (leaderIndexExclusionPatterns.isEmpty() == false) { - builder.stringListField(LEADER_EXCLUSION_PATTERNS_FIELD.getPreferredName(), leaderIndexExclusionPatterns); - } - if (followIndexNamePattern != null) { - builder.field(FOLLOW_PATTERN_FIELD.getPreferredName(), followIndexNamePattern); - } - toXContentFragment(builder, params); - builder.endObject(); - return builder; - } - - @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; - PutAutoFollowPatternRequest that = (PutAutoFollowPatternRequest) o; - return Objects.equals(name, that.name) - && Objects.equals(remoteCluster, that.remoteCluster) - && Objects.equals(leaderIndexPatterns, that.leaderIndexPatterns) - && Objects.equals(leaderIndexExclusionPatterns, that.leaderIndexExclusionPatterns) - && Objects.equals(followIndexNamePattern, that.followIndexNamePattern); - } - - @Override - public int hashCode() { - return Objects.hash( - super.hashCode(), - name, - remoteCluster, - leaderIndexPatterns, - leaderIndexExclusionPatterns, - followIndexNamePattern - ); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/PutFollowRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/PutFollowRequest.java deleted file mode 100644 index 26b5225fab630..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/PutFollowRequest.java +++ /dev/null @@ -1,83 +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.ccr; - -import org.elasticsearch.action.support.ActiveShardCount; -import org.elasticsearch.client.Validatable; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.ToXContentObject; -import org.elasticsearch.xcontent.XContentBuilder; - -import java.io.IOException; -import java.util.Objects; - -public final class PutFollowRequest extends FollowConfig implements Validatable, ToXContentObject { - - static final ParseField REMOTE_CLUSTER_FIELD = new ParseField("remote_cluster"); - static final ParseField LEADER_INDEX_FIELD = new ParseField("leader_index"); - - private final String remoteCluster; - private final String leaderIndex; - private final String followerIndex; - private final ActiveShardCount waitForActiveShards; - - public PutFollowRequest(String remoteCluster, String leaderIndex, String followerIndex) { - this(remoteCluster, leaderIndex, followerIndex, ActiveShardCount.NONE); - } - - public PutFollowRequest(String remoteCluster, String leaderIndex, String followerIndex, ActiveShardCount waitForActiveShards) { - this.remoteCluster = Objects.requireNonNull(remoteCluster, "remoteCluster"); - this.leaderIndex = Objects.requireNonNull(leaderIndex, "leaderIndex"); - this.followerIndex = Objects.requireNonNull(followerIndex, "followerIndex"); - this.waitForActiveShards = waitForActiveShards; - } - - @Override - public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(); - builder.field(REMOTE_CLUSTER_FIELD.getPreferredName(), remoteCluster); - builder.field(LEADER_INDEX_FIELD.getPreferredName(), leaderIndex); - toXContentFragment(builder, params); - builder.endObject(); - return builder; - } - - public String getRemoteCluster() { - return remoteCluster; - } - - public String getLeaderIndex() { - return leaderIndex; - } - - public String getFollowerIndex() { - return followerIndex; - } - - public ActiveShardCount waitForActiveShards() { - return waitForActiveShards; - } - - @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; - PutFollowRequest that = (PutFollowRequest) o; - return Objects.equals(waitForActiveShards, that.waitForActiveShards) - && Objects.equals(remoteCluster, that.remoteCluster) - && Objects.equals(leaderIndex, that.leaderIndex) - && Objects.equals(followerIndex, that.followerIndex); - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), remoteCluster, leaderIndex, followerIndex, waitForActiveShards); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/PutFollowResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/PutFollowResponse.java deleted file mode 100644 index 4f9a016f7a507..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/PutFollowResponse.java +++ /dev/null @@ -1,76 +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.ccr; - -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.Objects; - -public final class PutFollowResponse { - - static final ParseField FOLLOW_INDEX_CREATED = new ParseField("follow_index_created"); - static final ParseField FOLLOW_INDEX_SHARDS_ACKED = new ParseField("follow_index_shards_acked"); - static final ParseField INDEX_FOLLOWING_STARTED = new ParseField("index_following_started"); - - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "put_follow_response", - true, - args -> new PutFollowResponse((boolean) args[0], (boolean) args[1], (boolean) args[2]) - ); - - static { - PARSER.declareBoolean(ConstructingObjectParser.constructorArg(), FOLLOW_INDEX_CREATED); - PARSER.declareBoolean(ConstructingObjectParser.constructorArg(), FOLLOW_INDEX_SHARDS_ACKED); - PARSER.declareBoolean(ConstructingObjectParser.constructorArg(), INDEX_FOLLOWING_STARTED); - } - - public static PutFollowResponse fromXContent(final XContentParser parser) throws IOException { - return PARSER.parse(parser, null); - } - - private final boolean followIndexCreated; - private final boolean followIndexShardsAcked; - private final boolean indexFollowingStarted; - - public PutFollowResponse(boolean followIndexCreated, boolean followIndexShardsAcked, boolean indexFollowingStarted) { - this.followIndexCreated = followIndexCreated; - this.followIndexShardsAcked = followIndexShardsAcked; - this.indexFollowingStarted = indexFollowingStarted; - } - - public boolean isFollowIndexCreated() { - return followIndexCreated; - } - - public boolean isFollowIndexShardsAcked() { - return followIndexShardsAcked; - } - - public boolean isIndexFollowingStarted() { - return indexFollowingStarted; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - PutFollowResponse that = (PutFollowResponse) o; - return followIndexCreated == that.followIndexCreated - && followIndexShardsAcked == that.followIndexShardsAcked - && indexFollowingStarted == that.indexFollowingStarted; - } - - @Override - public int hashCode() { - return Objects.hash(followIndexCreated, followIndexShardsAcked, indexFollowingStarted); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/ResumeAutoFollowPatternRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/ResumeAutoFollowPatternRequest.java deleted file mode 100644 index de7ef9eb73f85..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/ResumeAutoFollowPatternRequest.java +++ /dev/null @@ -1,34 +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.ccr; - -import org.elasticsearch.client.Validatable; - -import java.util.Objects; - -/** - * Request class for resume auto follow pattern api. - */ -public final class ResumeAutoFollowPatternRequest implements Validatable { - - private final String name; - - /** - * Resume auto follow pattern with the specified name - * - * @param name The name of the auto follow pattern to resume - */ - public ResumeAutoFollowPatternRequest(String name) { - this.name = Objects.requireNonNull(name); - } - - public String getName() { - return name; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/ResumeFollowRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/ResumeFollowRequest.java deleted file mode 100644 index 1af40af5d59ca..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/ResumeFollowRequest.java +++ /dev/null @@ -1,51 +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.ccr; - -import org.elasticsearch.client.Validatable; -import org.elasticsearch.xcontent.ToXContentObject; -import org.elasticsearch.xcontent.XContentBuilder; - -import java.io.IOException; -import java.util.Objects; - -public final class ResumeFollowRequest extends FollowConfig implements Validatable, ToXContentObject { - - private final String followerIndex; - - public ResumeFollowRequest(String followerIndex) { - this.followerIndex = Objects.requireNonNull(followerIndex, "followerIndex"); - } - - @Override - public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(); - toXContentFragment(builder, params); - builder.endObject(); - return builder; - } - - public String getFollowerIndex() { - return followerIndex; - } - - @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; - ResumeFollowRequest that = (ResumeFollowRequest) o; - return Objects.equals(followerIndex, that.followerIndex); - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), followerIndex); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/UnfollowRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/UnfollowRequest.java deleted file mode 100644 index 794e01b537d3d..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/UnfollowRequest.java +++ /dev/null @@ -1,26 +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.ccr; - -import org.elasticsearch.client.Validatable; - -import java.util.Objects; - -public final class UnfollowRequest implements Validatable { - - private final String followerIndex; - - public UnfollowRequest(String followerIndex) { - this.followerIndex = Objects.requireNonNull(followerIndex); - } - - public String getFollowerIndex() { - return followerIndex; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/enrich/DeletePolicyRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/enrich/DeletePolicyRequest.java deleted file mode 100644 index 9cc42319b5524..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/enrich/DeletePolicyRequest.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.enrich; - -import org.elasticsearch.client.Validatable; -import org.elasticsearch.common.Strings; - -public final class DeletePolicyRequest implements Validatable { - - private final String name; - - public DeletePolicyRequest(String name) { - if (Strings.hasLength(name) == false) { - throw new IllegalArgumentException("name must be a non-null and non-empty string"); - } - this.name = name; - } - - public String getName() { - return name; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/enrich/ExecutePolicyRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/enrich/ExecutePolicyRequest.java deleted file mode 100644 index 061c94b07913e..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/enrich/ExecutePolicyRequest.java +++ /dev/null @@ -1,32 +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.enrich; - -import org.elasticsearch.client.Validatable; - -public final class ExecutePolicyRequest implements Validatable { - - private final String name; - private Boolean waitForCompletion; - - public ExecutePolicyRequest(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public Boolean getWaitForCompletion() { - return waitForCompletion; - } - - public void setWaitForCompletion(boolean waitForCompletion) { - this.waitForCompletion = waitForCompletion; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/enrich/ExecutePolicyResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/enrich/ExecutePolicyResponse.java deleted file mode 100644 index 32e1d037c9bad..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/enrich/ExecutePolicyResponse.java +++ /dev/null @@ -1,74 +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.enrich; - -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentParser; - -public final class ExecutePolicyResponse { - - private static final ParseField TASK_FIELD = new ParseField("task"); - private static final ParseField STATUS_FIELD = new ParseField("status"); - - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "execute_policy_response", - true, - args -> new ExecutePolicyResponse((String) args[0], (ExecutionStatus) args[1]) - ); - - static { - PARSER.declareString(ConstructingObjectParser.optionalConstructorArg(), TASK_FIELD); - PARSER.declareObject(ConstructingObjectParser.optionalConstructorArg(), ExecutionStatus.PARSER, STATUS_FIELD); - } - - public static ExecutePolicyResponse fromXContent(XContentParser parser) { - return PARSER.apply(parser, null); - } - - private final String taskId; - private final ExecutionStatus executionStatus; - - ExecutePolicyResponse(String taskId, ExecutionStatus executionStatus) { - this.taskId = taskId; - this.executionStatus = executionStatus; - } - - public String getTaskId() { - return taskId; - } - - public ExecutionStatus getExecutionStatus() { - return executionStatus; - } - - public static final class ExecutionStatus { - - private static final ParseField PHASE_FIELD = new ParseField("phase"); - - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "execution_status", - true, - args -> new ExecutionStatus((String) args[0]) - ); - - static { - PARSER.declareString(ConstructingObjectParser.constructorArg(), PHASE_FIELD); - } - - private final String phase; - - ExecutionStatus(String phase) { - this.phase = phase; - } - - public String getPhase() { - return phase; - } - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/enrich/GetPolicyRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/enrich/GetPolicyRequest.java deleted file mode 100644 index 34464c8820fbf..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/enrich/GetPolicyRequest.java +++ /dev/null @@ -1,33 +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.enrich; - -import org.elasticsearch.client.Validatable; - -import java.util.List; - -public final class GetPolicyRequest implements Validatable { - - private final List names; - - public GetPolicyRequest() { - this(List.of()); - } - - public GetPolicyRequest(String... names) { - this(List.of(names)); - } - - public GetPolicyRequest(List names) { - this.names = names; - } - - public List getNames() { - return names; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/enrich/GetPolicyResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/enrich/GetPolicyResponse.java deleted file mode 100644 index b8d823d33a259..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/enrich/GetPolicyResponse.java +++ /dev/null @@ -1,55 +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.enrich; - -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.List; - -public final class GetPolicyResponse { - - @SuppressWarnings("unchecked") - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "get_policy_response", - true, - args -> new GetPolicyResponse((List) args[0]) - ); - - @SuppressWarnings("unchecked") - private static final ConstructingObjectParser CONFIG_PARSER = new ConstructingObjectParser<>( - "config", - true, - args -> (NamedPolicy) args[0] - ); - - static { - PARSER.declareObjectArray(ConstructingObjectParser.constructorArg(), CONFIG_PARSER::apply, new ParseField("policies")); - CONFIG_PARSER.declareObject( - ConstructingObjectParser.constructorArg(), - (p, c) -> NamedPolicy.fromXContent(p), - new ParseField("config") - ); - } - - private final List policies; - - public static GetPolicyResponse fromXContent(XContentParser parser) throws IOException { - return PARSER.apply(parser, null); - } - - public GetPolicyResponse(List policies) { - this.policies = policies; - } - - public List getPolicies() { - return policies; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/enrich/NamedPolicy.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/enrich/NamedPolicy.java deleted file mode 100644 index d83975fbd5a8d..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/enrich/NamedPolicy.java +++ /dev/null @@ -1,118 +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.enrich; - -import org.elasticsearch.common.ParsingException; -import org.elasticsearch.common.bytes.BytesReference; -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentBuilder; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.List; - -public final class NamedPolicy { - - static final ParseField NAME_FIELD = new ParseField("name"); - static final ParseField QUERY_FIELD = new ParseField("query"); - static final ParseField INDICES_FIELD = new ParseField("indices"); - static final ParseField MATCH_FIELD_FIELD = new ParseField("match_field"); - static final ParseField ENRICH_FIELDS_FIELD = new ParseField("enrich_fields"); - - @SuppressWarnings("unchecked") - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "policy", - true, - (args, policyType) -> new NamedPolicy( - policyType, - (String) args[0], - (BytesReference) args[1], - (List) args[2], - (String) args[3], - (List) args[4] - ) - ); - - static { - declareParserOptions(PARSER); - } - - private static void declareParserOptions(ConstructingObjectParser parser) { - parser.declareString(ConstructingObjectParser.constructorArg(), NAME_FIELD); - parser.declareObject(ConstructingObjectParser.optionalConstructorArg(), (p, c) -> { - XContentBuilder builder = XContentBuilder.builder(p.contentType().xContent()); - builder.copyCurrentStructure(p); - return BytesReference.bytes(builder); - }, QUERY_FIELD); - parser.declareStringArray(ConstructingObjectParser.constructorArg(), INDICES_FIELD); - parser.declareString(ConstructingObjectParser.constructorArg(), MATCH_FIELD_FIELD); - parser.declareStringArray(ConstructingObjectParser.constructorArg(), ENRICH_FIELDS_FIELD); - } - - public static NamedPolicy fromXContent(XContentParser parser) throws IOException { - XContentParser.Token token = parser.currentToken(); - if (token != XContentParser.Token.START_OBJECT) { - token = parser.nextToken(); - } - if (token != XContentParser.Token.START_OBJECT) { - throw new ParsingException(parser.getTokenLocation(), "unexpected token"); - } - token = parser.nextToken(); - if (token != XContentParser.Token.FIELD_NAME) { - throw new ParsingException(parser.getTokenLocation(), "unexpected token"); - } - String policyType = parser.currentName(); - NamedPolicy policy = PARSER.parse(parser, policyType); - token = parser.nextToken(); - if (token != XContentParser.Token.END_OBJECT) { - throw new ParsingException(parser.getTokenLocation(), "unexpected token"); - } - return policy; - } - - private final String type; - private final String name; - private final BytesReference query; - private final List indices; - private final String matchField; - private final List enrichFields; - - NamedPolicy(String type, String name, BytesReference query, List indices, String matchField, List enrichFields) { - this.type = type; - this.name = name; - this.query = query; - this.indices = indices; - this.matchField = matchField; - this.enrichFields = enrichFields; - } - - public String getType() { - return type; - } - - public String getName() { - return name; - } - - public BytesReference getQuery() { - return query; - } - - public List getIndices() { - return indices; - } - - public String getMatchField() { - return matchField; - } - - public List getEnrichFields() { - return enrichFields; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/enrich/PutPolicyRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/enrich/PutPolicyRequest.java deleted file mode 100644 index b9875608ef931..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/enrich/PutPolicyRequest.java +++ /dev/null @@ -1,140 +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.enrich; - -import org.elasticsearch.client.Validatable; -import org.elasticsearch.common.Strings; -import org.elasticsearch.common.bytes.BytesReference; -import org.elasticsearch.common.xcontent.XContentHelper; -import org.elasticsearch.index.query.QueryBuilder; -import org.elasticsearch.xcontent.ToXContentObject; -import org.elasticsearch.xcontent.XContentBuilder; -import org.elasticsearch.xcontent.XContentType; -import org.elasticsearch.xcontent.json.JsonXContent; - -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -public final class PutPolicyRequest implements Validatable, ToXContentObject { - - private final String name; - private final String type; - private BytesReference query; - private final List indices; - private final String matchField; - private final List enrichFields; - - public PutPolicyRequest(String name, String type, List indices, String matchField, List enrichFields) { - if (Strings.hasLength(name) == false) { - throw new IllegalArgumentException("name must be a non-null and non-empty string"); - } - if (Strings.hasLength(type) == false) { - throw new IllegalArgumentException("type must be a non-null and non-empty string"); - } - if (indices == null || indices.isEmpty()) { - throw new IllegalArgumentException("indices must be specified"); - } - if (Strings.hasLength(matchField) == false) { - throw new IllegalArgumentException("matchField must be a non-null and non-empty string"); - } - if (enrichFields == null || enrichFields.isEmpty()) { - throw new IllegalArgumentException("enrichFields must be specified"); - } - - this.name = name; - this.type = type; - this.indices = indices; - this.matchField = matchField; - this.enrichFields = enrichFields; - } - - public String getName() { - return name; - } - - public String getType() { - return type; - } - - public BytesReference getQuery() { - return query; - } - - // package private for testing only - void setQuery(BytesReference query) { - assert query == null || XContentHelper.xContentType(query).canonical() == XContentType.JSON - : "Only accepts JSON encoded query but received [" + Strings.toString(query) + "]"; - this.query = query; - } - - public void setQuery(QueryBuilder query) throws IOException { - setQuery(xContentToBytes(query)); - } - - public List getIndices() { - return indices; - } - - public String getMatchField() { - return matchField; - } - - public List getEnrichFields() { - return enrichFields; - } - - @Override - public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(); - { - builder.startObject(type); - { - builder.stringListField(NamedPolicy.INDICES_FIELD.getPreferredName(), indices); - if (query != null) { - builder.field(NamedPolicy.QUERY_FIELD.getPreferredName(), asMap(query, XContentType.JSON)); - } - builder.field(NamedPolicy.MATCH_FIELD_FIELD.getPreferredName(), matchField); - builder.stringListField(NamedPolicy.ENRICH_FIELDS_FIELD.getPreferredName(), enrichFields); - } - builder.endObject(); - } - builder.endObject(); - return builder; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - PutPolicyRequest that = (PutPolicyRequest) o; - return Objects.equals(name, that.name) - && Objects.equals(type, that.type) - && Objects.equals(query, that.query) - && Objects.equals(indices, that.indices) - && Objects.equals(matchField, that.matchField) - && Objects.equals(enrichFields, that.enrichFields); - } - - @Override - public int hashCode() { - return Objects.hash(name, type, query, indices, matchField, enrichFields); - } - - private static BytesReference xContentToBytes(ToXContentObject object) throws IOException { - try (XContentBuilder builder = JsonXContent.contentBuilder()) { - object.toXContent(builder, ToXContentObject.EMPTY_PARAMS); - return BytesReference.bytes(builder); - } - } - - static Map asMap(BytesReference bytesReference, XContentType xContentType) { - return bytesReference == null ? null : XContentHelper.convertToMap(bytesReference, true, xContentType).v2(); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/enrich/StatsRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/enrich/StatsRequest.java deleted file mode 100644 index fbc7a6a782fc7..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/enrich/StatsRequest.java +++ /dev/null @@ -1,12 +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.enrich; - -import org.elasticsearch.client.Validatable; - -public final class StatsRequest implements Validatable {} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/enrich/StatsResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/enrich/StatsResponse.java deleted file mode 100644 index 134b4b0cb16d2..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/enrich/StatsResponse.java +++ /dev/null @@ -1,262 +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.enrich; - -import org.elasticsearch.tasks.TaskInfo; -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentParser; - -import java.util.List; -import java.util.Objects; - -public final class StatsResponse { - - private static final ParseField EXECUTING_POLICIES_FIELD = new ParseField("executing_policies"); - private static final ParseField COORDINATOR_STATS_FIELD = new ParseField("coordinator_stats"); - private static final ParseField CACHE_STATS_FIELD = new ParseField("cache_stats"); - - @SuppressWarnings("unchecked") - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "stats_response", - true, - args -> new StatsResponse((List) args[0], (List) args[1], (List) args[2]) - ); - - static { - PARSER.declareObjectArray(ConstructingObjectParser.constructorArg(), ExecutingPolicy.PARSER::apply, EXECUTING_POLICIES_FIELD); - PARSER.declareObjectArray(ConstructingObjectParser.constructorArg(), CoordinatorStats.PARSER::apply, COORDINATOR_STATS_FIELD); - PARSER.declareObjectArray(ConstructingObjectParser.constructorArg(), CacheStats.PARSER::apply, CACHE_STATS_FIELD); - } - - public static StatsResponse fromXContent(XContentParser parser) { - return PARSER.apply(parser, null); - } - - private final List executingPolicies; - private final List coordinatorStats; - private final List cacheStats; - - public StatsResponse(List executingPolicies, List coordinatorStats, List cacheStats) { - this.executingPolicies = executingPolicies; - this.coordinatorStats = coordinatorStats; - this.cacheStats = cacheStats; - } - - public List getExecutingPolicies() { - return executingPolicies; - } - - public List getCoordinatorStats() { - return coordinatorStats; - } - - public List getCacheStats() { - return cacheStats; - } - - public static final class CoordinatorStats { - - static ParseField NODE_ID_FIELD = new ParseField("node_id"); - static ParseField QUEUE_SIZE_FIELD = new ParseField("queue_size"); - static ParseField REMOTE_REQUESTS_CONCURRENT_FIELD = new ParseField("remote_requests_current"); - static ParseField REMOTE_REQUESTS_TOTAL_FIELD = new ParseField("remote_requests_total"); - static ParseField EXECUTED_SEARCHES_FIELD = new ParseField("executed_searches_total"); - - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "coordinator_stats_item", - true, - args -> new CoordinatorStats((String) args[0], (int) args[1], (int) args[2], (long) args[3], (long) args[4]) - ); - - static { - PARSER.declareString(ConstructingObjectParser.constructorArg(), NODE_ID_FIELD); - PARSER.declareInt(ConstructingObjectParser.constructorArg(), QUEUE_SIZE_FIELD); - PARSER.declareInt(ConstructingObjectParser.constructorArg(), REMOTE_REQUESTS_CONCURRENT_FIELD); - PARSER.declareLong(ConstructingObjectParser.constructorArg(), REMOTE_REQUESTS_TOTAL_FIELD); - PARSER.declareLong(ConstructingObjectParser.constructorArg(), EXECUTED_SEARCHES_FIELD); - } - - private final String nodeId; - private final int queueSize; - private final int remoteRequestsCurrent; - private final long remoteRequestsTotal; - private final long executedSearchesTotal; - - public CoordinatorStats( - String nodeId, - int queueSize, - int remoteRequestsCurrent, - long remoteRequestsTotal, - long executedSearchesTotal - ) { - this.nodeId = nodeId; - this.queueSize = queueSize; - this.remoteRequestsCurrent = remoteRequestsCurrent; - this.remoteRequestsTotal = remoteRequestsTotal; - this.executedSearchesTotal = executedSearchesTotal; - } - - public String getNodeId() { - return nodeId; - } - - public int getQueueSize() { - return queueSize; - } - - public int getRemoteRequestsCurrent() { - return remoteRequestsCurrent; - } - - public long getRemoteRequestsTotal() { - return remoteRequestsTotal; - } - - public long getExecutedSearchesTotal() { - return executedSearchesTotal; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - CoordinatorStats stats = (CoordinatorStats) o; - return Objects.equals(nodeId, stats.nodeId) - && queueSize == stats.queueSize - && remoteRequestsCurrent == stats.remoteRequestsCurrent - && remoteRequestsTotal == stats.remoteRequestsTotal - && executedSearchesTotal == stats.executedSearchesTotal; - } - - @Override - public int hashCode() { - return Objects.hash(nodeId, queueSize, remoteRequestsCurrent, remoteRequestsTotal, executedSearchesTotal); - } - } - - public static class ExecutingPolicy { - - static ParseField NAME_FIELD = new ParseField("name"); - static ParseField TASK_FIELD = new ParseField("task"); - - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "executing_policy_item", - true, - args -> new ExecutingPolicy((String) args[0], (TaskInfo) args[1]) - ); - - static { - PARSER.declareString(ConstructingObjectParser.constructorArg(), NAME_FIELD); - PARSER.declareObject(ConstructingObjectParser.constructorArg(), (p, c) -> TaskInfo.fromXContent(p), TASK_FIELD); - } - - private final String name; - private final TaskInfo taskInfo; - - public ExecutingPolicy(String name, TaskInfo taskInfo) { - this.name = name; - this.taskInfo = taskInfo; - } - - public String getName() { - return name; - } - - public TaskInfo getTaskInfo() { - return taskInfo; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - ExecutingPolicy that = (ExecutingPolicy) o; - return name.equals(that.name) && taskInfo.equals(that.taskInfo); - } - - @Override - public int hashCode() { - return Objects.hash(name, taskInfo); - } - } - - public static final class CacheStats { - - static ParseField NODE_ID_FIELD = new ParseField("node_id"); - static ParseField COUNT_FIELD = new ParseField("count"); - static ParseField HITS_FIELD = new ParseField("hits"); - static ParseField MISSES_FIELD = new ParseField("misses"); - static ParseField EVICTIONS_FIELD = new ParseField("evictions"); - - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "coordinator_stats_item", - true, - args -> new CacheStats((String) args[0], (long) args[1], (long) args[2], (long) args[3], (long) args[4]) - ); - - static { - PARSER.declareString(ConstructingObjectParser.constructorArg(), NODE_ID_FIELD); - PARSER.declareLong(ConstructingObjectParser.constructorArg(), COUNT_FIELD); - PARSER.declareLong(ConstructingObjectParser.constructorArg(), HITS_FIELD); - PARSER.declareLong(ConstructingObjectParser.constructorArg(), MISSES_FIELD); - PARSER.declareLong(ConstructingObjectParser.constructorArg(), EVICTIONS_FIELD); - } - - private final String nodeId; - private final long count; - private final long hits; - private final long misses; - private final long evictions; - - public CacheStats(String nodeId, long count, long hits, long misses, long evictions) { - this.nodeId = nodeId; - this.count = count; - this.hits = hits; - this.misses = misses; - this.evictions = evictions; - } - - public String getNodeId() { - return nodeId; - } - - public long getCount() { - return count; - } - - public long getHits() { - return hits; - } - - public long getMisses() { - return misses; - } - - public long getEvictions() { - return evictions; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - CacheStats that = (CacheStats) o; - return count == that.count - && hits == that.hits - && misses == that.misses - && evictions == that.evictions - && nodeId.equals(that.nodeId); - } - - @Override - public int hashCode() { - return Objects.hash(nodeId, count, hits, misses, evictions); - } - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/graph/Connection.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/graph/Connection.java deleted file mode 100644 index 56993fe6a2bd2..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/graph/Connection.java +++ /dev/null @@ -1,190 +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.graph; - -import com.carrotsearch.hppc.ObjectIntHashMap; - -import org.elasticsearch.client.graph.Vertex.VertexId; -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.ToXContent.Params; -import org.elasticsearch.xcontent.XContentBuilder; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.List; -import java.util.Objects; - -import static org.elasticsearch.xcontent.ConstructingObjectParser.constructorArg; - -/** - * A Connection links exactly two {@link Vertex} objects. The basis of a - * connection is one or more documents have been found that contain - * this pair of terms and the strength of the connection is recorded - * as a weight. - */ -public class Connection { - private Vertex from; - private Vertex to; - private double weight; - private long docCount; - - public Connection(Vertex from, Vertex to, double weight, long docCount) { - this.from = from; - this.to = to; - this.weight = weight; - this.docCount = docCount; - } - - Connection() {} - - public ConnectionId getId() { - return new ConnectionId(from.getId(), to.getId()); - } - - public Vertex getFrom() { - return from; - } - - public Vertex getTo() { - return to; - } - - /** - * @return a measure of the relative connectedness between a pair of {@link Vertex} objects - */ - public double getWeight() { - return weight; - } - - /** - * @return the number of documents in the sampled set that contained this - * pair of {@link Vertex} objects. - */ - public long getDocCount() { - return docCount; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; - Connection other = (Connection) obj; - return docCount == other.docCount && weight == other.weight && Objects.equals(to, other.to) && Objects.equals(from, other.from); - } - - @Override - public int hashCode() { - return Objects.hash(docCount, weight, from, to); - } - - private static final ParseField SOURCE = new ParseField("source"); - private static final ParseField TARGET = new ParseField("target"); - private static final ParseField WEIGHT = new ParseField("weight"); - private static final ParseField DOC_COUNT = new ParseField("doc_count"); - - void toXContent(XContentBuilder builder, Params params, ObjectIntHashMap vertexNumbers) throws IOException { - builder.field(SOURCE.getPreferredName(), vertexNumbers.get(from)); - builder.field(TARGET.getPreferredName(), vertexNumbers.get(to)); - builder.field(WEIGHT.getPreferredName(), weight); - builder.field(DOC_COUNT.getPreferredName(), docCount); - } - - // When deserializing from XContent we need to wait for all vertices to be loaded before - // Connection objects can be created that reference them. This class provides the interim - // state for connections. - static class UnresolvedConnection { - int fromIndex; - int toIndex; - double weight; - long docCount; - - UnresolvedConnection(int fromIndex, int toIndex, double weight, long docCount) { - super(); - this.fromIndex = fromIndex; - this.toIndex = toIndex; - this.weight = weight; - this.docCount = docCount; - } - - public Connection resolve(List vertices) { - return new Connection(vertices.get(fromIndex), vertices.get(toIndex), weight, docCount); - } - - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "ConnectionParser", - true, - args -> { - int source = (Integer) args[0]; - int target = (Integer) args[1]; - double weight = (Double) args[2]; - long docCount = (Long) args[3]; - return new UnresolvedConnection(source, target, weight, docCount); - } - ); - - static { - PARSER.declareInt(constructorArg(), SOURCE); - PARSER.declareInt(constructorArg(), TARGET); - PARSER.declareDouble(constructorArg(), WEIGHT); - PARSER.declareLong(constructorArg(), DOC_COUNT); - } - - static UnresolvedConnection fromXContent(XContentParser parser) throws IOException { - return PARSER.apply(parser, null); - } - } - - /** - * An identifier (implements hashcode and equals) that represents a - * unique key for a {@link Connection} - */ - public static class ConnectionId { - private final VertexId source; - private final VertexId target; - - public ConnectionId(VertexId source, VertexId target) { - this.source = source; - this.target = target; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - ConnectionId vertexId = (ConnectionId) o; - - if (source != null ? source.equals(vertexId.source) == false : vertexId.source != null) return false; - if (target != null ? target.equals(vertexId.target) == false : vertexId.target != null) return false; - - return true; - } - - @Override - public int hashCode() { - int result = source != null ? source.hashCode() : 0; - result = 31 * result + (target != null ? target.hashCode() : 0); - return result; - } - - public VertexId getSource() { - return source; - } - - public VertexId getTarget() { - return target; - } - - @Override - public String toString() { - return getSource() + "->" + getTarget(); - } - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/graph/GraphExploreRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/graph/GraphExploreRequest.java deleted file mode 100644 index f8f76629869d9..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/graph/GraphExploreRequest.java +++ /dev/null @@ -1,315 +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.graph; - -import org.elasticsearch.action.IndicesRequest; -import org.elasticsearch.action.support.IndicesOptions; -import org.elasticsearch.client.Validatable; -import org.elasticsearch.client.ValidationException; -import org.elasticsearch.common.Strings; -import org.elasticsearch.core.TimeValue; -import org.elasticsearch.index.query.QueryBuilder; -import org.elasticsearch.search.aggregations.bucket.sampler.SamplerAggregationBuilder; -import org.elasticsearch.search.aggregations.bucket.terms.SignificantTerms; -import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregator; -import org.elasticsearch.xcontent.ToXContentObject; -import org.elasticsearch.xcontent.XContentBuilder; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; - -/** - * Holds the criteria required to guide the exploration of connected terms which - * can be returned as a graph. - */ -public class GraphExploreRequest implements IndicesRequest.Replaceable, ToXContentObject, Validatable { - - public static final String NO_HOPS_ERROR_MESSAGE = "Graph explore request must have at least one hop"; - public static final String NO_VERTICES_ERROR_MESSAGE = "Graph explore hop must have at least one VertexRequest"; - private String[] indices = Strings.EMPTY_ARRAY; - private IndicesOptions indicesOptions = IndicesOptions.fromOptions(false, false, true, false); - private String routing; - private TimeValue timeout; - - private int sampleSize = SamplerAggregationBuilder.DEFAULT_SHARD_SAMPLE_SIZE; - private String sampleDiversityField; - private int maxDocsPerDiversityValue; - private boolean useSignificance = true; - private boolean returnDetailedInfo; - - private List hops = new ArrayList<>(); - - public GraphExploreRequest() {} - - /** - * Constructs a new graph request to run against the provided indices. No - * indices means it will run against all indices. - */ - public GraphExploreRequest(String... indices) { - this.indices = indices; - } - - @Override - public Optional validate() { - ValidationException validationException = new ValidationException(); - if (hops.size() == 0) { - validationException.addValidationError(NO_HOPS_ERROR_MESSAGE); - } - for (Hop hop : hops) { - hop.validate(validationException); - } - return validationException.validationErrors().isEmpty() ? Optional.empty() : Optional.of(validationException); - } - - @Override - public String[] indices() { - return this.indices; - } - - @Override - public GraphExploreRequest indices(String... indices) { - this.indices = indices; - return this; - } - - @Override - public IndicesOptions indicesOptions() { - return indicesOptions; - } - - public GraphExploreRequest indicesOptions(IndicesOptions indicesOptions) { - if (indicesOptions == null) { - throw new IllegalArgumentException("IndicesOptions must not be null"); - } - this.indicesOptions = indicesOptions; - return this; - } - - public String routing() { - return this.routing; - } - - public GraphExploreRequest routing(String routing) { - this.routing = routing; - return this; - } - - public GraphExploreRequest routing(String... routings) { - this.routing = Strings.arrayToCommaDelimitedString(routings); - return this; - } - - public TimeValue timeout() { - return timeout; - } - - /** - * Graph exploration can be set to timeout after the given period. Search - * operations involved in each hop are limited to the remaining time - * available but can still overrun due to the nature of their "best efforts" - * timeout support. When a timeout occurs partial results are returned. - * - * @param timeout - * a {@link TimeValue} object which determines the maximum length - * of time to spend exploring - */ - public GraphExploreRequest timeout(TimeValue timeout) { - if (timeout == null) { - throw new IllegalArgumentException("timeout must not be null"); - } - this.timeout = timeout; - return this; - } - - public GraphExploreRequest timeout(String timeout) { - timeout(TimeValue.parseTimeValue(timeout, null, getClass().getSimpleName() + ".timeout")); - return this; - } - - @Override - public String toString() { - return "graph explore [" + Arrays.toString(indices) + "]"; - } - - /** - * The number of top-matching documents that are considered during each hop - * (default is {@link SamplerAggregationBuilder#DEFAULT_SHARD_SAMPLE_SIZE} - * Very small values (less than 50) may not provide sufficient - * weight-of-evidence to identify significant connections between terms. - *

- * Very large values (many thousands) are not recommended with loosely - * defined queries (fuzzy queries or those with many OR clauses). This is - * because any useful signals in the best documents are diluted with - * irrelevant noise from low-quality matches. Performance is also typically - * better with smaller samples as there are less look-ups required for - * background frequencies of terms found in the documents - *

- * - * @param maxNumberOfDocsPerHop - * shard-level sample size in documents - */ - public void sampleSize(int maxNumberOfDocsPerHop) { - sampleSize = maxNumberOfDocsPerHop; - } - - public int sampleSize() { - return sampleSize; - } - - /** - * Optional choice of single-value field on which to diversify sampled - * search results - */ - public void sampleDiversityField(String name) { - sampleDiversityField = name; - } - - public String sampleDiversityField() { - return sampleDiversityField; - } - - /** - * Optional number of permitted docs with same value in sampled search - * results. Must also declare which field using sampleDiversityField - */ - public void maxDocsPerDiversityValue(int maxDocs) { - this.maxDocsPerDiversityValue = maxDocs; - } - - public int maxDocsPerDiversityValue() { - return maxDocsPerDiversityValue; - } - - /** - * Controls the choice of algorithm used to select interesting terms. The - * default value is true which means terms are selected based on - * significance (see the {@link SignificantTerms} aggregation) rather than - * popularity (using the {@link TermsAggregator}). - * - * @param value - * true if the significant_terms algorithm should be used. - */ - public void useSignificance(boolean value) { - this.useSignificance = value; - } - - public boolean useSignificance() { - return useSignificance; - } - - /** - * Return detailed information about vertex frequencies as part of JSON - * results - defaults to false - * - * @param value - * true if detailed information is required in JSON responses - */ - public void returnDetailedInfo(boolean value) { - this.returnDetailedInfo = value; - } - - public boolean returnDetailedInfo() { - return returnDetailedInfo; - } - - /** - * Add a stage in the graph exploration. Each hop represents a stage of - * querying elasticsearch to identify terms which can then be connnected to - * other terms in a subsequent hop. - * - * @param guidingQuery - * optional choice of query which influences which documents are - * considered in this stage - * @return a {@link Hop} object that holds settings for a stage in the graph - * exploration - */ - public Hop createNextHop(QueryBuilder guidingQuery) { - Hop parent = null; - if (hops.size() > 0) { - parent = hops.get(hops.size() - 1); - } - Hop newHop = new Hop(parent); - newHop.guidingQuery = guidingQuery; - hops.add(newHop); - return newHop; - } - - public int getHopNumbers() { - return hops.size(); - } - - public Hop getHop(int hopNumber) { - return hops.get(hopNumber); - } - - public static class TermBoost { - String term; - float boost; - - public TermBoost(String term, float boost) { - super(); - this.term = term; - if (boost <= 0) { - throw new IllegalArgumentException("Boosts must be a positive non-zero number"); - } - this.boost = boost; - } - - TermBoost() {} - - public String getTerm() { - return term; - } - - public float getBoost() { - return boost; - } - } - - @Override - public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(); - - builder.startObject("controls"); - { - if (sampleSize != SamplerAggregationBuilder.DEFAULT_SHARD_SAMPLE_SIZE) { - builder.field("sample_size", sampleSize); - } - if (sampleDiversityField != null) { - builder.startObject("sample_diversity"); - builder.field("field", sampleDiversityField); - builder.field("max_docs_per_value", maxDocsPerDiversityValue); - builder.endObject(); - } - builder.field("use_significance", useSignificance); - if (returnDetailedInfo) { - builder.field("return_detailed_stats", returnDetailedInfo); - } - } - builder.endObject(); - - for (Hop hop : hops) { - if (hop.parentHop != null) { - builder.startObject("connections"); - } - hop.toXContent(builder, params); - } - for (Hop hop : hops) { - if (hop.parentHop != null) { - builder.endObject(); - } - } - builder.endObject(); - - return builder; - } - -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/graph/GraphExploreResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/graph/GraphExploreResponse.java deleted file mode 100644 index 26f7008bde898..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/graph/GraphExploreResponse.java +++ /dev/null @@ -1,207 +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.graph; - -import com.carrotsearch.hppc.ObjectIntHashMap; - -import org.elasticsearch.action.ShardOperationFailedException; -import org.elasticsearch.action.search.ShardSearchFailure; -import org.elasticsearch.client.graph.Connection.ConnectionId; -import org.elasticsearch.client.graph.Connection.UnresolvedConnection; -import org.elasticsearch.client.graph.Vertex.VertexId; -import org.elasticsearch.core.TimeValue; -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.ToXContentObject; -import org.elasticsearch.xcontent.XContentBuilder; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.elasticsearch.xcontent.ConstructingObjectParser.constructorArg; -import static org.elasticsearch.xcontent.ConstructingObjectParser.optionalConstructorArg; - -/** - * Graph explore response holds a graph of {@link Vertex} and {@link Connection} objects - * (nodes and edges in common graph parlance). - * - * @see GraphExploreRequest - */ -public class GraphExploreResponse implements ToXContentObject { - - private long tookInMillis; - private boolean timedOut = false; - private ShardOperationFailedException[] shardFailures = ShardSearchFailure.EMPTY_ARRAY; - private Map vertices; - private Map connections; - private boolean returnDetailedInfo; - static final String RETURN_DETAILED_INFO_PARAM = "returnDetailedInfo"; - - public GraphExploreResponse() {} - - public GraphExploreResponse( - long tookInMillis, - boolean timedOut, - ShardOperationFailedException[] shardFailures, - Map vertices, - Map connections, - boolean returnDetailedInfo - ) { - this.tookInMillis = tookInMillis; - this.timedOut = timedOut; - this.shardFailures = shardFailures; - this.vertices = vertices; - this.connections = connections; - this.returnDetailedInfo = returnDetailedInfo; - } - - public TimeValue getTook() { - return new TimeValue(tookInMillis); - } - - public long getTookInMillis() { - return tookInMillis; - } - - /** - * @return true if the time stated in {@link GraphExploreRequest#timeout(TimeValue)} was exceeded - * (not all hops may have been completed in this case) - */ - public boolean isTimedOut() { - return this.timedOut; - } - - public ShardOperationFailedException[] getShardFailures() { - return shardFailures; - } - - public Collection getConnections() { - return connections.values(); - } - - public Collection getConnectionIds() { - return connections.keySet(); - } - - public Connection getConnection(ConnectionId connectionId) { - return connections.get(connectionId); - } - - public Collection getVertices() { - return vertices.values(); - } - - public Collection getVertexIds() { - return vertices.keySet(); - } - - public Vertex getVertex(VertexId id) { - return vertices.get(id); - } - - public boolean isReturnDetailedInfo() { - return returnDetailedInfo; - } - - private static final ParseField TOOK = new ParseField("took"); - private static final ParseField TIMED_OUT = new ParseField("timed_out"); - private static final ParseField VERTICES = new ParseField("vertices"); - private static final ParseField CONNECTIONS = new ParseField("connections"); - private static final ParseField FAILURES = new ParseField("failures"); - - @Override - public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(); - builder.field(TOOK.getPreferredName(), tookInMillis); - builder.field(TIMED_OUT.getPreferredName(), timedOut); - - builder.startArray(FAILURES.getPreferredName()); - if (shardFailures != null) { - for (ShardOperationFailedException shardFailure : shardFailures) { - shardFailure.toXContent(builder, params); - } - } - builder.endArray(); - - ObjectIntHashMap vertexNumbers = new ObjectIntHashMap<>(vertices.size()); - - Map extraParams = new HashMap<>(); - extraParams.put(RETURN_DETAILED_INFO_PARAM, Boolean.toString(returnDetailedInfo)); - Params extendedParams = new DelegatingMapParams(extraParams, params); - - builder.startArray(VERTICES.getPreferredName()); - for (Vertex vertex : vertices.values()) { - builder.startObject(); - vertexNumbers.put(vertex, vertexNumbers.size()); - vertex.toXContent(builder, extendedParams); - builder.endObject(); - } - builder.endArray(); - - builder.startArray(CONNECTIONS.getPreferredName()); - for (Connection connection : connections.values()) { - builder.startObject(); - connection.toXContent(builder, extendedParams, vertexNumbers); - builder.endObject(); - } - builder.endArray(); - builder.endObject(); - return builder; - } - - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "GraphExploreResponsenParser", - true, - args -> { - GraphExploreResponse result = new GraphExploreResponse(); - result.vertices = new HashMap<>(); - result.connections = new HashMap<>(); - - result.tookInMillis = (Long) args[0]; - result.timedOut = (Boolean) args[1]; - - @SuppressWarnings("unchecked") - List vertices = (List) args[2]; - @SuppressWarnings("unchecked") - List unresolvedConnections = (List) args[3]; - @SuppressWarnings("unchecked") - List failures = (List) args[4]; - for (Vertex vertex : vertices) { - // reverse-engineer if detailed stats were requested - - // mainly here for testing framework's equality tests - result.returnDetailedInfo = result.returnDetailedInfo || vertex.getFg() > 0; - result.vertices.put(vertex.getId(), vertex); - } - for (UnresolvedConnection unresolvedConnection : unresolvedConnections) { - Connection resolvedConnection = unresolvedConnection.resolve(vertices); - result.connections.put(resolvedConnection.getId(), resolvedConnection); - } - if (failures.size() > 0) { - result.shardFailures = failures.toArray(new ShardSearchFailure[failures.size()]); - } - return result; - } - ); - - static { - PARSER.declareLong(constructorArg(), TOOK); - PARSER.declareBoolean(constructorArg(), TIMED_OUT); - PARSER.declareObjectArray(optionalConstructorArg(), (p, c) -> Vertex.fromXContent(p), VERTICES); - PARSER.declareObjectArray(optionalConstructorArg(), (p, c) -> UnresolvedConnection.fromXContent(p), CONNECTIONS); - PARSER.declareObjectArray(optionalConstructorArg(), (p, c) -> ShardSearchFailure.fromXContent(p), FAILURES); - } - - public static GraphExploreResponse fromXContent(XContentParser parser) throws IOException { - return PARSER.apply(parser, null); - } - -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/graph/Hop.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/graph/Hop.java deleted file mode 100644 index e997b7cc3c9cd..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/graph/Hop.java +++ /dev/null @@ -1,131 +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.graph; - -import org.elasticsearch.client.ValidationException; -import org.elasticsearch.index.query.QueryBuilder; -import org.elasticsearch.index.query.QueryBuilders; -import org.elasticsearch.xcontent.ToXContentFragment; -import org.elasticsearch.xcontent.XContentBuilder; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** - * A Hop represents one of potentially many stages in a graph exploration. - * Each Hop identifies one or more fields in which it will attempt to find - * terms that are significantly connected to the previous Hop. Each field is identified - * using a {@link VertexRequest} - * - *

An example series of Hops on webserver logs would be: - *

    - *
  1. an initial Hop to find - * the top ten IPAddresses trying to access urls containing the word "admin"
  2. - *
  3. a secondary Hop to see which other URLs those IPAddresses were trying to access
  4. - *
- * - *

- * Optionally, each hop can contain a "guiding query" that further limits the set of documents considered. - * In our weblog example above we might choose to constrain the second hop to only look at log records that - * had a reponse code of 404. - *

- *

- * If absent, the list of {@link VertexRequest}s is inherited from the prior Hop's list to avoid repeating - * the fields that will be examined at each stage. - *

- * - */ -public class Hop implements ToXContentFragment { - final Hop parentHop; - List vertices = null; - QueryBuilder guidingQuery = null; - - public Hop(Hop parent) { - this.parentHop = parent; - } - - public void validate(ValidationException validationException) { - if (getEffectiveVertexRequests().size() == 0) { - validationException.addValidationError(GraphExploreRequest.NO_VERTICES_ERROR_MESSAGE); - } - } - - public Hop getParentHop() { - return parentHop; - } - - public QueryBuilder guidingQuery() { - if (guidingQuery != null) { - return guidingQuery; - } - return QueryBuilders.matchAllQuery(); - } - - /** - * Add a field in which this {@link Hop} will look for terms that are highly linked to - * previous hops and optionally the guiding query. - * - * @param fieldName a field in the chosen index - */ - public VertexRequest addVertexRequest(String fieldName) { - if (vertices == null) { - vertices = new ArrayList<>(); - } - VertexRequest vr = new VertexRequest(); - vr.fieldName(fieldName); - vertices.add(vr); - return vr; - } - - /** - * An optional parameter that focuses the exploration on documents that - * match the given query. - * - * @param queryBuilder any query - */ - public void guidingQuery(QueryBuilder queryBuilder) { - guidingQuery = queryBuilder; - } - - protected List getEffectiveVertexRequests() { - if (vertices != null) { - return vertices; - } - if (parentHop == null) { - return Collections.emptyList(); - } - // otherwise inherit settings from parent - return parentHop.getEffectiveVertexRequests(); - } - - public int getNumberVertexRequests() { - return getEffectiveVertexRequests().size(); - } - - public VertexRequest getVertexRequest(int requestNumber) { - return getEffectiveVertexRequests().get(requestNumber); - } - - @Override - public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - if (guidingQuery != null) { - builder.field("query"); - guidingQuery.toXContent(builder, params); - } - if (vertices != null && vertices.size() > 0) { - builder.startArray("vertices"); - for (VertexRequest vertexRequest : vertices) { - vertexRequest.toXContent(builder, params); - } - builder.endArray(); - } - return builder; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/graph/Vertex.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/graph/Vertex.java deleted file mode 100644 index 2db13014aa427..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/graph/Vertex.java +++ /dev/null @@ -1,244 +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.graph; - -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.ToXContentFragment; -import org.elasticsearch.xcontent.XContentBuilder; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.Objects; - -import static org.elasticsearch.xcontent.ConstructingObjectParser.constructorArg; -import static org.elasticsearch.xcontent.ConstructingObjectParser.optionalConstructorArg; - -/** - * A vertex in a graph response represents a single term (a field and value pair) - * which appears in one or more documents found as part of the graph exploration. - * - * A vertex term could be a bank account number, an email address, a hashtag or any - * other term that appears in documents and is interesting to represent in a network. - */ -public class Vertex implements ToXContentFragment { - - private final String field; - private final String term; - private double weight; - private final int depth; - private final long bg; - private long fg; - private static final ParseField FIELD = new ParseField("field"); - private static final ParseField TERM = new ParseField("term"); - private static final ParseField WEIGHT = new ParseField("weight"); - private static final ParseField DEPTH = new ParseField("depth"); - private static final ParseField FG = new ParseField("fg"); - private static final ParseField BG = new ParseField("bg"); - - public Vertex(String field, String term, double weight, int depth, long bg, long fg) { - super(); - this.field = field; - this.term = term; - this.weight = weight; - this.depth = depth; - this.bg = bg; - this.fg = fg; - } - - @Override - public int hashCode() { - return Objects.hash(field, term, weight, depth, bg, fg); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; - Vertex other = (Vertex) obj; - return depth == other.depth - && weight == other.weight - && bg == other.bg - && fg == other.fg - && Objects.equals(field, other.field) - && Objects.equals(term, other.term); - - } - - @Override - public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - boolean returnDetailedInfo = params.paramAsBoolean(GraphExploreResponse.RETURN_DETAILED_INFO_PARAM, false); - builder.field(FIELD.getPreferredName(), field); - builder.field(TERM.getPreferredName(), term); - builder.field(WEIGHT.getPreferredName(), weight); - builder.field(DEPTH.getPreferredName(), depth); - if (returnDetailedInfo) { - builder.field(FG.getPreferredName(), fg); - builder.field(BG.getPreferredName(), bg); - } - return builder; - } - - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>("VertexParser", true, args -> { - String field = (String) args[0]; - String term = (String) args[1]; - double weight = (Double) args[2]; - int depth = (Integer) args[3]; - Long optionalBg = (Long) args[4]; - Long optionalFg = (Long) args[5]; - long bg = optionalBg == null ? 0 : optionalBg; - long fg = optionalFg == null ? 0 : optionalFg; - return new Vertex(field, term, weight, depth, bg, fg); - }); - - static { - PARSER.declareString(constructorArg(), FIELD); - PARSER.declareString(constructorArg(), TERM); - PARSER.declareDouble(constructorArg(), WEIGHT); - PARSER.declareInt(constructorArg(), DEPTH); - PARSER.declareLong(optionalConstructorArg(), BG); - PARSER.declareLong(optionalConstructorArg(), FG); - } - - static Vertex fromXContent(XContentParser parser) throws IOException { - return PARSER.apply(parser, null); - } - - /** - * @return a {@link VertexId} object that uniquely identifies this Vertex - */ - public VertexId getId() { - return createId(field, term); - } - - /** - * A convenience method for creating a {@link VertexId} - * @param field the field - * @param term the term - * @return a {@link VertexId} that can be used for looking up vertices - */ - public static VertexId createId(String field, String term) { - return new VertexId(field, term); - } - - @Override - public String toString() { - return getId().toString(); - } - - public String getField() { - return field; - } - - public String getTerm() { - return term; - } - - /** - * The weight of a vertex is an accumulation of all of the {@link Connection}s - * that are linked to this {@link Vertex} as part of a graph exploration. - * It is used internally to identify the most interesting vertices to be returned. - * @return a measure of the {@link Vertex}'s relative importance. - */ - public double getWeight() { - return weight; - } - - public void setWeight(final double weight) { - this.weight = weight; - } - - // tag::noformat - /** - * If the {@link GraphExploreRequest#useSignificance(boolean)} is true (the default) - * this statistic is available. - * @return the number of documents in the index that contain this term (see bg_count in - * the significant_terms aggregation) - */ - // end::noformat - public long getBg() { - return bg; - } - - // tag::noformat - /** - * If the {@link GraphExploreRequest#useSignificance(boolean)} is true (the default) - * this statistic is available. - * Together with {@link #getBg()} these numbers are used to derive the significance of a term. - * @return the number of documents in the sample of best matching documents that contain this term (see fg_count in - * the significant_terms aggregation) - */ - // end::noformat - public long getFg() { - return fg; - } - - public void setFg(final long fg) { - this.fg = fg; - } - - /** - * @return the sequence number in the series of hops where this Vertex term was first encountered - */ - public int getHopDepth() { - return depth; - } - - /** - * An identifier (implements hashcode and equals) that represents a - * unique key for a {@link Vertex} - */ - public static class VertexId { - private final String field; - private final String term; - - public VertexId(String field, String term) { - this.field = field; - this.term = term; - } - - public String getField() { - return field; - } - - public String getTerm() { - return term; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - VertexId vertexId = (VertexId) o; - - if (field != null ? field.equals(vertexId.field) == false : vertexId.field != null) return false; - if (term != null ? term.equals(vertexId.term) == false : vertexId.term != null) return false; - - return true; - } - - @Override - public int hashCode() { - int result = field != null ? field.hashCode() : 0; - result = 31 * result + (term != null ? term.hashCode() : 0); - return result; - } - - @Override - public String toString() { - return field + ":" + term; - } - } - -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/graph/VertexRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/graph/VertexRequest.java deleted file mode 100644 index 92c26b00e9201..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/graph/VertexRequest.java +++ /dev/null @@ -1,182 +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.graph; - -import org.elasticsearch.client.graph.GraphExploreRequest.TermBoost; -import org.elasticsearch.xcontent.ToXContentObject; -import org.elasticsearch.xcontent.XContentBuilder; - -import java.io.IOException; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -/** - * A request to identify terms from a choice of field as part of a {@link Hop}. - * Optionally, a set of terms can be provided that are used as an exclusion or - * inclusion list to filter which terms are considered. - * - */ -public class VertexRequest implements ToXContentObject { - private String fieldName; - private int size = DEFAULT_SIZE; - public static final int DEFAULT_SIZE = 5; - private Map includes; - private Set excludes; - public static final int DEFAULT_MIN_DOC_COUNT = 3; - private int minDocCount = DEFAULT_MIN_DOC_COUNT; - public static final int DEFAULT_SHARD_MIN_DOC_COUNT = 2; - private int shardMinDocCount = DEFAULT_SHARD_MIN_DOC_COUNT; - - public VertexRequest() { - - } - - public String fieldName() { - return fieldName; - } - - public VertexRequest fieldName(String fieldName) { - this.fieldName = fieldName; - return this; - } - - public int size() { - return size; - } - - /** - * @param size The maximum number of terms that should be returned from this field as part of this {@link Hop} - */ - public VertexRequest size(int size) { - this.size = size; - return this; - } - - public boolean hasIncludeClauses() { - return includes != null && includes.size() > 0; - } - - public boolean hasExcludeClauses() { - return excludes != null && excludes.size() > 0; - } - - /** - * Adds a term that should be excluded from results - * @param term A term to be excluded - */ - public void addExclude(String term) { - if (includes != null) { - throw new IllegalArgumentException("Cannot have both include and exclude clauses"); - } - if (excludes == null) { - excludes = new HashSet<>(); - } - excludes.add(term); - } - - /** - * Adds a term to the set of allowed values - the boost defines the relative - * importance when pursuing connections in subsequent {@link Hop}s. The boost value - * appears as part of the query. - * @param term a required term - * @param boost an optional boost - */ - public void addInclude(String term, float boost) { - if (excludes != null) { - throw new IllegalArgumentException("Cannot have both include and exclude clauses"); - } - if (includes == null) { - includes = new HashMap<>(); - } - includes.put(term, new TermBoost(term, boost)); - } - - public TermBoost[] includeValues() { - return includes.values().toArray(new TermBoost[includes.size()]); - } - - public String[] includeValuesAsStringArray() { - String[] result = new String[includes.size()]; - int i = 0; - for (TermBoost tb : includes.values()) { - result[i++] = tb.term; - } - return result; - } - - public String[] excludesAsArray() { - return excludes.toArray(new String[excludes.size()]); - } - - public int minDocCount() { - return minDocCount; - } - - /** - * A "certainty" threshold which defines the weight-of-evidence required before - * a term found in this field is identified as a useful connection - * - * @param value The minimum number of documents that contain this term found in the samples used across all shards - */ - public VertexRequest minDocCount(int value) { - minDocCount = value; - return this; - } - - public int shardMinDocCount() { - return Math.min(shardMinDocCount, minDocCount); - } - - /** - * A "certainty" threshold which defines the weight-of-evidence required before - * a term found in this field is identified as a useful connection - * - * @param value The minimum number of documents that contain this term found in the samples used across all shards - */ - public VertexRequest shardMinDocCount(int value) { - shardMinDocCount = value; - return this; - } - - @Override - public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(); - builder.field("field", fieldName); - if (size != DEFAULT_SIZE) { - builder.field("size", size); - } - if (minDocCount != DEFAULT_MIN_DOC_COUNT) { - builder.field("min_doc_count", minDocCount); - } - if (shardMinDocCount != DEFAULT_SHARD_MIN_DOC_COUNT) { - builder.field("shard_min_doc_count", shardMinDocCount); - } - if (includes != null) { - builder.startArray("include"); - for (TermBoost tb : includes.values()) { - builder.startObject(); - builder.field("term", tb.term); - builder.field("boost", tb.boost); - builder.endObject(); - } - builder.endArray(); - } - if (excludes != null) { - builder.startArray("exclude"); - for (String value : excludes) { - builder.value(value); - } - builder.endArray(); - } - builder.endObject(); - return builder; - } - -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/graph/package-info.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/graph/package-info.java deleted file mode 100644 index 6b723b6a79ddf..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/graph/package-info.java +++ /dev/null @@ -1,13 +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. - */ - -/** - * Request and Response objects for the default distribution's Graph - * APIs. - */ -package org.elasticsearch.client.graph; diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/license/DeleteLicenseRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/license/DeleteLicenseRequest.java deleted file mode 100644 index 538f616ec4744..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/license/DeleteLicenseRequest.java +++ /dev/null @@ -1,14 +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.license; - -import org.elasticsearch.client.TimedRequest; - -public class DeleteLicenseRequest extends TimedRequest { - -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/license/GetBasicStatusResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/license/GetBasicStatusResponse.java deleted file mode 100644 index 4d98ab60074c1..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/license/GetBasicStatusResponse.java +++ /dev/null @@ -1,75 +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.license; - -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; - -/** - * Response class for license get basic status API - */ -public class GetBasicStatusResponse { - - private static final ParseField ELIGIBLE_TO_START_BASIC = new ParseField("eligible_to_start_basic"); - - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "get_basic_status_response", - true, - a -> new GetBasicStatusResponse((boolean) a[0]) - ); - - static { - PARSER.declareField( - constructorArg(), - (parser, context) -> parser.booleanValue(), - ELIGIBLE_TO_START_BASIC, - ObjectParser.ValueType.BOOLEAN - ); - } - - private final boolean eligibleToStartBasic; - - GetBasicStatusResponse(boolean eligibleToStartBasic) { - this.eligibleToStartBasic = eligibleToStartBasic; - } - - /** - * Returns whether the license is eligible to start basic or not - */ - public boolean isEligibleToStartBasic() { - return eligibleToStartBasic; - } - - public static GetBasicStatusResponse 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; - } - GetBasicStatusResponse that = (GetBasicStatusResponse) o; - return eligibleToStartBasic == that.eligibleToStartBasic; - } - - @Override - public int hashCode() { - return Objects.hash(eligibleToStartBasic); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/license/GetLicenseRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/license/GetLicenseRequest.java deleted file mode 100644 index 1e236379c6da2..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/license/GetLicenseRequest.java +++ /dev/null @@ -1,25 +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.license; - -import org.elasticsearch.client.Validatable; - -public class GetLicenseRequest implements Validatable { - - protected boolean local = false; - - public GetLicenseRequest() {} - - 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/license/GetLicenseResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/license/GetLicenseResponse.java deleted file mode 100644 index 6ebef1dd6a54b..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/license/GetLicenseResponse.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.license; - -public class GetLicenseResponse { - - private String license; - - GetLicenseResponse() {} - - public GetLicenseResponse(String license) { - this.license = license; - } - - public String getLicenseDefinition() { - return license; - } - -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/license/GetTrialStatusResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/license/GetTrialStatusResponse.java deleted file mode 100644 index 65f7ba8f4a2df..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/license/GetTrialStatusResponse.java +++ /dev/null @@ -1,76 +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.license; - -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; - -/** - * Response class for license get trial status API - */ -public class GetTrialStatusResponse { - - private static final ParseField ELIGIBLE_TO_START_TRIAL = new ParseField("eligible_to_start_trial"); - - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "get_trial_status_response", - true, - a -> new GetTrialStatusResponse((boolean) a[0]) - ); - - static { - PARSER.declareField( - constructorArg(), - (parser, context) -> parser.booleanValue(), - ELIGIBLE_TO_START_TRIAL, - ObjectParser.ValueType.BOOLEAN - ); - } - - private final boolean eligibleToStartTrial; - - GetTrialStatusResponse(boolean eligibleToStartTrial) { - this.eligibleToStartTrial = eligibleToStartTrial; - } - - /** - * Returns whether the license is eligible to start trial or not - */ - public boolean isEligibleToStartTrial() { - return eligibleToStartTrial; - } - - public static GetTrialStatusResponse 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; - } - GetTrialStatusResponse that = (GetTrialStatusResponse) o; - return eligibleToStartTrial == that.eligibleToStartTrial; - } - - @Override - public int hashCode() { - return Objects.hash(eligibleToStartTrial); - } - -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/license/LicensesStatus.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/license/LicensesStatus.java deleted file mode 100644 index f9dbaf611ec11..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/license/LicensesStatus.java +++ /dev/null @@ -1,52 +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.license; - -import java.util.Locale; - -public enum LicensesStatus { - VALID((byte) 0), - INVALID((byte) 1), - EXPIRED((byte) 2); - - private final byte id; - - LicensesStatus(byte id) { - this.id = id; - } - - public int id() { - return id; - } - - public static LicensesStatus fromId(int id) { - if (id == 0) { - return VALID; - } else if (id == 1) { - return INVALID; - } else if (id == 2) { - return EXPIRED; - } else { - throw new IllegalStateException("no valid LicensesStatus for id=" + id); - } - } - - @Override - public String toString() { - return this.name().toLowerCase(Locale.ROOT); - } - - public static LicensesStatus fromString(String value) { - return switch (value) { - case "valid" -> VALID; - case "invalid" -> INVALID; - case "expired" -> EXPIRED; - default -> throw new IllegalArgumentException("unknown licenses status [" + value + "]"); - }; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/license/PutLicenseRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/license/PutLicenseRequest.java deleted file mode 100644 index 0a9e2e6ab18cc..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/license/PutLicenseRequest.java +++ /dev/null @@ -1,35 +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.license; - -import org.elasticsearch.client.TimedRequest; - -public class PutLicenseRequest extends TimedRequest { - - private String licenseDefinition; - private boolean acknowledge = false; - - public PutLicenseRequest() {} - - public void setLicenseDefinition(String licenseDefinition) { - this.licenseDefinition = licenseDefinition; - } - - public String getLicenseDefinition() { - return licenseDefinition; - } - - public void setAcknowledge(boolean acknowledge) { - this.acknowledge = acknowledge; - } - - public boolean isAcknowledge() { - return acknowledge; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/license/PutLicenseResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/license/PutLicenseResponse.java deleted file mode 100644 index 2970f8b83a707..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/license/PutLicenseResponse.java +++ /dev/null @@ -1,147 +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.license; - -import org.elasticsearch.client.common.ProtocolUtils; -import org.elasticsearch.core.Tuple; -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentParseException; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -import static org.elasticsearch.xcontent.ConstructingObjectParser.constructorArg; -import static org.elasticsearch.xcontent.ConstructingObjectParser.optionalConstructorArg; - -public final class PutLicenseResponse { - - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "put_license_response", - true, - (a, v) -> { - boolean acknowledged = (Boolean) a[0]; - LicensesStatus licensesStatus = LicensesStatus.fromString((String) a[1]); - @SuppressWarnings("unchecked") - Tuple> acknowledgements = (Tuple>) a[2]; - if (acknowledgements == null) { - return new PutLicenseResponse(acknowledged, licensesStatus); - } else { - return new PutLicenseResponse(acknowledged, licensesStatus, acknowledgements.v1(), acknowledgements.v2()); - } - - } - ); - - static { - PARSER.declareBoolean(constructorArg(), new ParseField("acknowledged")); - PARSER.declareString(constructorArg(), new ParseField("license_status")); - PARSER.declareObject(optionalConstructorArg(), (parser, v) -> { - Map acknowledgeMessages = new HashMap<>(); - String message = null; - XContentParser.Token token; - String currentFieldName = null; - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else { - if (currentFieldName == null) { - throw new XContentParseException(parser.getTokenLocation(), "expected message header or acknowledgement"); - } - if ("message".equals(currentFieldName)) { - if (token != XContentParser.Token.VALUE_STRING) { - throw new XContentParseException(parser.getTokenLocation(), "unexpected message header type"); - } - message = parser.text(); - } else { - if (token != XContentParser.Token.START_ARRAY) { - throw new XContentParseException(parser.getTokenLocation(), "unexpected acknowledgement type"); - } - List acknowledgeMessagesList = new ArrayList<>(); - while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { - if (token != XContentParser.Token.VALUE_STRING) { - throw new XContentParseException(parser.getTokenLocation(), "unexpected acknowledgement text"); - } - acknowledgeMessagesList.add(parser.text()); - } - acknowledgeMessages.put(currentFieldName, acknowledgeMessagesList.toArray(new String[0])); - } - } - } - return new Tuple<>(message, acknowledgeMessages); - }, new ParseField("acknowledge")); - } - - private boolean acknowledged; - private LicensesStatus status; - private Map acknowledgeMessages; - private String acknowledgeHeader; - - public PutLicenseResponse() {} - - public PutLicenseResponse(boolean acknowledged, LicensesStatus status) { - this(acknowledged, status, null, Collections.emptyMap()); - } - - public PutLicenseResponse( - boolean acknowledged, - LicensesStatus status, - String acknowledgeHeader, - Map acknowledgeMessages - ) { - this.acknowledged = acknowledged; - this.status = status; - this.acknowledgeHeader = acknowledgeHeader; - this.acknowledgeMessages = acknowledgeMessages; - } - - public boolean isAcknowledged() { - return acknowledged; - } - - public LicensesStatus status() { - return status; - } - - public Map acknowledgeMessages() { - return acknowledgeMessages; - } - - public String acknowledgeHeader() { - return acknowledgeHeader; - } - - public static PutLicenseResponse 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; - if (super.equals(o) == false) return false; - PutLicenseResponse that = (PutLicenseResponse) o; - - return status == that.status - && ProtocolUtils.equals(acknowledgeMessages, that.acknowledgeMessages) - && Objects.equals(acknowledgeHeader, that.acknowledgeHeader); - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), status, ProtocolUtils.hashCode(acknowledgeMessages), acknowledgeHeader); - } - -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/license/StartBasicRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/license/StartBasicRequest.java deleted file mode 100644 index ebfaca66552ad..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/license/StartBasicRequest.java +++ /dev/null @@ -1,26 +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.license; - -import org.elasticsearch.client.TimedRequest; - -public class StartBasicRequest extends TimedRequest { - private final boolean acknowledge; - - public StartBasicRequest() { - this(false); - } - - public StartBasicRequest(boolean acknowledge) { - this.acknowledge = acknowledge; - } - - public boolean isAcknowledge() { - return acknowledge; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/license/StartBasicResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/license/StartBasicResponse.java deleted file mode 100644 index df037e22169c0..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/license/StartBasicResponse.java +++ /dev/null @@ -1,148 +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.license; - -import org.elasticsearch.core.Tuple; -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentParseException; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -import static org.elasticsearch.common.xcontent.XContentParserUtils.ensureExpectedToken; -import static org.elasticsearch.xcontent.ConstructingObjectParser.constructorArg; -import static org.elasticsearch.xcontent.ConstructingObjectParser.optionalConstructorArg; - -public class StartBasicResponse { - - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "start_basic_response", - true, - (a, v) -> { - boolean basicWasStarted = (Boolean) a[0]; - String errorMessage = (String) a[1]; - - if (basicWasStarted) { - return new StartBasicResponse(StartBasicResponse.Status.GENERATED_BASIC); - } - StartBasicResponse.Status status = StartBasicResponse.Status.fromErrorMessage(errorMessage); - @SuppressWarnings("unchecked") - Tuple> acknowledgements = (Tuple>) a[2]; - return new StartBasicResponse(status, acknowledgements.v2(), acknowledgements.v1()); - } - ); - - static { - PARSER.declareBoolean(constructorArg(), new ParseField("basic_was_started")); - PARSER.declareString(optionalConstructorArg(), new ParseField("error_message")); - PARSER.declareObject(optionalConstructorArg(), (parser, v) -> { - Map acknowledgeMessages = new HashMap<>(); - String message = null; - XContentParser.Token token; - String currentFieldName = null; - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else { - if (currentFieldName == null) { - throw new XContentParseException(parser.getTokenLocation(), "expected message header or acknowledgement"); - } - if (new ParseField("message").getPreferredName().equals(currentFieldName)) { - ensureExpectedToken(XContentParser.Token.VALUE_STRING, token, parser); - message = parser.text(); - } else { - if (token != XContentParser.Token.START_ARRAY) { - throw new XContentParseException(parser.getTokenLocation(), "unexpected acknowledgement type"); - } - List acknowledgeMessagesList = new ArrayList<>(); - while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { - ensureExpectedToken(XContentParser.Token.VALUE_STRING, token, parser); - acknowledgeMessagesList.add(parser.text()); - } - acknowledgeMessages.put(currentFieldName, acknowledgeMessagesList.toArray(new String[0])); - } - } - } - return new Tuple<>(message, acknowledgeMessages); - }, new ParseField("acknowledge")); - } - - private Map acknowledgeMessages; - private String acknowledgeMessage; - - public enum Status { - GENERATED_BASIC(true, null), - ALREADY_USING_BASIC(false, "Operation failed: Current license is basic."), - NEED_ACKNOWLEDGEMENT(false, "Operation failed: Needs acknowledgement."); - - private final boolean isBasicStarted; - private final String errorMessage; - - Status(boolean isBasicStarted, String errorMessage) { - this.isBasicStarted = isBasicStarted; - this.errorMessage = errorMessage; - } - - static StartBasicResponse.Status fromErrorMessage(final String errorMessage) { - final StartBasicResponse.Status[] values = StartBasicResponse.Status.values(); - for (StartBasicResponse.Status status : values) { - if (Objects.equals(status.errorMessage, errorMessage)) { - return status; - } - } - throw new IllegalArgumentException("No status for error message ['" + errorMessage + "']"); - } - } - - private StartBasicResponse.Status status; - - private StartBasicResponse(StartBasicResponse.Status status) { - this(status, Collections.emptyMap(), null); - } - - private StartBasicResponse(StartBasicResponse.Status status, Map acknowledgeMessages, String acknowledgeMessage) { - this.status = status; - this.acknowledgeMessages = acknowledgeMessages; - this.acknowledgeMessage = acknowledgeMessage; - } - - public Status getStatus() { - return status; - } - - public boolean isAcknowledged() { - return status != StartBasicResponse.Status.NEED_ACKNOWLEDGEMENT; - } - - public boolean isBasicStarted() { - return status.isBasicStarted; - } - - public String getErrorMessage() { - return status.errorMessage; - } - - public String getAcknowledgeMessage() { - return acknowledgeMessage; - } - - public Map getAcknowledgeMessages() { - return acknowledgeMessages; - } - - public static StartBasicResponse fromXContent(XContentParser parser) throws IOException { - return PARSER.parse(parser, null); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/license/StartTrialRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/license/StartTrialRequest.java deleted file mode 100644 index 8d60e334f9db6..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/license/StartTrialRequest.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.license; - -import org.elasticsearch.client.Validatable; -import org.elasticsearch.core.Nullable; - -public class StartTrialRequest implements Validatable { - - private final boolean acknowledge; - private final String licenseType; - - public StartTrialRequest() { - this(false); - } - - public StartTrialRequest(boolean acknowledge) { - this(acknowledge, null); - } - - public StartTrialRequest(boolean acknowledge, @Nullable String licenseType) { - this.acknowledge = acknowledge; - this.licenseType = licenseType; - } - - public boolean isAcknowledge() { - return acknowledge; - } - - public String getLicenseType() { - return licenseType; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/license/StartTrialResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/license/StartTrialResponse.java deleted file mode 100644 index 13e831be3149e..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/license/StartTrialResponse.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.license; - -import org.elasticsearch.core.Tuple; -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentParseException; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.elasticsearch.xcontent.ConstructingObjectParser.constructorArg; -import static org.elasticsearch.xcontent.ConstructingObjectParser.optionalConstructorArg; - -public class StartTrialResponse { - - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "start_trial_response", - true, - (Object[] arguments, Void aVoid) -> { - final boolean acknowledged = (boolean) arguments[0]; - final boolean trialWasStarted = (boolean) arguments[1]; - final String licenseType = (String) arguments[2]; - final String errorMessage = (String) arguments[3]; - - @SuppressWarnings("unchecked") - final Tuple> acknowledgeDetails = (Tuple>) arguments[4]; - final String acknowledgeHeader; - final Map acknowledgeMessages; - - if (acknowledgeDetails != null) { - acknowledgeHeader = acknowledgeDetails.v1(); - acknowledgeMessages = acknowledgeDetails.v2(); - } else { - acknowledgeHeader = null; - acknowledgeMessages = null; - } - - return new StartTrialResponse(acknowledged, trialWasStarted, licenseType, errorMessage, acknowledgeHeader, acknowledgeMessages); - } - ); - - static { - PARSER.declareBoolean(constructorArg(), new ParseField("acknowledged")); - PARSER.declareBoolean(constructorArg(), new ParseField("trial_was_started")); - PARSER.declareString(optionalConstructorArg(), new ParseField("type")); - PARSER.declareString(optionalConstructorArg(), new ParseField("error_message")); - // todo consolidate this parsing with the parsing in PutLicenseResponse - PARSER.declareObject(optionalConstructorArg(), (parser, aVoid) -> { - final Map acknowledgeMessages = new HashMap<>(); - String message = null; - - final Map parsedMap = parser.map(); - for (Map.Entry entry : parsedMap.entrySet()) { - if (entry.getKey().equals("message")) { - if (entry.getValue() instanceof String) { - message = (String) entry.getValue(); - } else { - throw new XContentParseException(parser.getTokenLocation(), "unexpected acknowledgement header type"); - } - } else { - if (entry.getValue() instanceof List) { - final List messageStrings = new ArrayList<>(); - @SuppressWarnings("unchecked") - final List messageObjects = (List) entry.getValue(); - for (Object messageObject : messageObjects) { - if (messageObject instanceof String) { - messageStrings.add((String) messageObject); - } else { - throw new XContentParseException(parser.getTokenLocation(), "expected text in acknowledgement message"); - } - } - - acknowledgeMessages.put(entry.getKey(), messageStrings.toArray(new String[messageStrings.size()])); - } else { - throw new XContentParseException(parser.getTokenLocation(), "unexpected acknowledgement message type"); - } - } - } - - if (message == null) { - throw new XContentParseException(parser.getTokenLocation(), "expected acknowledgement header"); - } - - return new Tuple<>(message, acknowledgeMessages); - - }, new ParseField("acknowledge")); - } - - public static StartTrialResponse fromXContent(XContentParser parser) throws IOException { - return PARSER.apply(parser, null); - } - - private final boolean acknowledged; - private final boolean trialWasStarted; - private final String licenseType; - private final String errorMessage; - private final String acknowledgeHeader; - private final Map acknowledgeMessages; - - public StartTrialResponse( - boolean acknowledged, - boolean trialWasStarted, - String licenseType, - String errorMessage, - String acknowledgeHeader, - Map acknowledgeMessages - ) { - - this.acknowledged = acknowledged; - this.trialWasStarted = trialWasStarted; - this.licenseType = licenseType; - this.errorMessage = errorMessage; - this.acknowledgeHeader = acknowledgeHeader; - this.acknowledgeMessages = acknowledgeMessages; - } - - /** - * Returns true if the request that corresponds to this response acknowledged license changes that would occur as a result of starting - * a trial license - */ - public boolean isAcknowledged() { - return acknowledged; - } - - /** - * Returns true if a trial license was started as a result of the request corresponding to this response. Returns false if the cluster - * did not start a trial, or a trial had already been started before the corresponding request was made - */ - public boolean isTrialWasStarted() { - return trialWasStarted; - } - - /** - * If a trial license was started as a result of the request corresponding to this response (see {@link #isTrialWasStarted()}) then - * returns the type of license that was started on the cluster. Returns null otherwise - */ - public String getLicenseType() { - return licenseType; - } - - /** - * If a trial license was not started as a result of the request corresponding to this response (see {@link #isTrialWasStarted()} then - * returns a brief message explaining why the trial could not be started. Returns false otherwise - */ - public String getErrorMessage() { - return errorMessage; - } - - /** - * If the request corresponding to this response did not acknowledge licensing changes that would result from starting a trial license - * (see {@link #isAcknowledged()}), returns a message describing how the user must acknowledge licensing changes as a result of - * such a request. Returns null otherwise - */ - public String getAcknowledgeHeader() { - return acknowledgeHeader; - } - - /** - * If the request corresponding to this response did not acknowledge licensing changes that would result from starting a trial license - * (see {@link #isAcknowledged()}, returns a map. The map's keys are names of commercial Elasticsearch features, and their values are - * messages about how those features will be affected by licensing changes as a result of starting a trial license - */ - public Map getAcknowledgeMessages() { - return acknowledgeMessages; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/license/package-info.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/license/package-info.java deleted file mode 100644 index 511a8ddf68350..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/license/package-info.java +++ /dev/null @@ -1,13 +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. - */ - -/** - * Request and Response objects for the default distribution's License - * APIs. - */ -package org.elasticsearch.client.license; diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/DeleteRollupJobRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/DeleteRollupJobRequest.java deleted file mode 100644 index 4d03176edd391..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/DeleteRollupJobRequest.java +++ /dev/null @@ -1,38 +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.rollup; - -import org.elasticsearch.client.Validatable; - -import java.util.Objects; - -public class DeleteRollupJobRequest implements Validatable { - - private final String id; - - public DeleteRollupJobRequest(String id) { - this.id = Objects.requireNonNull(id, "id parameter must not be null"); - } - - public String getId() { - return id; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - DeleteRollupJobRequest that = (DeleteRollupJobRequest) o; - return Objects.equals(id, that.id); - } - - @Override - public int hashCode() { - return Objects.hash(id); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/GetRollupCapsRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/GetRollupCapsRequest.java deleted file mode 100644 index fe05f37e49369..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/GetRollupCapsRequest.java +++ /dev/null @@ -1,48 +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.rollup; - -import org.elasticsearch.client.Validatable; -import org.elasticsearch.cluster.metadata.Metadata; -import org.elasticsearch.common.Strings; - -import java.util.Objects; - -public class GetRollupCapsRequest implements Validatable { - - private final String indexPattern; - - public GetRollupCapsRequest(final String indexPattern) { - if (Strings.isNullOrEmpty(indexPattern) || indexPattern.equals("*")) { - this.indexPattern = Metadata.ALL; - } else { - this.indexPattern = indexPattern; - } - } - - public String getIndexPattern() { - return indexPattern; - } - - @Override - public int hashCode() { - return Objects.hash(indexPattern); - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - GetRollupCapsRequest other = (GetRollupCapsRequest) obj; - return Objects.equals(indexPattern, other.indexPattern); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/GetRollupCapsResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/GetRollupCapsResponse.java deleted file mode 100644 index a4f501307674b..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/GetRollupCapsResponse.java +++ /dev/null @@ -1,62 +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.rollup; - -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; - -public class GetRollupCapsResponse { - - private final Map jobs; - - public GetRollupCapsResponse(final Map jobs) { - this.jobs = Collections.unmodifiableMap(Objects.requireNonNull(jobs)); - } - - public Map getJobs() { - return jobs; - } - - public static GetRollupCapsResponse fromXContent(final XContentParser parser) throws IOException { - Map jobs = new HashMap<>(); - XContentParser.Token token = parser.nextToken(); - if (token.equals(XContentParser.Token.START_OBJECT)) { - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token.equals(XContentParser.Token.FIELD_NAME)) { - String pattern = parser.currentName(); - - RollableIndexCaps cap = RollableIndexCaps.PARSER.parse(parser, pattern); - jobs.put(pattern, cap); - } - } - } - return new GetRollupCapsResponse(jobs); - } - - @Override - public int hashCode() { - return Objects.hash(jobs); - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - GetRollupCapsResponse other = (GetRollupCapsResponse) obj; - return Objects.equals(jobs, other.jobs); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/GetRollupIndexCapsRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/GetRollupIndexCapsRequest.java deleted file mode 100644 index 351e648fe5dd0..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/GetRollupIndexCapsRequest.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.rollup; - -import org.elasticsearch.action.support.IndicesOptions; -import org.elasticsearch.client.Validatable; -import org.elasticsearch.common.Strings; - -import java.util.Arrays; -import java.util.Objects; - -public class GetRollupIndexCapsRequest implements Validatable { - - private String[] indices; - private IndicesOptions options; - - public GetRollupIndexCapsRequest(final String... indices) { - this(indices, IndicesOptions.STRICT_EXPAND_OPEN_FORBID_CLOSED); - } - - public GetRollupIndexCapsRequest(final String[] indices, final IndicesOptions options) { - if (indices == null || indices.length == 0) { - throw new IllegalArgumentException("[indices] must not be null or empty"); - } - for (String index : indices) { - if (Strings.isNullOrEmpty(index)) { - throw new IllegalArgumentException("[index] must not be null or empty"); - } - } - this.indices = indices; - this.options = Objects.requireNonNull(options); - } - - public IndicesOptions indicesOptions() { - return options; - } - - public String[] indices() { - return indices; - } - - @Override - public int hashCode() { - return Objects.hash(Arrays.hashCode(indices), options); - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - GetRollupIndexCapsRequest other = (GetRollupIndexCapsRequest) obj; - return Arrays.equals(indices, other.indices) && Objects.equals(options, other.options); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/GetRollupIndexCapsResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/GetRollupIndexCapsResponse.java deleted file mode 100644 index 8dc64add9ac7a..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/GetRollupIndexCapsResponse.java +++ /dev/null @@ -1,62 +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.rollup; - -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; - -public class GetRollupIndexCapsResponse { - - private final Map jobs; - - public GetRollupIndexCapsResponse(final Map jobs) { - this.jobs = Collections.unmodifiableMap(Objects.requireNonNull(jobs)); - } - - public Map getJobs() { - return jobs; - } - - public static GetRollupIndexCapsResponse fromXContent(final XContentParser parser) throws IOException { - Map jobs = new HashMap<>(); - XContentParser.Token token = parser.nextToken(); - if (token.equals(XContentParser.Token.START_OBJECT)) { - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token.equals(XContentParser.Token.FIELD_NAME)) { - String pattern = parser.currentName(); - - RollableIndexCaps cap = RollableIndexCaps.PARSER.apply(parser, pattern); - jobs.put(pattern, cap); - } - } - } - return new GetRollupIndexCapsResponse(jobs); - } - - @Override - public int hashCode() { - return Objects.hash(jobs); - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - GetRollupIndexCapsResponse other = (GetRollupIndexCapsResponse) obj; - return Objects.equals(jobs, other.jobs); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/GetRollupJobRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/GetRollupJobRequest.java deleted file mode 100644 index df51487f8d3dd..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/GetRollupJobRequest.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.rollup; - -import org.elasticsearch.client.Validatable; -import org.elasticsearch.client.ValidationException; - -import java.util.Objects; -import java.util.Optional; - -/** - * Request to fetch rollup jobs. - */ -public class GetRollupJobRequest implements Validatable { - private final String jobId; - - /** - * Create a requets . - * @param jobId id of the job to return or {@code _all} to return all jobs - */ - public GetRollupJobRequest(final String jobId) { - Objects.requireNonNull(jobId, "jobId is required"); - if ("_all".equals(jobId)) { - throw new IllegalArgumentException("use the default ctor to ask for all jobs"); - } - this.jobId = jobId; - } - - /** - * Create a request to load all rollup jobs. - */ - public GetRollupJobRequest() { - this.jobId = "_all"; - } - - /** - * ID of the job to return. - */ - public String getJobId() { - return jobId; - } - - @Override - public Optional validate() { - return Optional.empty(); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - final GetRollupJobRequest that = (GetRollupJobRequest) o; - return jobId.equals(that.jobId); - } - - @Override - public int hashCode() { - return Objects.hash(jobId); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/GetRollupJobResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/GetRollupJobResponse.java deleted file mode 100644 index 6aebeab9ca4d4..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/GetRollupJobResponse.java +++ /dev/null @@ -1,300 +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.rollup; - -import org.elasticsearch.client.core.IndexerJobStats; -import org.elasticsearch.client.core.IndexerState; -import org.elasticsearch.client.rollup.job.config.RollupJobConfig; -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.List; -import java.util.Map; -import java.util.Objects; - -import static java.util.Collections.unmodifiableList; -import static java.util.stream.Collectors.joining; -import static org.elasticsearch.xcontent.ConstructingObjectParser.constructorArg; -import static org.elasticsearch.xcontent.ConstructingObjectParser.optionalConstructorArg; - -/** - * Response from rollup's get jobs api. - */ -public class GetRollupJobResponse { - static final ParseField JOBS = new ParseField("jobs"); - static final ParseField CONFIG = new ParseField("config"); - static final ParseField STATS = new ParseField("stats"); - static final ParseField STATUS = new ParseField("status"); - static final ParseField STATE = new ParseField("job_state"); - static final ParseField CURRENT_POSITION = new ParseField("current_position"); - static final ParseField ROLLUPS_INDEXED = new ParseField("rollups_indexed"); - private static final ParseField UPGRADED_DOC_ID = new ParseField("upgraded_doc_id"); - - private List jobs; - - GetRollupJobResponse(final List jobs) { - this.jobs = Objects.requireNonNull(jobs, "jobs is required"); - } - - /** - * Jobs returned by the request. - */ - public List getJobs() { - return jobs; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - final GetRollupJobResponse that = (GetRollupJobResponse) o; - return jobs.equals(that.jobs); - } - - @Override - public int hashCode() { - return Objects.hash(jobs); - } - - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "get_rollup_job_response", - true, - args -> { - @SuppressWarnings("unchecked") // We're careful about the type in the list - List jobs = (List) args[0]; - return new GetRollupJobResponse(unmodifiableList(jobs)); - } - ); - static { - PARSER.declareObjectArray(constructorArg(), JobWrapper.PARSER::apply, JOBS); - } - - public static GetRollupJobResponse fromXContent(final XContentParser parser) throws IOException { - return PARSER.parse(parser, null); - } - - @Override - public final String toString() { - return "{jobs=" + jobs.stream().map(Object::toString).collect(joining("\n")) + "\n}"; - } - - public static class JobWrapper { - private final RollupJobConfig job; - private final RollupIndexerJobStats stats; - private final RollupJobStatus status; - - JobWrapper(RollupJobConfig job, RollupIndexerJobStats stats, RollupJobStatus status) { - this.job = job; - this.stats = stats; - this.status = status; - } - - /** - * Configuration of the job. - */ - public RollupJobConfig getJob() { - return job; - } - - /** - * Statistics about the execution of the job. - */ - public RollupIndexerJobStats getStats() { - return stats; - } - - /** - * Current state of the job. - */ - public RollupJobStatus getStatus() { - return status; - } - - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "job", - true, - a -> new JobWrapper((RollupJobConfig) a[0], (RollupIndexerJobStats) a[1], (RollupJobStatus) a[2]) - ); - static { - PARSER.declareObject(ConstructingObjectParser.constructorArg(), (p, c) -> RollupJobConfig.fromXContent(p, null), CONFIG); - PARSER.declareObject(ConstructingObjectParser.constructorArg(), RollupIndexerJobStats.PARSER::apply, STATS); - PARSER.declareObject(ConstructingObjectParser.constructorArg(), RollupJobStatus.PARSER::apply, STATUS); - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - JobWrapper other = (JobWrapper) obj; - return Objects.equals(job, other.job) && Objects.equals(stats, other.stats) && Objects.equals(status, other.status); - } - - @Override - public int hashCode() { - return Objects.hash(job, stats, status); - } - - @Override - public final String toString() { - return "{job=" + job + ", stats=" + stats + ", status=" + status + "}"; - } - } - - /** - * The Rollup specialization of stats for the AsyncTwoPhaseIndexer. - * Note: instead of `documents_indexed`, this XContent show `rollups_indexed` - */ - public static class RollupIndexerJobStats extends IndexerJobStats { - - RollupIndexerJobStats( - long numPages, - long numInputDocuments, - long numOuputDocuments, - long numInvocations, - long indexTime, - long indexTotal, - long searchTime, - long searchTotal, - long processingTime, - long processingTotal, - long indexFailures, - long searchFailures - ) { - super( - numPages, - numInputDocuments, - numOuputDocuments, - numInvocations, - indexTime, - searchTime, - processingTime, - indexTotal, - searchTotal, - processingTotal, - indexFailures, - searchFailures - ); - } - - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - STATS.getPreferredName(), - true, - args -> new RollupIndexerJobStats( - (long) args[0], - (long) args[1], - (long) args[2], - (long) args[3], - (long) args[4], - (long) args[5], - (long) args[6], - (long) args[7], - (long) args[8], - (long) args[9], - (long) args[10], - (long) args[11] - ) - ); - static { - PARSER.declareLong(constructorArg(), NUM_PAGES); - PARSER.declareLong(constructorArg(), NUM_INPUT_DOCUMENTS); - PARSER.declareLong(constructorArg(), ROLLUPS_INDEXED); - PARSER.declareLong(constructorArg(), NUM_INVOCATIONS); - PARSER.declareLong(constructorArg(), INDEX_TIME_IN_MS); - PARSER.declareLong(constructorArg(), INDEX_TOTAL); - PARSER.declareLong(constructorArg(), SEARCH_TIME_IN_MS); - PARSER.declareLong(constructorArg(), SEARCH_TOTAL); - PARSER.declareLong(constructorArg(), PROCESSING_TIME_IN_MS); - PARSER.declareLong(constructorArg(), PROCESSING_TOTAL); - PARSER.declareLong(constructorArg(), INDEX_FAILURES); - PARSER.declareLong(constructorArg(), SEARCH_FAILURES); - } - } - - /** - * Status of the rollup job. - */ - public static class RollupJobStatus { - private final IndexerState state; - private final Map currentPosition; - - RollupJobStatus(IndexerState state, Map position) { - this.state = state; - this.currentPosition = position; - } - - /** - * The state of the writer. - */ - public IndexerState getState() { - return state; - } - - /** - * The current position of the writer. - */ - public Map getCurrentPosition() { - return currentPosition; - } - - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - STATUS.getPreferredName(), - true, - args -> { - IndexerState state = (IndexerState) args[0]; - @SuppressWarnings("unchecked") // We're careful of the contents - Map currentPosition = (Map) args[1]; - return new RollupJobStatus(state, currentPosition); - } - ); - static { - PARSER.declareField(constructorArg(), p -> IndexerState.fromString(p.text()), STATE, ObjectParser.ValueType.STRING); - PARSER.declareField(optionalConstructorArg(), p -> { - if (p.currentToken() == XContentParser.Token.START_OBJECT) { - return p.map(); - } - if (p.currentToken() == XContentParser.Token.VALUE_NULL) { - return null; - } - throw new IllegalArgumentException("Unsupported token [" + p.currentToken() + "]"); - }, CURRENT_POSITION, ObjectParser.ValueType.VALUE_OBJECT_ARRAY); - - // Optional to accommodate old versions of state, not used - PARSER.declareBoolean(ConstructingObjectParser.optionalConstructorArg(), UPGRADED_DOC_ID); - } - - @Override - public boolean equals(Object other) { - if (this == other) return true; - if (other == null || getClass() != other.getClass()) return false; - RollupJobStatus that = (RollupJobStatus) other; - return Objects.equals(state, that.state) && Objects.equals(currentPosition, that.currentPosition); - } - - @Override - public int hashCode() { - return Objects.hash(state, currentPosition); - } - - @Override - public final String toString() { - return "{stats=" + state + ", currentPosition=" + currentPosition + "}"; - } - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/PutRollupJobRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/PutRollupJobRequest.java deleted file mode 100644 index 130b226e66c95..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/PutRollupJobRequest.java +++ /dev/null @@ -1,54 +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.rollup; - -import org.elasticsearch.client.Validatable; -import org.elasticsearch.client.ValidationException; -import org.elasticsearch.client.rollup.job.config.RollupJobConfig; -import org.elasticsearch.xcontent.ToXContentObject; -import org.elasticsearch.xcontent.XContentBuilder; - -import java.io.IOException; -import java.util.Objects; -import java.util.Optional; - -public class PutRollupJobRequest implements Validatable, ToXContentObject { - - private final RollupJobConfig config; - - public PutRollupJobRequest(final RollupJobConfig config) { - this.config = Objects.requireNonNull(config, "rollup job configuration is required"); - } - - public RollupJobConfig getConfig() { - return config; - } - - @Override - public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - return config.toXContent(builder, params); - } - - @Override - public Optional validate() { - return config.validate(); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - final PutRollupJobRequest that = (PutRollupJobRequest) o; - return Objects.equals(config, that.config); - } - - @Override - public int hashCode() { - return Objects.hash(config); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/RollableIndexCaps.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/RollableIndexCaps.java deleted file mode 100644 index 9a3fef50cb56f..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/RollableIndexCaps.java +++ /dev/null @@ -1,93 +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.rollup; - -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.ToXContentFragment; -import org.elasticsearch.xcontent.XContentBuilder; - -import java.io.IOException; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.Objects; -import java.util.stream.Collectors; - -import static org.elasticsearch.xcontent.ConstructingObjectParser.constructorArg; - -/** - * Represents the rollup capabilities of a non-rollup index. E.g. what values/aggregations - * were rolled up for this index, in what rollup jobs that data is stored and where those - * concrete rollup indices exist - * - * The index name can either be a single index, or an index pattern (logstash-*) - */ -public class RollableIndexCaps implements ToXContentFragment { - private static final ParseField ROLLUP_JOBS = new ParseField("rollup_jobs"); - - public static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - ROLLUP_JOBS.getPreferredName(), - true, - (Object[] args, String indexName) -> { - @SuppressWarnings("unchecked") - var caps = (List) args[0]; - return new RollableIndexCaps(indexName, caps); - } - ); - static { - PARSER.declareObjectArray(constructorArg(), (p, name) -> RollupJobCaps.PARSER.parse(p, null), ROLLUP_JOBS); - } - - private final String indexName; - private final List jobCaps; - - RollableIndexCaps(final String indexName, final List caps) { - this.indexName = indexName; - this.jobCaps = Collections.unmodifiableList( - Objects.requireNonNull(caps).stream().sorted(Comparator.comparing(RollupJobCaps::getJobID)).collect(Collectors.toList()) - ); - } - - public String getIndexName() { - return indexName; - } - - public List getJobCaps() { - return jobCaps; - } - - @Override - public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(indexName); - { - builder.field(ROLLUP_JOBS.getPreferredName(), jobCaps); - } - builder.endObject(); - return builder; - } - - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - - if (other == null || getClass() != other.getClass()) { - return false; - } - - RollableIndexCaps that = (RollableIndexCaps) other; - return Objects.equals(this.jobCaps, that.jobCaps) && Objects.equals(this.indexName, that.indexName); - } - - @Override - public int hashCode() { - return Objects.hash(jobCaps, indexName); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/RollupJobCaps.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/RollupJobCaps.java deleted file mode 100644 index 6a9abb76de092..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/RollupJobCaps.java +++ /dev/null @@ -1,179 +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.rollup; - -import org.elasticsearch.core.Tuple; -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.ToXContentFragment; -import org.elasticsearch.xcontent.ToXContentObject; -import org.elasticsearch.xcontent.XContentBuilder; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.stream.Collectors; - -/** - * Represents the Rollup capabilities for a specific job on a single rollup index - */ -public class RollupJobCaps implements ToXContentObject { - private static final ParseField JOB_ID = new ParseField("job_id"); - private static final ParseField ROLLUP_INDEX = new ParseField("rollup_index"); - private static final ParseField INDEX_PATTERN = new ParseField("index_pattern"); - private static final ParseField FIELDS = new ParseField("fields"); - private static final String NAME = "rollup_job_caps"; - - public static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>(NAME, true, a -> { - @SuppressWarnings("unchecked") - List> caps = (List>) a[3]; - Map mapCaps = new HashMap<>(caps.stream().collect(Collectors.toMap(Tuple::v1, Tuple::v2))); - return new RollupJobCaps((String) a[0], (String) a[1], (String) a[2], mapCaps); - }); - - static { - PARSER.declareString(ConstructingObjectParser.constructorArg(), JOB_ID); - PARSER.declareString(ConstructingObjectParser.constructorArg(), ROLLUP_INDEX); - PARSER.declareString(ConstructingObjectParser.constructorArg(), INDEX_PATTERN); - PARSER.declareNamedObjects( - ConstructingObjectParser.constructorArg(), - (p, c, name) -> new Tuple<>(name, RollupFieldCaps.fromXContent(p)), - FIELDS - ); - } - - private final String jobID; - private final String rollupIndex; - private final String indexPattern; - private final Map fieldCapLookup; - - RollupJobCaps( - final String jobID, - final String rollupIndex, - final String indexPattern, - final Map fieldCapLookup - ) { - this.jobID = jobID; - this.rollupIndex = rollupIndex; - this.indexPattern = indexPattern; - this.fieldCapLookup = Collections.unmodifiableMap(Objects.requireNonNull(fieldCapLookup)); - } - - public Map getFieldCaps() { - return fieldCapLookup; - } - - public String getRollupIndex() { - return rollupIndex; - } - - public String getIndexPattern() { - return indexPattern; - } - - public String getJobID() { - return jobID; - } - - @Override - public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(); - { - builder.field(JOB_ID.getPreferredName(), jobID); - builder.field(ROLLUP_INDEX.getPreferredName(), rollupIndex); - builder.field(INDEX_PATTERN.getPreferredName(), indexPattern); - builder.startObject(FIELDS.getPreferredName()); - { - for (Map.Entry fieldCap : fieldCapLookup.entrySet()) { - builder.array(fieldCap.getKey(), fieldCap.getValue()); - } - } - builder.endObject(); - } - builder.endObject(); - return builder; - } - - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - - if (other == null || getClass() != other.getClass()) { - return false; - } - - RollupJobCaps that = (RollupJobCaps) other; - - return Objects.equals(this.jobID, that.jobID) - && Objects.equals(this.indexPattern, that.indexPattern) - && Objects.equals(this.rollupIndex, that.rollupIndex) - && Objects.equals(this.fieldCapLookup, that.fieldCapLookup); - } - - @Override - public int hashCode() { - return Objects.hash(jobID, rollupIndex, fieldCapLookup, indexPattern); - } - - public static class RollupFieldCaps implements ToXContentFragment { - private static final String NAME = "rollup_field_caps"; - private final List> aggs; - - RollupFieldCaps(final List> aggs) { - this.aggs = Collections.unmodifiableList(Objects.requireNonNull(aggs)); - } - - public List> getAggs() { - return aggs; - } - - @Override - public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - for (Map agg : aggs) { - builder.map(agg); - } - return builder; - } - - public static RollupFieldCaps fromXContent(XContentParser parser) throws IOException { - List> aggs = new ArrayList<>(); - if (parser.nextToken().equals(XContentParser.Token.START_ARRAY)) { - while (parser.nextToken().equals(XContentParser.Token.START_OBJECT)) { - aggs.add(parser.map()); - } - } - return new RollupFieldCaps(aggs); - } - - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - - if (other == null || getClass() != other.getClass()) { - return false; - } - - RollupFieldCaps that = (RollupFieldCaps) other; - return Objects.equals(this.aggs, that.aggs); - } - - @Override - public int hashCode() { - return Objects.hash(aggs); - } - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/StartRollupJobRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/StartRollupJobRequest.java deleted file mode 100644 index ab428ebc167f1..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/StartRollupJobRequest.java +++ /dev/null @@ -1,38 +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.rollup; - -import org.elasticsearch.client.Validatable; - -import java.util.Objects; - -public class StartRollupJobRequest implements Validatable { - - private final String jobId; - - public StartRollupJobRequest(final String jobId) { - this.jobId = Objects.requireNonNull(jobId, "id parameter must not be null"); - } - - public String getJobId() { - return jobId; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - final StartRollupJobRequest that = (StartRollupJobRequest) o; - return Objects.equals(jobId, that.jobId); - } - - @Override - public int hashCode() { - return Objects.hash(jobId); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/StartRollupJobResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/StartRollupJobResponse.java deleted file mode 100644 index 3c56eff4415c9..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/StartRollupJobResponse.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.rollup; - -import org.elasticsearch.client.core.AcknowledgedResponse; -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; - -public class StartRollupJobResponse extends AcknowledgedResponse { - - private static final String PARSE_FIELD_NAME = "started"; - - private static final ConstructingObjectParser PARSER = AcknowledgedResponse.generateParser( - "start_rollup_job_response", - StartRollupJobResponse::new, - PARSE_FIELD_NAME - ); - - public StartRollupJobResponse(boolean acknowledged) { - super(acknowledged); - } - - public static StartRollupJobResponse fromXContent(final XContentParser parser) throws IOException { - return PARSER.parse(parser, null); - } - - @Override - protected String getFieldName() { - return PARSE_FIELD_NAME; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/StopRollupJobRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/StopRollupJobRequest.java deleted file mode 100644 index c3f66863a6940..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/StopRollupJobRequest.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.rollup; - -import org.elasticsearch.client.Validatable; -import org.elasticsearch.core.TimeValue; - -import java.util.Objects; - -public class StopRollupJobRequest implements Validatable { - - private final String jobId; - private TimeValue timeout; - private Boolean waitForCompletion; - - public StopRollupJobRequest(final String jobId) { - this.jobId = Objects.requireNonNull(jobId, "id parameter must not be null"); - } - - public String getJobId() { - return jobId; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - final StopRollupJobRequest that = (StopRollupJobRequest) o; - return Objects.equals(jobId, that.jobId); - } - - @Override - public int hashCode() { - return Objects.hash(jobId); - } - - /** - * Sets the requests optional "timeout" parameter. - */ - public void timeout(TimeValue timeout) { - this.timeout = timeout; - } - - public TimeValue timeout() { - return this.timeout; - } - - /** - * Sets the requests optional "wait_for_completion". - */ - public void waitForCompletion(boolean waitForCompletion) { - this.waitForCompletion = waitForCompletion; - } - - public Boolean waitForCompletion() { - return this.waitForCompletion; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/StopRollupJobResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/StopRollupJobResponse.java deleted file mode 100644 index 4f2daecee494c..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/StopRollupJobResponse.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.rollup; - -import org.elasticsearch.client.core.AcknowledgedResponse; -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; - -public class StopRollupJobResponse extends AcknowledgedResponse { - - private static final String PARSE_FIELD_NAME = "stopped"; - - private static final ConstructingObjectParser PARSER = AcknowledgedResponse.generateParser( - "stop_rollup_job_response", - StopRollupJobResponse::new, - PARSE_FIELD_NAME - ); - - public StopRollupJobResponse(boolean acknowledged) { - super(acknowledged); - } - - public static StopRollupJobResponse fromXContent(final XContentParser parser) throws IOException { - return PARSER.parse(parser, null); - } - - @Override - protected String getFieldName() { - return PARSE_FIELD_NAME; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/job/config/DateHistogramGroupConfig.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/job/config/DateHistogramGroupConfig.java deleted file mode 100644 index 266f0d5bc0fc0..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/job/config/DateHistogramGroupConfig.java +++ /dev/null @@ -1,303 +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.rollup.job.config; - -import org.elasticsearch.client.Validatable; -import org.elasticsearch.client.ValidationException; -import org.elasticsearch.core.Nullable; -import org.elasticsearch.core.TimeValue; -import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval; -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.ToXContentObject; -import org.elasticsearch.xcontent.XContentBuilder; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.time.ZoneId; -import java.util.Collections; -import java.util.HashSet; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; - -import static org.elasticsearch.xcontent.ConstructingObjectParser.constructorArg; -import static org.elasticsearch.xcontent.ConstructingObjectParser.optionalConstructorArg; -import static org.elasticsearch.xcontent.ObjectParser.ValueType; - -/** - * The configuration object for the histograms in the rollup config - * - * { - * "groups": [ - * "date_histogram": { - * "field" : "foo", - * "interval" : "1d", - * "delay": "30d", - * "time_zone" : "EST" - * } - * ] - * } - */ -public class DateHistogramGroupConfig implements Validatable, ToXContentObject { - - static final String NAME = "date_histogram"; - private static final String INTERVAL = "interval"; - private static final String FIELD = "field"; - private static final String TIME_ZONE = "time_zone"; - private static final String DELAY = "delay"; - private static final String DEFAULT_TIMEZONE = "UTC"; - private static final String CALENDAR_INTERVAL = "calendar_interval"; - private static final String FIXED_INTERVAL = "fixed_interval"; - - // From DateHistogramAggregationBuilder in core, transplanted and modified to a set - // so we don't need to import a dependency on the class - private static final Set DATE_FIELD_UNITS; - static { - Set dateFieldUnits = new HashSet<>(); - dateFieldUnits.add("year"); - dateFieldUnits.add("1y"); - dateFieldUnits.add("quarter"); - dateFieldUnits.add("1q"); - dateFieldUnits.add("month"); - dateFieldUnits.add("1M"); - dateFieldUnits.add("week"); - dateFieldUnits.add("1w"); - dateFieldUnits.add("day"); - dateFieldUnits.add("1d"); - dateFieldUnits.add("hour"); - dateFieldUnits.add("1h"); - dateFieldUnits.add("minute"); - dateFieldUnits.add("1m"); - dateFieldUnits.add("second"); - dateFieldUnits.add("1s"); - DATE_FIELD_UNITS = Collections.unmodifiableSet(dateFieldUnits); - } - - private static final ConstructingObjectParser PARSER; - static { - PARSER = new ConstructingObjectParser<>(NAME, true, a -> { - DateHistogramInterval oldInterval = (DateHistogramInterval) a[1]; - DateHistogramInterval calendarInterval = (DateHistogramInterval) a[2]; - DateHistogramInterval fixedInterval = (DateHistogramInterval) a[3]; - - if (oldInterval != null) { - if (calendarInterval != null || fixedInterval != null) { - throw new IllegalArgumentException( - "Cannot use [interval] with [fixed_interval] or [calendar_interval] " + "configuration options." - ); - } - return new DateHistogramGroupConfig((String) a[0], oldInterval, (DateHistogramInterval) a[4], (String) a[5]); - } else if (calendarInterval != null && fixedInterval == null) { - return new CalendarInterval((String) a[0], calendarInterval, (DateHistogramInterval) a[4], (String) a[5]); - } else if (calendarInterval == null && fixedInterval != null) { - return new FixedInterval((String) a[0], fixedInterval, (DateHistogramInterval) a[4], (String) a[5]); - } else if (calendarInterval != null && fixedInterval != null) { - throw new IllegalArgumentException("Cannot set both [fixed_interval] and [calendar_interval] at the same time"); - } else { - throw new IllegalArgumentException("An interval is required. Use [fixed_interval] or [calendar_interval]."); - } - }); - PARSER.declareString(constructorArg(), new ParseField(FIELD)); - PARSER.declareField(optionalConstructorArg(), p -> new DateHistogramInterval(p.text()), new ParseField(INTERVAL), ValueType.STRING); - PARSER.declareField( - optionalConstructorArg(), - p -> new DateHistogramInterval(p.text()), - new ParseField(CALENDAR_INTERVAL), - ValueType.STRING - ); - PARSER.declareField( - optionalConstructorArg(), - p -> new DateHistogramInterval(p.text()), - new ParseField(FIXED_INTERVAL), - ValueType.STRING - ); - PARSER.declareField(optionalConstructorArg(), p -> new DateHistogramInterval(p.text()), new ParseField(DELAY), ValueType.STRING); - PARSER.declareString(optionalConstructorArg(), new ParseField(TIME_ZONE)); - } - - private final String field; - private final DateHistogramInterval interval; - private final DateHistogramInterval delay; - private final String timeZone; - - /** - * FixedInterval is a {@link DateHistogramGroupConfig} that uses a fixed time interval for rolling up data. - * The fixed time interval is one or multiples of SI units and has no calendar-awareness (e.g. doesn't account - * for leap corrections, does not have variable length months, etc). - * - * For calendar-aware rollups, use {@link CalendarInterval} - */ - public static class FixedInterval extends DateHistogramGroupConfig { - public FixedInterval(String field, DateHistogramInterval interval) { - this(field, interval, null, null); - } - - public FixedInterval(String field, DateHistogramInterval interval, DateHistogramInterval delay, String timeZone) { - super(field, interval, delay, timeZone); - // validate fixed time - TimeValue.parseTimeValue(interval.toString(), NAME + ".FixedInterval"); - } - } - - /** - * CalendarInterval is a {@link DateHistogramGroupConfig} that uses calendar-aware intervals for rolling up data. - * Calendar time intervals understand leap corrections and contextual differences in certain calendar units (e.g. - * months are variable length depending on the month). Calendar units are only available in singular quantities: - * 1s, 1m, 1h, 1d, 1w, 1q, 1M, 1y - * - * For fixed time rollups, use {@link FixedInterval} - */ - public static class CalendarInterval extends DateHistogramGroupConfig { - public CalendarInterval(String field, DateHistogramInterval interval) { - this(field, interval, null, null); - - } - - public CalendarInterval(String field, DateHistogramInterval interval, DateHistogramInterval delay, String timeZone) { - super(field, interval, delay, timeZone); - if (DATE_FIELD_UNITS.contains(interval.toString()) == false) { - throw new IllegalArgumentException( - "The supplied interval [" + interval + "] could not be parsed " + "as a calendar interval." - ); - } - } - - } - - /** - * Create a new {@link DateHistogramGroupConfig} using the given field and interval parameters. - * - * @deprecated Build a DateHistoConfig using {@link DateHistogramGroupConfig.CalendarInterval} - * or {@link DateHistogramGroupConfig.FixedInterval} instead - * - * @since 7.2.0 - */ - @Deprecated - public DateHistogramGroupConfig(final String field, final DateHistogramInterval interval) { - this(field, interval, null, null); - } - - /** - * Create a new {@link DateHistogramGroupConfig} using the given configuration parameters. - *

- * The {@code field} and {@code interval} are required to compute the date histogram for the rolled up documents. - * The {@code delay} is optional and can be set to {@code null}. It defines how long to wait before rolling up new documents. - * The {@code timeZone} is optional and can be set to {@code null}. When configured, the time zone value is resolved using - * ({@link ZoneId#of(String)} and must match a time zone identifier provided by the Joda Time library. - *

- * @param field the name of the date field to use for the date histogram (required) - * @param interval the interval to use for the date histogram (required) - * @param delay the time delay (optional) - * @param timeZone the id of time zone to use to calculate the date histogram (optional). When {@code null}, the UTC timezone is used. - * - * @deprecated Build a DateHistoConfig using {@link DateHistogramGroupConfig.CalendarInterval} - * or {@link DateHistogramGroupConfig.FixedInterval} instead - * - * @since 7.2.0 - */ - @Deprecated - public DateHistogramGroupConfig( - final String field, - final DateHistogramInterval interval, - final @Nullable DateHistogramInterval delay, - final @Nullable String timeZone - ) { - this.field = field; - this.interval = interval; - this.delay = delay; - this.timeZone = (timeZone != null && timeZone.isEmpty() == false) ? timeZone : DEFAULT_TIMEZONE; - } - - @Override - public Optional validate() { - final ValidationException validationException = new ValidationException(); - if (field == null || field.isEmpty()) { - validationException.addValidationError("Field name is required"); - } - if (interval == null) { - validationException.addValidationError("Interval is required"); - } - if (validationException.validationErrors().isEmpty()) { - return Optional.empty(); - } - return Optional.of(validationException); - } - - /** - * Get the date field - */ - public String getField() { - return field; - } - - /** - * Get the date interval - */ - public DateHistogramInterval getInterval() { - return interval; - } - - /** - * Get the time delay for this histogram - */ - public DateHistogramInterval getDelay() { - return delay; - } - - /** - * Get the timezone to apply - */ - public String getTimeZone() { - return timeZone; - } - - @Override - public XContentBuilder toXContent(final XContentBuilder builder, final Params params) throws IOException { - builder.startObject(); - { - if (this.getClass().equals(CalendarInterval.class)) { - builder.field(CALENDAR_INTERVAL, interval.toString()); - } else if (this.getClass().equals(FixedInterval.class)) { - builder.field(FIXED_INTERVAL, interval.toString()); - } else { - builder.field(INTERVAL, interval.toString()); - } - builder.field(FIELD, field); - if (delay != null) { - builder.field(DELAY, delay.toString()); - } - builder.field(TIME_ZONE, timeZone); - } - return builder.endObject(); - } - - @Override - public boolean equals(final Object other) { - if (this == other) { - return true; - } - if (other == null || getClass() != other.getClass()) { - return false; - } - final DateHistogramGroupConfig that = (DateHistogramGroupConfig) other; - return Objects.equals(interval, that.interval) - && Objects.equals(field, that.field) - && Objects.equals(delay, that.delay) - && Objects.equals(timeZone, that.timeZone); - } - - @Override - public int hashCode() { - return Objects.hash(interval, field, delay, timeZone); - } - - public static DateHistogramGroupConfig fromXContent(final XContentParser parser) throws IOException { - return PARSER.parse(parser, null); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/job/config/GroupConfig.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/job/config/GroupConfig.java deleted file mode 100644 index fa700bb95d474..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/job/config/GroupConfig.java +++ /dev/null @@ -1,168 +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.rollup.job.config; - -import org.elasticsearch.client.Validatable; -import org.elasticsearch.client.ValidationException; -import org.elasticsearch.core.Nullable; -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.ToXContentObject; -import org.elasticsearch.xcontent.XContentBuilder; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.Objects; -import java.util.Optional; - -import static org.elasticsearch.xcontent.ConstructingObjectParser.constructorArg; -import static org.elasticsearch.xcontent.ConstructingObjectParser.optionalConstructorArg; - -/** - * The configuration object for the groups section in the rollup config. - * Basically just a wrapper for histo/date histo/terms objects - * - * { - * "groups": [ - * "date_histogram": {...}, - * "histogram" : {...}, - * "terms" : {...} - * ] - * } - */ -public class GroupConfig implements Validatable, ToXContentObject { - - static final String NAME = "groups"; - private static final ConstructingObjectParser PARSER; - static { - PARSER = new ConstructingObjectParser<>( - NAME, - true, - args -> new GroupConfig((DateHistogramGroupConfig) args[0], (HistogramGroupConfig) args[1], (TermsGroupConfig) args[2]) - ); - PARSER.declareObject( - constructorArg(), - (p, c) -> DateHistogramGroupConfig.fromXContent(p), - new ParseField(DateHistogramGroupConfig.NAME) - ); - PARSER.declareObject( - optionalConstructorArg(), - (p, c) -> HistogramGroupConfig.fromXContent(p), - new ParseField(HistogramGroupConfig.NAME) - ); - PARSER.declareObject(optionalConstructorArg(), (p, c) -> TermsGroupConfig.fromXContent(p), new ParseField(TermsGroupConfig.NAME)); - } - - private final DateHistogramGroupConfig dateHistogram; - private final @Nullable HistogramGroupConfig histogram; - private final @Nullable TermsGroupConfig terms; - - public GroupConfig(final DateHistogramGroupConfig dateHistogram) { - this(dateHistogram, null, null); - } - - public GroupConfig( - final DateHistogramGroupConfig dateHistogram, - final @Nullable HistogramGroupConfig histogram, - final @Nullable TermsGroupConfig terms - ) { - this.dateHistogram = dateHistogram; - this.histogram = histogram; - this.terms = terms; - } - - @Override - public Optional validate() { - final ValidationException validationException = new ValidationException(); - if (dateHistogram != null) { - final Optional dateHistogramValidationErrors = dateHistogram.validate(); - if (dateHistogramValidationErrors != null && dateHistogramValidationErrors.isPresent()) { - validationException.addValidationErrors(dateHistogramValidationErrors.get()); - } - } else { - validationException.addValidationError("Date histogram must not be null"); - } - if (histogram != null) { - final Optional histogramValidationErrors = histogram.validate(); - if (histogramValidationErrors != null && histogramValidationErrors.isPresent()) { - validationException.addValidationErrors(histogramValidationErrors.get()); - } - } - if (terms != null) { - final Optional termsValidationErrors = terms.validate(); - if (termsValidationErrors != null && termsValidationErrors.isPresent()) { - validationException.addValidationErrors(termsValidationErrors.get()); - } - } - if (validationException.validationErrors().isEmpty()) { - return Optional.empty(); - } - return Optional.of(validationException); - } - - /** - * @return the configuration of the date histogram - */ - public DateHistogramGroupConfig getDateHistogram() { - return dateHistogram; - } - - /** - * @return the configuration of the histogram - */ - @Nullable - public HistogramGroupConfig getHistogram() { - return histogram; - } - - /** - * @return the configuration of the terms - */ - @Nullable - public TermsGroupConfig getTerms() { - return terms; - } - - @Override - public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(); - { - builder.field(DateHistogramGroupConfig.NAME, dateHistogram); - if (histogram != null) { - builder.field(HistogramGroupConfig.NAME, histogram); - } - if (terms != null) { - builder.field(TermsGroupConfig.NAME, terms); - } - } - return builder.endObject(); - } - - @Override - public boolean equals(final Object other) { - if (this == other) { - return true; - } - if (other == null || getClass() != other.getClass()) { - return false; - } - final GroupConfig that = (GroupConfig) other; - return Objects.equals(dateHistogram, that.dateHistogram) - && Objects.equals(histogram, that.histogram) - && Objects.equals(terms, that.terms); - } - - @Override - public int hashCode() { - return Objects.hash(dateHistogram, histogram, terms); - } - - public static GroupConfig fromXContent(final XContentParser parser) throws IOException { - return PARSER.parse(parser, null); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/job/config/HistogramGroupConfig.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/job/config/HistogramGroupConfig.java deleted file mode 100644 index 68dfc2717b3c7..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/job/config/HistogramGroupConfig.java +++ /dev/null @@ -1,117 +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.rollup.job.config; - -import org.elasticsearch.client.Validatable; -import org.elasticsearch.client.ValidationException; -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.ToXContentObject; -import org.elasticsearch.xcontent.XContentBuilder; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; -import java.util.Optional; - -import static org.elasticsearch.xcontent.ConstructingObjectParser.constructorArg; - -/** - * The configuration object for the histograms in the rollup config - * - * { - * "groups": [ - * "histogram": { - * "fields" : [ "foo", "bar" ], - * "interval" : 123 - * } - * ] - * } - */ -public class HistogramGroupConfig implements Validatable, ToXContentObject { - - static final String NAME = "histogram"; - private static final String INTERVAL = "interval"; - private static final String FIELDS = "fields"; - - private static final ConstructingObjectParser PARSER; - static { - PARSER = new ConstructingObjectParser<>(NAME, true, args -> { - @SuppressWarnings("unchecked") - List fields = (List) args[1]; - return new HistogramGroupConfig((long) args[0], fields != null ? fields.toArray(new String[fields.size()]) : null); - }); - PARSER.declareLong(constructorArg(), new ParseField(INTERVAL)); - PARSER.declareStringArray(constructorArg(), new ParseField(FIELDS)); - } - - private final long interval; - private final String[] fields; - - public HistogramGroupConfig(final long interval, final String... fields) { - this.interval = interval; - this.fields = fields; - } - - @Override - public Optional validate() { - final ValidationException validationException = new ValidationException(); - if (fields == null || fields.length == 0) { - validationException.addValidationError("Fields must have at least one value"); - } - if (interval <= 0) { - validationException.addValidationError("Interval must be a positive long"); - } - if (validationException.validationErrors().isEmpty()) { - return Optional.empty(); - } - return Optional.of(validationException); - } - - public long getInterval() { - return interval; - } - - public String[] getFields() { - return fields; - } - - @Override - public XContentBuilder toXContent(final XContentBuilder builder, final Params params) throws IOException { - builder.startObject(); - { - builder.field(INTERVAL, interval); - builder.field(FIELDS, fields); - } - builder.endObject(); - return builder; - } - - @Override - public boolean equals(final Object other) { - if (this == other) { - return true; - } - if (other == null || getClass() != other.getClass()) { - return false; - } - final HistogramGroupConfig that = (HistogramGroupConfig) other; - return Objects.equals(interval, that.interval) && Arrays.equals(fields, that.fields); - } - - @Override - public int hashCode() { - return Objects.hash(interval, Arrays.hashCode(fields)); - } - - public static HistogramGroupConfig fromXContent(final XContentParser parser) throws IOException { - return PARSER.parse(parser, null); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/job/config/MetricConfig.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/job/config/MetricConfig.java deleted file mode 100644 index 4e9590fd2cdc0..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/job/config/MetricConfig.java +++ /dev/null @@ -1,125 +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.rollup.job.config; - -import org.elasticsearch.client.Validatable; -import org.elasticsearch.client.ValidationException; -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.ToXContentObject; -import org.elasticsearch.xcontent.XContentBuilder; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.List; -import java.util.Objects; -import java.util.Optional; - -import static org.elasticsearch.xcontent.ConstructingObjectParser.constructorArg; - -/** - * The configuration object for the metrics portion of a rollup job config - * - * { - * "metrics": [ - * { - * "field": "foo", - * "metrics": [ "min", "max", "sum"] - * }, - * { - * "field": "bar", - * "metrics": [ "max" ] - * } - * ] - * } - */ -public class MetricConfig implements Validatable, ToXContentObject { - - static final String NAME = "metrics"; - private static final String FIELD = "field"; - private static final String METRICS = "metrics"; - - private static final ConstructingObjectParser PARSER; - static { - PARSER = new ConstructingObjectParser<>(NAME, true, args -> { - @SuppressWarnings("unchecked") - List metrics = (List) args[1]; - return new MetricConfig((String) args[0], metrics); - }); - PARSER.declareString(constructorArg(), new ParseField(FIELD)); - PARSER.declareStringArray(constructorArg(), new ParseField(METRICS)); - } - - private final String field; - private final List metrics; - - public MetricConfig(final String field, final List metrics) { - this.field = field; - this.metrics = metrics; - } - - @Override - public Optional validate() { - final ValidationException validationException = new ValidationException(); - if (field == null || field.isEmpty()) { - validationException.addValidationError("Field name is required"); - } - if (metrics == null || metrics.isEmpty()) { - validationException.addValidationError("Metrics must be a non-null, non-empty array of strings"); - } - if (validationException.validationErrors().isEmpty()) { - return Optional.empty(); - } - return Optional.of(validationException); - } - - /** - * @return the name of the field used in the metric configuration. Never {@code null}. - */ - public String getField() { - return field; - } - - /** - * @return the names of the metrics used in the metric configuration. Never {@code null}. - */ - public List getMetrics() { - return metrics; - } - - @Override - public XContentBuilder toXContent(final XContentBuilder builder, final Params params) throws IOException { - builder.startObject(); - { - builder.field(FIELD, field); - builder.field(METRICS, metrics); - } - return builder.endObject(); - } - - @Override - public boolean equals(final Object other) { - if (this == other) { - return true; - } - if (other == null || getClass() != other.getClass()) { - return false; - } - final MetricConfig that = (MetricConfig) other; - return Objects.equals(field, that.field) && Objects.equals(metrics, that.metrics); - } - - @Override - public int hashCode() { - return Objects.hash(field, metrics); - } - - public static MetricConfig fromXContent(final XContentParser parser) throws IOException { - return PARSER.parse(parser, null); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/job/config/RollupJobConfig.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/job/config/RollupJobConfig.java deleted file mode 100644 index 92620c9f06458..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/job/config/RollupJobConfig.java +++ /dev/null @@ -1,237 +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.rollup.job.config; - -import org.elasticsearch.client.Validatable; -import org.elasticsearch.client.ValidationException; -import org.elasticsearch.common.regex.Regex; -import org.elasticsearch.core.Nullable; -import org.elasticsearch.core.TimeValue; -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.ToXContentObject; -import org.elasticsearch.xcontent.XContentBuilder; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.Collections; -import java.util.List; -import java.util.Objects; -import java.util.Optional; - -import static org.elasticsearch.xcontent.ConstructingObjectParser.constructorArg; -import static org.elasticsearch.xcontent.ConstructingObjectParser.optionalConstructorArg; - -/** - * This class holds the configuration details of a rollup job, such as the groupings, metrics, what - * index to rollup and where to roll them to. - */ -public class RollupJobConfig implements Validatable, ToXContentObject { - - private static final TimeValue DEFAULT_TIMEOUT = TimeValue.timeValueSeconds(20); - private static final String ID = "id"; - private static final String TIMEOUT = "timeout"; - private static final String CRON = "cron"; - private static final String PAGE_SIZE = "page_size"; - private static final String INDEX_PATTERN = "index_pattern"; - private static final String ROLLUP_INDEX = "rollup_index"; - - private final String id; - private final String indexPattern; - private final String rollupIndex; - private final GroupConfig groupConfig; - private final List metricsConfig; - private final TimeValue timeout; - private final String cron; - private final int pageSize; - - private static final ConstructingObjectParser PARSER; - static { - PARSER = new ConstructingObjectParser<>("rollup_job_config", true, (args, optionalId) -> { - String id = args[0] != null ? (String) args[0] : optionalId; - String indexPattern = (String) args[1]; - String rollupIndex = (String) args[2]; - GroupConfig groupConfig = (GroupConfig) args[3]; - @SuppressWarnings("unchecked") - List metricsConfig = (List) args[4]; - TimeValue timeout = (TimeValue) args[5]; - String cron = (String) args[6]; - int pageSize = (int) args[7]; - return new RollupJobConfig(id, indexPattern, rollupIndex, cron, pageSize, groupConfig, metricsConfig, timeout); - }); - PARSER.declareString(optionalConstructorArg(), new ParseField(ID)); - PARSER.declareString(constructorArg(), new ParseField(INDEX_PATTERN)); - PARSER.declareString(constructorArg(), new ParseField(ROLLUP_INDEX)); - PARSER.declareObject(optionalConstructorArg(), (p, c) -> GroupConfig.fromXContent(p), new ParseField(GroupConfig.NAME)); - PARSER.declareObjectArray(optionalConstructorArg(), (p, c) -> MetricConfig.fromXContent(p), new ParseField(MetricConfig.NAME)); - PARSER.declareField( - optionalConstructorArg(), - (p, c) -> TimeValue.parseTimeValue(p.textOrNull(), TIMEOUT), - new ParseField(TIMEOUT), - ObjectParser.ValueType.STRING_OR_NULL - ); - PARSER.declareString(constructorArg(), new ParseField(CRON)); - PARSER.declareInt(constructorArg(), new ParseField(PAGE_SIZE)); - } - - public RollupJobConfig( - final String id, - final String indexPattern, - final String rollupIndex, - final String cron, - final int pageSize, - final GroupConfig groupConfig, - final List metricsConfig, - final @Nullable TimeValue timeout - ) { - this.id = id; - this.indexPattern = indexPattern; - this.rollupIndex = rollupIndex; - this.groupConfig = groupConfig; - this.metricsConfig = metricsConfig != null ? metricsConfig : Collections.emptyList(); - this.timeout = timeout != null ? timeout : DEFAULT_TIMEOUT; - this.cron = cron; - this.pageSize = pageSize; - } - - @Override - public Optional validate() { - final ValidationException validationException = new ValidationException(); - if (id == null || id.isEmpty()) { - validationException.addValidationError("Id must be a non-null, non-empty string"); - } - if (indexPattern == null || indexPattern.isEmpty()) { - validationException.addValidationError("Index pattern must be a non-null, non-empty string"); - } else if (Regex.isMatchAllPattern(indexPattern)) { - validationException.addValidationError("Index pattern must not match all indices (as it would match it's own rollup index"); - } else if (indexPattern != null && indexPattern.equals(rollupIndex)) { - validationException.addValidationError("Rollup index may not be the same as the index pattern"); - } else if (Regex.isSimpleMatchPattern(indexPattern) && Regex.simpleMatch(indexPattern, rollupIndex)) { - validationException.addValidationError("Index pattern would match rollup index name which is not allowed"); - } - - if (rollupIndex == null || rollupIndex.isEmpty()) { - validationException.addValidationError("Rollup index must be a non-null, non-empty string"); - } - if (cron == null || cron.isEmpty()) { - validationException.addValidationError("Cron schedule must be a non-null, non-empty string"); - } - if (pageSize <= 0) { - validationException.addValidationError("Page size is mandatory and must be a positive long"); - } - if (groupConfig == null && (metricsConfig == null || metricsConfig.isEmpty())) { - validationException.addValidationError("At least one grouping or metric must be configured"); - } - if (groupConfig != null) { - final Optional groupValidationErrors = groupConfig.validate(); - if (groupValidationErrors != null && groupValidationErrors.isPresent()) { - validationException.addValidationErrors(groupValidationErrors.get()); - } - } - if (metricsConfig != null) { - for (MetricConfig metricConfig : metricsConfig) { - final Optional metricsValidationErrors = metricConfig.validate(); - if (metricsValidationErrors != null && metricsValidationErrors.isPresent()) { - validationException.addValidationErrors(metricsValidationErrors.get()); - } - } - } - if (validationException.validationErrors().isEmpty()) { - return Optional.empty(); - } - return Optional.of(validationException); - } - - public String getId() { - return id; - } - - public GroupConfig getGroupConfig() { - return groupConfig; - } - - public List getMetricsConfig() { - return metricsConfig; - } - - public TimeValue getTimeout() { - return timeout; - } - - public String getIndexPattern() { - return indexPattern; - } - - public String getRollupIndex() { - return rollupIndex; - } - - public String getCron() { - return cron; - } - - public int getPageSize() { - return pageSize; - } - - @Override - public XContentBuilder toXContent(final XContentBuilder builder, final Params params) throws IOException { - builder.startObject(); - { - builder.field(ID, id); - builder.field(INDEX_PATTERN, indexPattern); - builder.field(ROLLUP_INDEX, rollupIndex); - builder.field(CRON, cron); - if (groupConfig != null) { - builder.field(GroupConfig.NAME, groupConfig); - } - if (metricsConfig != null) { - builder.startArray(MetricConfig.NAME); - for (MetricConfig metric : metricsConfig) { - metric.toXContent(builder, params); - } - builder.endArray(); - } - if (timeout != null) { - builder.field(TIMEOUT, timeout.getStringRep()); - } - builder.field(PAGE_SIZE, pageSize); - } - builder.endObject(); - return builder; - } - - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (other == null || getClass() != other.getClass()) { - return false; - } - final RollupJobConfig that = (RollupJobConfig) other; - return Objects.equals(this.id, that.id) - && Objects.equals(this.indexPattern, that.indexPattern) - && Objects.equals(this.rollupIndex, that.rollupIndex) - && Objects.equals(this.cron, that.cron) - && Objects.equals(this.groupConfig, that.groupConfig) - && Objects.equals(this.metricsConfig, that.metricsConfig) - && Objects.equals(this.timeout, that.timeout) - && Objects.equals(this.pageSize, that.pageSize); - } - - @Override - public int hashCode() { - return Objects.hash(id, indexPattern, rollupIndex, cron, groupConfig, metricsConfig, timeout, pageSize); - } - - public static RollupJobConfig fromXContent(final XContentParser parser, @Nullable final String optionalJobId) throws IOException { - return PARSER.parse(parser, optionalJobId); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/job/config/TermsGroupConfig.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/job/config/TermsGroupConfig.java deleted file mode 100644 index d75e2801f94d8..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/rollup/job/config/TermsGroupConfig.java +++ /dev/null @@ -1,105 +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.rollup.job.config; - -import org.elasticsearch.client.Validatable; -import org.elasticsearch.client.ValidationException; -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.ToXContentObject; -import org.elasticsearch.xcontent.XContentBuilder; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; - -import static org.elasticsearch.xcontent.ConstructingObjectParser.constructorArg; - -/** - * The configuration object for the histograms in the rollup config - * - * { - * "groups": [ - * "terms": { - * "fields" : [ "foo", "bar" ] - * } - * ] - * } - */ -public class TermsGroupConfig implements Validatable, ToXContentObject { - - static final String NAME = "terms"; - private static final String FIELDS = "fields"; - - private static final ConstructingObjectParser PARSER; - static { - PARSER = new ConstructingObjectParser<>(NAME, true, args -> { - @SuppressWarnings("unchecked") - List fields = (List) args[0]; - return new TermsGroupConfig(fields != null ? fields.toArray(new String[fields.size()]) : null); - }); - PARSER.declareStringArray(constructorArg(), new ParseField(FIELDS)); - } - - private final String[] fields; - - public TermsGroupConfig(final String... fields) { - this.fields = fields; - } - - @Override - public Optional validate() { - final ValidationException validationException = new ValidationException(); - if (fields == null || fields.length == 0) { - validationException.addValidationError("Fields must have at least one value"); - } - if (validationException.validationErrors().isEmpty()) { - return Optional.empty(); - } - return Optional.of(validationException); - } - - /** - * @return the names of the fields. Never {@code null}. - */ - public String[] getFields() { - return fields; - } - - @Override - public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(); - { - builder.field(FIELDS, fields); - } - return builder.endObject(); - } - - @Override - public boolean equals(final Object other) { - if (this == other) { - return true; - } - if (other == null || getClass() != other.getClass()) { - return false; - } - final TermsGroupConfig that = (TermsGroupConfig) other; - return Arrays.equals(fields, that.fields); - } - - @Override - public int hashCode() { - return Arrays.hashCode(fields); - } - - public static TermsGroupConfig fromXContent(final XContentParser parser) throws IOException { - return PARSER.parse(parser, null); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/textstructure/FindStructureRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/textstructure/FindStructureRequest.java deleted file mode 100644 index 1413c5cc661c4..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/textstructure/FindStructureRequest.java +++ /dev/null @@ -1,317 +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.textstructure; - -import org.elasticsearch.client.Validatable; -import org.elasticsearch.client.ValidationException; -import org.elasticsearch.client.textstructure.structurefinder.TextStructure; -import org.elasticsearch.common.bytes.BytesArray; -import org.elasticsearch.common.bytes.BytesReference; -import org.elasticsearch.core.TimeValue; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.ToXContentFragment; -import org.elasticsearch.xcontent.XContentBuilder; - -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; -import java.util.Optional; - -public class FindStructureRequest implements Validatable, ToXContentFragment { - - public static final ParseField LINES_TO_SAMPLE = new ParseField("lines_to_sample"); - public static final ParseField LINE_MERGE_SIZE_LIMIT = new ParseField("line_merge_size_limit"); - public static final ParseField TIMEOUT = new ParseField("timeout"); - public static final ParseField CHARSET = TextStructure.CHARSET; - public static final ParseField FORMAT = TextStructure.FORMAT; - public static final ParseField COLUMN_NAMES = TextStructure.COLUMN_NAMES; - public static final ParseField HAS_HEADER_ROW = TextStructure.HAS_HEADER_ROW; - public static final ParseField DELIMITER = TextStructure.DELIMITER; - public static final ParseField QUOTE = TextStructure.QUOTE; - public static final ParseField SHOULD_TRIM_FIELDS = TextStructure.SHOULD_TRIM_FIELDS; - public static final ParseField GROK_PATTERN = TextStructure.GROK_PATTERN; - // This one is plural in FileStructure, but singular in FileStructureOverrides - public static final ParseField TIMESTAMP_FORMAT = new ParseField("timestamp_format"); - public static final ParseField TIMESTAMP_FIELD = TextStructure.TIMESTAMP_FIELD; - public static final ParseField EXPLAIN = new ParseField("explain"); - - private Integer linesToSample; - private Integer lineMergeSizeLimit; - private TimeValue timeout; - private String charset; - private TextStructure.Format format; - private List columnNames; - private Boolean hasHeaderRow; - private Character delimiter; - private Character quote; - private Boolean shouldTrimFields; - private String grokPattern; - private String timestampFormat; - private String timestampField; - private Boolean explain; - private BytesReference sample; - - public FindStructureRequest() {} - - public Integer getLinesToSample() { - return linesToSample; - } - - public void setLinesToSample(Integer linesToSample) { - this.linesToSample = linesToSample; - } - - public Integer getLineMergeSizeLimit() { - return lineMergeSizeLimit; - } - - public void setLineMergeSizeLimit(Integer lineMergeSizeLimit) { - this.lineMergeSizeLimit = lineMergeSizeLimit; - } - - public TimeValue getTimeout() { - return timeout; - } - - public void setTimeout(TimeValue timeout) { - this.timeout = timeout; - } - - public String getCharset() { - return charset; - } - - public void setCharset(String charset) { - this.charset = (charset == null || charset.isEmpty()) ? null : charset; - } - - public TextStructure.Format getFormat() { - return format; - } - - public void setFormat(TextStructure.Format format) { - this.format = format; - } - - public void setFormat(String format) { - this.format = (format == null || format.isEmpty()) ? null : TextStructure.Format.fromString(format); - } - - public List getColumnNames() { - return columnNames; - } - - public void setColumnNames(List columnNames) { - this.columnNames = (columnNames == null || columnNames.isEmpty()) ? null : columnNames; - } - - public void setColumnNames(String[] columnNames) { - this.columnNames = (columnNames == null || columnNames.length == 0) ? null : Arrays.asList(columnNames); - } - - public Boolean getHasHeaderRow() { - return hasHeaderRow; - } - - public void setHasHeaderRow(Boolean hasHeaderRow) { - this.hasHeaderRow = hasHeaderRow; - } - - public Character getDelimiter() { - return delimiter; - } - - public void setDelimiter(Character delimiter) { - this.delimiter = delimiter; - } - - public void setDelimiter(String delimiter) { - if (delimiter == null || delimiter.isEmpty()) { - this.delimiter = null; - } else if (delimiter.length() == 1) { - this.delimiter = delimiter.charAt(0); - } else { - throw new IllegalArgumentException(DELIMITER.getPreferredName() + " must be a single character"); - } - } - - public Character getQuote() { - return quote; - } - - public void setQuote(Character quote) { - this.quote = quote; - } - - public void setQuote(String quote) { - if (quote == null || quote.isEmpty()) { - this.quote = null; - } else if (quote.length() == 1) { - this.quote = quote.charAt(0); - } else { - throw new IllegalArgumentException(QUOTE.getPreferredName() + " must be a single character"); - } - } - - public Boolean getShouldTrimFields() { - return shouldTrimFields; - } - - public void setShouldTrimFields(Boolean shouldTrimFields) { - this.shouldTrimFields = shouldTrimFields; - } - - public String getGrokPattern() { - return grokPattern; - } - - public void setGrokPattern(String grokPattern) { - this.grokPattern = (grokPattern == null || grokPattern.isEmpty()) ? null : grokPattern; - } - - public String getTimestampFormat() { - return timestampFormat; - } - - public void setTimestampFormat(String timestampFormat) { - this.timestampFormat = (timestampFormat == null || timestampFormat.isEmpty()) ? null : timestampFormat; - } - - public String getTimestampField() { - return timestampField; - } - - public void setTimestampField(String timestampField) { - this.timestampField = (timestampField == null || timestampField.isEmpty()) ? null : timestampField; - } - - public Boolean getExplain() { - return explain; - } - - public void setExplain(Boolean explain) { - this.explain = explain; - } - - public BytesReference getSample() { - return sample; - } - - public void setSample(byte[] sample) { - this.sample = new BytesArray(sample); - } - - public void setSample(BytesReference sample) { - this.sample = Objects.requireNonNull(sample); - } - - @Override - public Optional validate() { - ValidationException validationException = new ValidationException(); - if (sample == null || sample.length() == 0) { - validationException.addValidationError("sample must be specified"); - } - return validationException.validationErrors().isEmpty() ? Optional.empty() : Optional.of(validationException); - } - - @Override - public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - - if (linesToSample != null) { - builder.field(LINES_TO_SAMPLE.getPreferredName(), linesToSample); - } - if (lineMergeSizeLimit != null) { - builder.field(LINE_MERGE_SIZE_LIMIT.getPreferredName(), lineMergeSizeLimit); - } - if (timeout != null) { - builder.field(TIMEOUT.getPreferredName(), timeout); - } - if (charset != null) { - builder.field(CHARSET.getPreferredName(), charset); - } - if (format != null) { - builder.field(FORMAT.getPreferredName(), format); - } - if (columnNames != null) { - builder.field(COLUMN_NAMES.getPreferredName(), columnNames); - } - if (hasHeaderRow != null) { - builder.field(HAS_HEADER_ROW.getPreferredName(), hasHeaderRow); - } - if (delimiter != null) { - builder.field(DELIMITER.getPreferredName(), delimiter.toString()); - } - if (quote != null) { - builder.field(QUOTE.getPreferredName(), quote.toString()); - } - if (shouldTrimFields != null) { - builder.field(SHOULD_TRIM_FIELDS.getPreferredName(), shouldTrimFields); - } - if (grokPattern != null) { - builder.field(GROK_PATTERN.getPreferredName(), grokPattern); - } - if (timestampFormat != null) { - builder.field(TIMESTAMP_FORMAT.getPreferredName(), timestampFormat); - } - if (timestampField != null) { - builder.field(TIMESTAMP_FIELD.getPreferredName(), timestampField); - } - if (explain != null) { - builder.field(EXPLAIN.getPreferredName(), explain); - } - // Sample is not included in the X-Content representation - return builder; - } - - @Override - public int hashCode() { - return Objects.hash( - linesToSample, - lineMergeSizeLimit, - timeout, - charset, - format, - columnNames, - hasHeaderRow, - delimiter, - grokPattern, - timestampFormat, - timestampField, - explain, - sample - ); - } - - @Override - public boolean equals(Object other) { - - if (this == other) { - return true; - } - - if (other == null || getClass() != other.getClass()) { - return false; - } - - FindStructureRequest that = (FindStructureRequest) other; - return Objects.equals(this.linesToSample, that.linesToSample) - && Objects.equals(this.lineMergeSizeLimit, that.lineMergeSizeLimit) - && Objects.equals(this.timeout, that.timeout) - && Objects.equals(this.charset, that.charset) - && Objects.equals(this.format, that.format) - && Objects.equals(this.columnNames, that.columnNames) - && Objects.equals(this.hasHeaderRow, that.hasHeaderRow) - && Objects.equals(this.delimiter, that.delimiter) - && Objects.equals(this.grokPattern, that.grokPattern) - && Objects.equals(this.timestampFormat, that.timestampFormat) - && Objects.equals(this.timestampField, that.timestampField) - && Objects.equals(this.explain, that.explain) - && Objects.equals(this.sample, that.sample); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/textstructure/FindStructureResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/textstructure/FindStructureResponse.java deleted file mode 100644 index 681f49ccafd83..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/textstructure/FindStructureResponse.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.textstructure; - -import org.elasticsearch.client.textstructure.structurefinder.TextStructure; -import org.elasticsearch.xcontent.ToXContentObject; -import org.elasticsearch.xcontent.XContentBuilder; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.Objects; - -public class FindStructureResponse implements ToXContentObject { - - private final TextStructure textStructure; - - FindStructureResponse(TextStructure textStructure) { - this.textStructure = Objects.requireNonNull(textStructure); - } - - public static FindStructureResponse fromXContent(XContentParser parser) throws IOException { - return new FindStructureResponse(TextStructure.PARSER.parse(parser, null).build()); - } - - public TextStructure getFileStructure() { - return textStructure; - } - - @Override - public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - textStructure.toXContent(builder, params); - return builder; - } - - @Override - public int hashCode() { - return Objects.hash(textStructure); - } - - @Override - public boolean equals(Object other) { - - if (this == other) { - return true; - } - - if (other == null || getClass() != other.getClass()) { - return false; - } - - FindStructureResponse that = (FindStructureResponse) other; - return Objects.equals(textStructure, that.textStructure); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/textstructure/structurefinder/FieldStats.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/textstructure/structurefinder/FieldStats.java deleted file mode 100644 index 8e38fbbc0ddc1..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/textstructure/structurefinder/FieldStats.java +++ /dev/null @@ -1,200 +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.textstructure.structurefinder; - -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.ToXContent; -import org.elasticsearch.xcontent.ToXContentObject; -import org.elasticsearch.xcontent.XContentBuilder; - -import java.io.IOException; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -public class FieldStats implements ToXContentObject { - - public static final ParseField COUNT = new ParseField("count"); - public static final ParseField CARDINALITY = new ParseField("cardinality"); - public static final ParseField MIN_VALUE = new ParseField("min_value"); - public static final ParseField MAX_VALUE = new ParseField("max_value"); - public static final ParseField MEAN_VALUE = new ParseField("mean_value"); - public static final ParseField MEDIAN_VALUE = new ParseField("median_value"); - public static final ParseField EARLIEST = new ParseField("earliest"); - public static final ParseField LATEST = new ParseField("latest"); - public static final ParseField TOP_HITS = new ParseField("top_hits"); - - @SuppressWarnings("unchecked") - public static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "field_stats", - true, - a -> new FieldStats( - (long) a[0], - (int) a[1], - (Double) a[2], - (Double) a[3], - (Double) a[4], - (Double) a[5], - (String) a[6], - (String) a[7], - (List>) a[8] - ) - ); - - static { - PARSER.declareLong(ConstructingObjectParser.constructorArg(), COUNT); - PARSER.declareInt(ConstructingObjectParser.constructorArg(), CARDINALITY); - PARSER.declareDouble(ConstructingObjectParser.optionalConstructorArg(), MIN_VALUE); - PARSER.declareDouble(ConstructingObjectParser.optionalConstructorArg(), MAX_VALUE); - PARSER.declareDouble(ConstructingObjectParser.optionalConstructorArg(), MEAN_VALUE); - PARSER.declareDouble(ConstructingObjectParser.optionalConstructorArg(), MEDIAN_VALUE); - PARSER.declareString(ConstructingObjectParser.optionalConstructorArg(), EARLIEST); - PARSER.declareString(ConstructingObjectParser.optionalConstructorArg(), LATEST); - PARSER.declareObjectArray(ConstructingObjectParser.optionalConstructorArg(), (p, c) -> p.mapOrdered(), TOP_HITS); - } - - private final long count; - private final int cardinality; - private final Double minValue; - private final Double maxValue; - private final Double meanValue; - private final Double medianValue; - private final String earliestTimestamp; - private final String latestTimestamp; - private final List> topHits; - - FieldStats( - long count, - int cardinality, - Double minValue, - Double maxValue, - Double meanValue, - Double medianValue, - String earliestTimestamp, - String latestTimestamp, - List> topHits - ) { - this.count = count; - this.cardinality = cardinality; - this.minValue = minValue; - this.maxValue = maxValue; - this.meanValue = meanValue; - this.medianValue = medianValue; - this.earliestTimestamp = earliestTimestamp; - this.latestTimestamp = latestTimestamp; - this.topHits = (topHits == null) ? Collections.emptyList() : Collections.unmodifiableList(topHits); - } - - public long getCount() { - return count; - } - - public int getCardinality() { - return cardinality; - } - - public Double getMinValue() { - return minValue; - } - - public Double getMaxValue() { - return maxValue; - } - - public Double getMeanValue() { - return meanValue; - } - - public Double getMedianValue() { - return medianValue; - } - - public String getEarliestTimestamp() { - return earliestTimestamp; - } - - public String getLatestTimestamp() { - return latestTimestamp; - } - - public List> getTopHits() { - return topHits; - } - - @Override - public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException { - - builder.startObject(); - builder.field(COUNT.getPreferredName(), count); - builder.field(CARDINALITY.getPreferredName(), cardinality); - if (minValue != null) { - builder.field(MIN_VALUE.getPreferredName(), toIntegerIfInteger(minValue)); - } - if (maxValue != null) { - builder.field(MAX_VALUE.getPreferredName(), toIntegerIfInteger(maxValue)); - } - if (meanValue != null) { - builder.field(MEAN_VALUE.getPreferredName(), toIntegerIfInteger(meanValue)); - } - if (medianValue != null) { - builder.field(MEDIAN_VALUE.getPreferredName(), toIntegerIfInteger(medianValue)); - } - if (earliestTimestamp != null) { - builder.field(EARLIEST.getPreferredName(), earliestTimestamp); - } - if (latestTimestamp != null) { - builder.field(LATEST.getPreferredName(), latestTimestamp); - } - if (topHits.isEmpty() == false) { - builder.field(TOP_HITS.getPreferredName(), topHits); - } - builder.endObject(); - - return builder; - } - - static Number toIntegerIfInteger(double d) { - - if (d >= Integer.MIN_VALUE && d <= Integer.MAX_VALUE && Double.compare(d, StrictMath.rint(d)) == 0) { - return (int) d; - } - - return d; - } - - @Override - public int hashCode() { - - return Objects.hash(count, cardinality, minValue, maxValue, meanValue, medianValue, earliestTimestamp, latestTimestamp, topHits); - } - - @Override - public boolean equals(Object other) { - - if (this == other) { - return true; - } - - if (other == null || getClass() != other.getClass()) { - return false; - } - - FieldStats that = (FieldStats) other; - return this.count == that.count - && this.cardinality == that.cardinality - && Objects.equals(this.minValue, that.minValue) - && Objects.equals(this.maxValue, that.maxValue) - && Objects.equals(this.meanValue, that.meanValue) - && Objects.equals(this.medianValue, that.medianValue) - && Objects.equals(this.earliestTimestamp, that.earliestTimestamp) - && Objects.equals(this.latestTimestamp, that.latestTimestamp) - && Objects.equals(this.topHits, that.topHits); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/textstructure/structurefinder/TextStructure.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/textstructure/structurefinder/TextStructure.java deleted file mode 100644 index 4abd1f3c7ce2b..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/textstructure/structurefinder/TextStructure.java +++ /dev/null @@ -1,563 +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.textstructure.structurefinder; - -import org.elasticsearch.xcontent.ObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.ToXContentObject; -import org.elasticsearch.xcontent.XContentBuilder; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Objects; -import java.util.SortedMap; -import java.util.TreeMap; - -/** - * Stores the determined text format. - */ -public class TextStructure implements ToXContentObject { - - public enum Format { - - NDJSON, - XML, - DELIMITED, - SEMI_STRUCTURED_TEXT; - - public static Format fromString(String name) { - return valueOf(name.trim().toUpperCase(Locale.ROOT)); - } - - @Override - public String toString() { - return name().toLowerCase(Locale.ROOT); - } - } - - public static final ParseField NUM_LINES_ANALYZED = new ParseField("num_lines_analyzed"); - public static final ParseField NUM_MESSAGES_ANALYZED = new ParseField("num_messages_analyzed"); - public static final ParseField SAMPLE_START = new ParseField("sample_start"); - public static final ParseField CHARSET = new ParseField("charset"); - public static final ParseField HAS_BYTE_ORDER_MARKER = new ParseField("has_byte_order_marker"); - public static final ParseField FORMAT = new ParseField("format"); - public static final ParseField MULTILINE_START_PATTERN = new ParseField("multiline_start_pattern"); - public static final ParseField EXCLUDE_LINES_PATTERN = new ParseField("exclude_lines_pattern"); - public static final ParseField COLUMN_NAMES = new ParseField("column_names"); - public static final ParseField HAS_HEADER_ROW = new ParseField("has_header_row"); - public static final ParseField DELIMITER = new ParseField("delimiter"); - public static final ParseField QUOTE = new ParseField("quote"); - public static final ParseField SHOULD_TRIM_FIELDS = new ParseField("should_trim_fields"); - public static final ParseField GROK_PATTERN = new ParseField("grok_pattern"); - public static final ParseField TIMESTAMP_FIELD = new ParseField("timestamp_field"); - public static final ParseField JODA_TIMESTAMP_FORMATS = new ParseField("joda_timestamp_formats"); - public static final ParseField JAVA_TIMESTAMP_FORMATS = new ParseField("java_timestamp_formats"); - public static final ParseField NEED_CLIENT_TIMEZONE = new ParseField("need_client_timezone"); - public static final ParseField MAPPINGS = new ParseField("mappings"); - public static final ParseField INGEST_PIPELINE = new ParseField("ingest_pipeline"); - public static final ParseField FIELD_STATS = new ParseField("field_stats"); - public static final ParseField EXPLANATION = new ParseField("explanation"); - - public static final ObjectParser PARSER = new ObjectParser<>("file_structure", true, Builder::new); - - static { - PARSER.declareInt(Builder::setNumLinesAnalyzed, NUM_LINES_ANALYZED); - PARSER.declareInt(Builder::setNumMessagesAnalyzed, NUM_MESSAGES_ANALYZED); - PARSER.declareString(Builder::setSampleStart, SAMPLE_START); - PARSER.declareString(Builder::setCharset, CHARSET); - PARSER.declareBoolean(Builder::setHasByteOrderMarker, HAS_BYTE_ORDER_MARKER); - PARSER.declareString((p, c) -> p.setFormat(Format.fromString(c)), FORMAT); - PARSER.declareString(Builder::setMultilineStartPattern, MULTILINE_START_PATTERN); - PARSER.declareString(Builder::setExcludeLinesPattern, EXCLUDE_LINES_PATTERN); - PARSER.declareStringArray(Builder::setColumnNames, COLUMN_NAMES); - PARSER.declareBoolean(Builder::setHasHeaderRow, HAS_HEADER_ROW); - PARSER.declareString((p, c) -> p.setDelimiter(c.charAt(0)), DELIMITER); - PARSER.declareString((p, c) -> p.setQuote(c.charAt(0)), QUOTE); - PARSER.declareBoolean(Builder::setShouldTrimFields, SHOULD_TRIM_FIELDS); - PARSER.declareString(Builder::setGrokPattern, GROK_PATTERN); - PARSER.declareString(Builder::setTimestampField, TIMESTAMP_FIELD); - PARSER.declareStringArray(Builder::setJodaTimestampFormats, JODA_TIMESTAMP_FORMATS); - PARSER.declareStringArray(Builder::setJavaTimestampFormats, JAVA_TIMESTAMP_FORMATS); - PARSER.declareBoolean(Builder::setNeedClientTimezone, NEED_CLIENT_TIMEZONE); - PARSER.declareObject(Builder::setMappings, (p, c) -> new TreeMap<>(p.map()), MAPPINGS); - PARSER.declareObject(Builder::setIngestPipeline, (p, c) -> p.mapOrdered(), INGEST_PIPELINE); - PARSER.declareObject(Builder::setFieldStats, (p, c) -> { - Map fieldStats = new TreeMap<>(); - while (p.nextToken() == XContentParser.Token.FIELD_NAME) { - fieldStats.put(p.currentName(), FieldStats.PARSER.apply(p, c)); - } - return fieldStats; - }, FIELD_STATS); - PARSER.declareStringArray(Builder::setExplanation, EXPLANATION); - } - - private final int numLinesAnalyzed; - private final int numMessagesAnalyzed; - private final String sampleStart; - private final String charset; - private final Boolean hasByteOrderMarker; - private final Format format; - private final String multilineStartPattern; - private final String excludeLinesPattern; - private final List columnNames; - private final Boolean hasHeaderRow; - private final Character delimiter; - private final Character quote; - private final Boolean shouldTrimFields; - private final String grokPattern; - private final List jodaTimestampFormats; - private final List javaTimestampFormats; - private final String timestampField; - private final boolean needClientTimezone; - private final SortedMap mappings; - private final Map ingestPipeline; - private final SortedMap fieldStats; - private final List explanation; - - private TextStructure( - int numLinesAnalyzed, - int numMessagesAnalyzed, - String sampleStart, - String charset, - Boolean hasByteOrderMarker, - Format format, - String multilineStartPattern, - String excludeLinesPattern, - List columnNames, - Boolean hasHeaderRow, - Character delimiter, - Character quote, - Boolean shouldTrimFields, - String grokPattern, - String timestampField, - List jodaTimestampFormats, - List javaTimestampFormats, - boolean needClientTimezone, - Map mappings, - Map ingestPipeline, - Map fieldStats, - List explanation - ) { - - this.numLinesAnalyzed = numLinesAnalyzed; - this.numMessagesAnalyzed = numMessagesAnalyzed; - this.sampleStart = Objects.requireNonNull(sampleStart); - this.charset = Objects.requireNonNull(charset); - this.hasByteOrderMarker = hasByteOrderMarker; - this.format = Objects.requireNonNull(format); - this.multilineStartPattern = multilineStartPattern; - this.excludeLinesPattern = excludeLinesPattern; - this.columnNames = (columnNames == null) ? null : List.copyOf(columnNames); - this.hasHeaderRow = hasHeaderRow; - this.delimiter = delimiter; - this.quote = quote; - this.shouldTrimFields = shouldTrimFields; - this.grokPattern = grokPattern; - this.timestampField = timestampField; - this.jodaTimestampFormats = (jodaTimestampFormats == null) ? null : List.copyOf(jodaTimestampFormats); - this.javaTimestampFormats = (javaTimestampFormats == null) ? null : List.copyOf(javaTimestampFormats); - this.needClientTimezone = needClientTimezone; - this.mappings = Collections.unmodifiableSortedMap(new TreeMap<>(mappings)); - this.ingestPipeline = (ingestPipeline == null) ? null : Collections.unmodifiableMap(new LinkedHashMap<>(ingestPipeline)); - this.fieldStats = Collections.unmodifiableSortedMap(new TreeMap<>(fieldStats)); - this.explanation = (explanation == null) ? null : List.copyOf(explanation); - } - - public int getNumLinesAnalyzed() { - return numLinesAnalyzed; - } - - public int getNumMessagesAnalyzed() { - return numMessagesAnalyzed; - } - - public String getSampleStart() { - return sampleStart; - } - - public String getCharset() { - return charset; - } - - public Boolean getHasByteOrderMarker() { - return hasByteOrderMarker; - } - - public Format getFormat() { - return format; - } - - public String getMultilineStartPattern() { - return multilineStartPattern; - } - - public String getExcludeLinesPattern() { - return excludeLinesPattern; - } - - public List getColumnNames() { - return columnNames; - } - - public Boolean getHasHeaderRow() { - return hasHeaderRow; - } - - public Character getDelimiter() { - return delimiter; - } - - public Character getQuote() { - return quote; - } - - public Boolean getShouldTrimFields() { - return shouldTrimFields; - } - - public String getGrokPattern() { - return grokPattern; - } - - public String getTimestampField() { - return timestampField; - } - - public List getJodaTimestampFormats() { - return jodaTimestampFormats; - } - - public List getJavaTimestampFormats() { - return javaTimestampFormats; - } - - public boolean needClientTimezone() { - return needClientTimezone; - } - - public SortedMap getMappings() { - return mappings; - } - - public Map getIngestPipeline() { - return ingestPipeline; - } - - public SortedMap getFieldStats() { - return fieldStats; - } - - public List getExplanation() { - return explanation; - } - - @Override - public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - - builder.startObject(); - builder.field(NUM_LINES_ANALYZED.getPreferredName(), numLinesAnalyzed); - builder.field(NUM_MESSAGES_ANALYZED.getPreferredName(), numMessagesAnalyzed); - builder.field(SAMPLE_START.getPreferredName(), sampleStart); - builder.field(CHARSET.getPreferredName(), charset); - if (hasByteOrderMarker != null) { - builder.field(HAS_BYTE_ORDER_MARKER.getPreferredName(), hasByteOrderMarker.booleanValue()); - } - builder.field(FORMAT.getPreferredName(), format); - if (multilineStartPattern != null && multilineStartPattern.isEmpty() == false) { - builder.field(MULTILINE_START_PATTERN.getPreferredName(), multilineStartPattern); - } - if (excludeLinesPattern != null && excludeLinesPattern.isEmpty() == false) { - builder.field(EXCLUDE_LINES_PATTERN.getPreferredName(), excludeLinesPattern); - } - if (columnNames != null && columnNames.isEmpty() == false) { - builder.field(COLUMN_NAMES.getPreferredName(), columnNames); - } - if (hasHeaderRow != null) { - builder.field(HAS_HEADER_ROW.getPreferredName(), hasHeaderRow.booleanValue()); - } - if (delimiter != null) { - builder.field(DELIMITER.getPreferredName(), String.valueOf(delimiter)); - } - if (quote != null) { - builder.field(QUOTE.getPreferredName(), String.valueOf(quote)); - } - if (shouldTrimFields != null) { - builder.field(SHOULD_TRIM_FIELDS.getPreferredName(), shouldTrimFields.booleanValue()); - } - if (grokPattern != null && grokPattern.isEmpty() == false) { - builder.field(GROK_PATTERN.getPreferredName(), grokPattern); - } - if (timestampField != null && timestampField.isEmpty() == false) { - builder.field(TIMESTAMP_FIELD.getPreferredName(), timestampField); - } - if (jodaTimestampFormats != null && jodaTimestampFormats.isEmpty() == false) { - builder.field(JODA_TIMESTAMP_FORMATS.getPreferredName(), jodaTimestampFormats); - } - if (javaTimestampFormats != null && javaTimestampFormats.isEmpty() == false) { - builder.field(JAVA_TIMESTAMP_FORMATS.getPreferredName(), javaTimestampFormats); - } - builder.field(NEED_CLIENT_TIMEZONE.getPreferredName(), needClientTimezone); - builder.field(MAPPINGS.getPreferredName(), mappings); - if (ingestPipeline != null) { - builder.field(INGEST_PIPELINE.getPreferredName(), ingestPipeline); - } - if (fieldStats.isEmpty() == false) { - builder.startObject(FIELD_STATS.getPreferredName()); - for (Map.Entry entry : fieldStats.entrySet()) { - builder.field(entry.getKey(), entry.getValue()); - } - builder.endObject(); - } - if (explanation != null && explanation.isEmpty() == false) { - builder.field(EXPLANATION.getPreferredName(), explanation); - } - builder.endObject(); - - return builder; - } - - @Override - public int hashCode() { - - return Objects.hash( - numLinesAnalyzed, - numMessagesAnalyzed, - sampleStart, - charset, - hasByteOrderMarker, - format, - multilineStartPattern, - excludeLinesPattern, - columnNames, - hasHeaderRow, - delimiter, - quote, - shouldTrimFields, - grokPattern, - timestampField, - jodaTimestampFormats, - javaTimestampFormats, - needClientTimezone, - mappings, - fieldStats, - explanation - ); - } - - @Override - public boolean equals(Object other) { - - if (this == other) { - return true; - } - - if (other == null || getClass() != other.getClass()) { - return false; - } - - TextStructure that = (TextStructure) other; - return this.numLinesAnalyzed == that.numLinesAnalyzed - && this.numMessagesAnalyzed == that.numMessagesAnalyzed - && Objects.equals(this.sampleStart, that.sampleStart) - && Objects.equals(this.charset, that.charset) - && Objects.equals(this.hasByteOrderMarker, that.hasByteOrderMarker) - && Objects.equals(this.format, that.format) - && Objects.equals(this.multilineStartPattern, that.multilineStartPattern) - && Objects.equals(this.excludeLinesPattern, that.excludeLinesPattern) - && Objects.equals(this.columnNames, that.columnNames) - && Objects.equals(this.hasHeaderRow, that.hasHeaderRow) - && Objects.equals(this.delimiter, that.delimiter) - && Objects.equals(this.quote, that.quote) - && Objects.equals(this.shouldTrimFields, that.shouldTrimFields) - && Objects.equals(this.grokPattern, that.grokPattern) - && Objects.equals(this.timestampField, that.timestampField) - && Objects.equals(this.jodaTimestampFormats, that.jodaTimestampFormats) - && Objects.equals(this.javaTimestampFormats, that.javaTimestampFormats) - && this.needClientTimezone == that.needClientTimezone - && Objects.equals(this.mappings, that.mappings) - && Objects.equals(this.fieldStats, that.fieldStats) - && Objects.equals(this.explanation, that.explanation); - } - - public static class Builder { - - private int numLinesAnalyzed; - private int numMessagesAnalyzed; - private String sampleStart; - private String charset; - private Boolean hasByteOrderMarker; - private Format format; - private String multilineStartPattern; - private String excludeLinesPattern; - private List columnNames; - private Boolean hasHeaderRow; - private Character delimiter; - private Character quote; - private Boolean shouldTrimFields; - private String grokPattern; - private String timestampField; - private List jodaTimestampFormats; - private List javaTimestampFormats; - private boolean needClientTimezone; - private Map mappings = Collections.emptyMap(); - private Map ingestPipeline; - private Map fieldStats = Collections.emptyMap(); - private List explanation; - - Builder() { - this(Format.SEMI_STRUCTURED_TEXT); - } - - Builder(Format format) { - setFormat(format); - } - - Builder setNumLinesAnalyzed(int numLinesAnalyzed) { - this.numLinesAnalyzed = numLinesAnalyzed; - return this; - } - - Builder setNumMessagesAnalyzed(int numMessagesAnalyzed) { - this.numMessagesAnalyzed = numMessagesAnalyzed; - return this; - } - - Builder setSampleStart(String sampleStart) { - this.sampleStart = Objects.requireNonNull(sampleStart); - return this; - } - - Builder setCharset(String charset) { - this.charset = Objects.requireNonNull(charset); - return this; - } - - Builder setHasByteOrderMarker(Boolean hasByteOrderMarker) { - this.hasByteOrderMarker = hasByteOrderMarker; - return this; - } - - Builder setFormat(Format format) { - this.format = Objects.requireNonNull(format); - return this; - } - - Builder setMultilineStartPattern(String multilineStartPattern) { - this.multilineStartPattern = multilineStartPattern; - return this; - } - - Builder setExcludeLinesPattern(String excludeLinesPattern) { - this.excludeLinesPattern = excludeLinesPattern; - return this; - } - - Builder setColumnNames(List columnNames) { - this.columnNames = columnNames; - return this; - } - - Builder setHasHeaderRow(Boolean hasHeaderRow) { - this.hasHeaderRow = hasHeaderRow; - return this; - } - - Builder setDelimiter(Character delimiter) { - this.delimiter = delimiter; - return this; - } - - Builder setQuote(Character quote) { - this.quote = quote; - return this; - } - - Builder setShouldTrimFields(Boolean shouldTrimFields) { - this.shouldTrimFields = shouldTrimFields; - return this; - } - - Builder setGrokPattern(String grokPattern) { - this.grokPattern = grokPattern; - return this; - } - - Builder setTimestampField(String timestampField) { - this.timestampField = timestampField; - return this; - } - - Builder setJodaTimestampFormats(List jodaTimestampFormats) { - this.jodaTimestampFormats = jodaTimestampFormats; - return this; - } - - Builder setJavaTimestampFormats(List javaTimestampFormats) { - this.javaTimestampFormats = javaTimestampFormats; - return this; - } - - Builder setNeedClientTimezone(boolean needClientTimezone) { - this.needClientTimezone = needClientTimezone; - return this; - } - - Builder setMappings(Map mappings) { - this.mappings = Objects.requireNonNull(mappings); - return this; - } - - Builder setIngestPipeline(Map ingestPipeline) { - this.ingestPipeline = ingestPipeline; - return this; - } - - Builder setFieldStats(Map fieldStats) { - this.fieldStats = Objects.requireNonNull(fieldStats); - return this; - } - - Builder setExplanation(List explanation) { - this.explanation = explanation; - return this; - } - - public TextStructure build() { - - return new TextStructure( - numLinesAnalyzed, - numMessagesAnalyzed, - sampleStart, - charset, - hasByteOrderMarker, - format, - multilineStartPattern, - excludeLinesPattern, - columnNames, - hasHeaderRow, - delimiter, - quote, - shouldTrimFields, - grokPattern, - timestampField, - jodaTimestampFormats, - javaTimestampFormats, - needClientTimezone, - mappings, - ingestPipeline, - fieldStats, - explanation - ); - } - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/AckWatchRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/AckWatchRequest.java deleted file mode 100644 index 714dfa6af6077..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/AckWatchRequest.java +++ /dev/null @@ -1,84 +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.watcher; - -import org.elasticsearch.client.Validatable; -import org.elasticsearch.client.ValidationException; - -import java.util.Locale; - -/** - * A request to explicitly acknowledge a watch. - */ -public class AckWatchRequest implements Validatable { - - private final String watchId; - private final String[] actionIds; - - public AckWatchRequest(String watchId, String... actionIds) { - validateIds(watchId, actionIds); - this.watchId = watchId; - this.actionIds = actionIds; - } - - @SuppressWarnings("HiddenField") - private void validateIds(String watchId, String... actionIds) { - ValidationException exception = new ValidationException(); - if (watchId == null) { - exception.addValidationError("watch id is missing"); - } else if (PutWatchRequest.isValidId(watchId) == false) { - exception.addValidationError("watch id contains whitespace"); - } - - if (actionIds != null) { - for (String actionId : actionIds) { - if (actionId == null) { - exception.addValidationError(String.format(Locale.ROOT, "action id may not be null")); - } else if (PutWatchRequest.isValidId(actionId) == false) { - exception.addValidationError(String.format(Locale.ROOT, "action id [%s] contains whitespace", actionId)); - } - } - } - - if (exception.validationErrors().isEmpty() == false) { - throw exception; - } - } - - /** - * @return The ID of the watch to be acked. - */ - public String getWatchId() { - return watchId; - } - - /** - * @return The IDs of the actions to be acked. If omitted, - * all actions for the given watch will be acknowledged. - */ - public String[] getActionIds() { - return actionIds; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("ack [").append(watchId).append("]"); - if (actionIds.length > 0) { - sb.append("["); - for (int i = 0; i < actionIds.length; i++) { - if (i > 0) { - sb.append(", "); - } - sb.append(actionIds[i]); - } - sb.append("]"); - } - return sb.toString(); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/AckWatchResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/AckWatchResponse.java deleted file mode 100644 index e53526b803f50..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/AckWatchResponse.java +++ /dev/null @@ -1,50 +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.watcher; - -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; - -/** - * The response from an 'ack watch' request. - */ -public class AckWatchResponse { - - private final WatchStatus status; - - public AckWatchResponse(WatchStatus status) { - this.status = status; - } - - /** - * @return the status of the requested watch. If an action was - * successfully acknowledged, this will be reflected in its status. - */ - public WatchStatus getStatus() { - return status; - } - - private static final ParseField STATUS_FIELD = new ParseField("status"); - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "ack_watch_response", - true, - a -> new AckWatchResponse((WatchStatus) a[0]) - ); - - static { - PARSER.declareObject(ConstructingObjectParser.constructorArg(), (parser, context) -> WatchStatus.parse(parser), STATUS_FIELD); - } - - public static AckWatchResponse fromXContent(XContentParser parser) throws IOException { - return PARSER.parse(parser, null); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/ActionStatus.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/ActionStatus.java deleted file mode 100644 index 57385a4a4fc93..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/ActionStatus.java +++ /dev/null @@ -1,367 +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.watcher; - -import org.elasticsearch.ElasticsearchParseException; -import org.elasticsearch.core.Nullable; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.util.Locale; -import java.util.Objects; - -public class ActionStatus { - - private final AckStatus ackStatus; - @Nullable - private final Execution lastExecution; - @Nullable - private final Execution lastSuccessfulExecution; - @Nullable - private final Throttle lastThrottle; - - public ActionStatus( - AckStatus ackStatus, - @Nullable Execution lastExecution, - @Nullable Execution lastSuccessfulExecution, - @Nullable Throttle lastThrottle - ) { - this.ackStatus = ackStatus; - this.lastExecution = lastExecution; - this.lastSuccessfulExecution = lastSuccessfulExecution; - this.lastThrottle = lastThrottle; - } - - public AckStatus ackStatus() { - return ackStatus; - } - - public Execution lastExecution() { - return lastExecution; - } - - public Execution lastSuccessfulExecution() { - return lastSuccessfulExecution; - } - - public Throttle lastThrottle() { - return lastThrottle; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - ActionStatus that = (ActionStatus) o; - - return Objects.equals(ackStatus, that.ackStatus) - && Objects.equals(lastExecution, that.lastExecution) - && Objects.equals(lastSuccessfulExecution, that.lastSuccessfulExecution) - && Objects.equals(lastThrottle, that.lastThrottle); - } - - @Override - public int hashCode() { - return Objects.hash(ackStatus, lastExecution, lastSuccessfulExecution, lastThrottle); - } - - public static ActionStatus parse(String actionId, XContentParser parser) throws IOException { - AckStatus ackStatus = null; - Execution lastExecution = null; - Execution lastSuccessfulExecution = null; - Throttle lastThrottle = null; - - String currentFieldName = null; - XContentParser.Token token; - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else if (Field.ACK_STATUS.match(currentFieldName, parser.getDeprecationHandler())) { - ackStatus = AckStatus.parse(actionId, parser); - } else if (Field.LAST_EXECUTION.match(currentFieldName, parser.getDeprecationHandler())) { - lastExecution = Execution.parse(actionId, parser); - } else if (Field.LAST_SUCCESSFUL_EXECUTION.match(currentFieldName, parser.getDeprecationHandler())) { - lastSuccessfulExecution = Execution.parse(actionId, parser); - } else if (Field.LAST_THROTTLE.match(currentFieldName, parser.getDeprecationHandler())) { - lastThrottle = Throttle.parse(actionId, parser); - } else { - parser.skipChildren(); - } - } - if (ackStatus == null) { - throw new ElasticsearchParseException( - "could not parse action status for [{}]. missing required field [{}]", - actionId, - Field.ACK_STATUS.getPreferredName() - ); - } - return new ActionStatus(ackStatus, lastExecution, lastSuccessfulExecution, lastThrottle); - } - - public static class AckStatus { - - public enum State { - AWAITS_SUCCESSFUL_EXECUTION, - ACKABLE, - ACKED; - } - - private final ZonedDateTime timestamp; - private final State state; - - public AckStatus(ZonedDateTime timestamp, State state) { - assert timestamp.getOffset() == ZoneOffset.UTC; - this.timestamp = timestamp; - this.state = state; - } - - public ZonedDateTime timestamp() { - return timestamp; - } - - public State state() { - return state; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - AckStatus ackStatus = (AckStatus) o; - - return Objects.equals(timestamp, ackStatus.timestamp) && Objects.equals(state, ackStatus.state); - } - - @Override - public int hashCode() { - return Objects.hash(timestamp, state); - } - - public static AckStatus parse(String actionId, XContentParser parser) throws IOException { - ZonedDateTime timestamp = null; - State state = null; - - String currentFieldName = null; - XContentParser.Token token; - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else if (Field.TIMESTAMP.match(currentFieldName, parser.getDeprecationHandler())) { - timestamp = WatchStatusDateParser.parseDate(parser.text()); - } else if (Field.ACK_STATUS_STATE.match(currentFieldName, parser.getDeprecationHandler())) { - state = State.valueOf(parser.text().toUpperCase(Locale.ROOT)); - } else { - parser.skipChildren(); - } - } - if (timestamp == null) { - throw new ElasticsearchParseException( - "could not parse action status for [{}]. missing required field [{}.{}]", - actionId, - Field.ACK_STATUS.getPreferredName(), - Field.TIMESTAMP.getPreferredName() - ); - } - if (state == null) { - throw new ElasticsearchParseException( - "could not parse action status for [{}]. missing required field [{}.{}]", - actionId, - Field.ACK_STATUS.getPreferredName(), - Field.ACK_STATUS_STATE.getPreferredName() - ); - } - return new AckStatus(timestamp, state); - } - } - - public static class Execution { - - public static Execution successful(ZonedDateTime timestamp) { - return new Execution(timestamp, true, null); - } - - public static Execution failure(ZonedDateTime timestamp, String reason) { - return new Execution(timestamp, false, reason); - } - - private final ZonedDateTime timestamp; - private final boolean successful; - private final String reason; - - private Execution(ZonedDateTime timestamp, boolean successful, String reason) { - this.timestamp = timestamp.withZoneSameInstant(ZoneOffset.UTC); - this.successful = successful; - this.reason = reason; - } - - public ZonedDateTime timestamp() { - return timestamp; - } - - public boolean successful() { - return successful; - } - - public String reason() { - return reason; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - Execution execution = (Execution) o; - - return Objects.equals(successful, execution.successful) - && Objects.equals(timestamp, execution.timestamp) - && Objects.equals(reason, execution.reason); - } - - @Override - public int hashCode() { - return Objects.hash(timestamp, successful, reason); - } - - public static Execution parse(String actionId, XContentParser parser) throws IOException { - ZonedDateTime timestamp = null; - Boolean successful = null; - String reason = null; - - String currentFieldName = null; - XContentParser.Token token; - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else if (Field.TIMESTAMP.match(currentFieldName, parser.getDeprecationHandler())) { - timestamp = WatchStatusDateParser.parseDate(parser.text()); - } else if (Field.EXECUTION_SUCCESSFUL.match(currentFieldName, parser.getDeprecationHandler())) { - successful = parser.booleanValue(); - } else if (Field.REASON.match(currentFieldName, parser.getDeprecationHandler())) { - reason = parser.text(); - } else { - parser.skipChildren(); - } - } - if (timestamp == null) { - throw new ElasticsearchParseException( - "could not parse action status for [{}]. missing required field [{}.{}]", - actionId, - Field.LAST_EXECUTION.getPreferredName(), - Field.TIMESTAMP.getPreferredName() - ); - } - if (successful == null) { - throw new ElasticsearchParseException( - "could not parse action status for [{}]. missing required field [{}.{}]", - actionId, - Field.LAST_EXECUTION.getPreferredName(), - Field.EXECUTION_SUCCESSFUL.getPreferredName() - ); - } - if (successful) { - return successful(timestamp); - } - if (reason == null) { - throw new ElasticsearchParseException( - "could not parse action status for [{}]. missing required field for unsuccessful" + " execution [{}.{}]", - actionId, - Field.LAST_EXECUTION.getPreferredName(), - Field.REASON.getPreferredName() - ); - } - return failure(timestamp, reason); - } - } - - public static class Throttle { - - private final ZonedDateTime timestamp; - private final String reason; - - public Throttle(ZonedDateTime timestamp, String reason) { - this.timestamp = timestamp.withZoneSameInstant(ZoneOffset.UTC); - this.reason = reason; - } - - public ZonedDateTime timestamp() { - return timestamp; - } - - public String reason() { - return reason; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - Throttle throttle = (Throttle) o; - return Objects.equals(timestamp, throttle.timestamp) && Objects.equals(reason, throttle.reason); - } - - @Override - public int hashCode() { - return Objects.hash(timestamp, reason); - } - - public static Throttle parse(String actionId, XContentParser parser) throws IOException { - ZonedDateTime timestamp = null; - String reason = null; - - String currentFieldName = null; - XContentParser.Token token; - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else if (Field.TIMESTAMP.match(currentFieldName, parser.getDeprecationHandler())) { - timestamp = WatchStatusDateParser.parseDate(parser.text()); - } else if (Field.REASON.match(currentFieldName, parser.getDeprecationHandler())) { - reason = parser.text(); - } else { - parser.skipChildren(); - } - } - if (timestamp == null) { - throw new ElasticsearchParseException( - "could not parse action status for [{}]. missing required field [{}.{}]", - actionId, - Field.LAST_THROTTLE.getPreferredName(), - Field.TIMESTAMP.getPreferredName() - ); - } - if (reason == null) { - throw new ElasticsearchParseException( - "could not parse action status for [{}]. missing required field [{}.{}]", - actionId, - Field.LAST_THROTTLE.getPreferredName(), - Field.REASON.getPreferredName() - ); - } - return new Throttle(timestamp, reason); - } - } - - private interface Field { - ParseField ACK_STATUS = new ParseField("ack"); - ParseField ACK_STATUS_STATE = new ParseField("state"); - ParseField LAST_EXECUTION = new ParseField("last_execution"); - ParseField LAST_SUCCESSFUL_EXECUTION = new ParseField("last_successful_execution"); - ParseField EXECUTION_SUCCESSFUL = new ParseField("successful"); - ParseField LAST_THROTTLE = new ParseField("last_throttle"); - ParseField TIMESTAMP = new ParseField("timestamp"); - ParseField REASON = new ParseField("reason"); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/ActivateWatchRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/ActivateWatchRequest.java deleted file mode 100644 index e402f484bdff7..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/ActivateWatchRequest.java +++ /dev/null @@ -1,49 +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.watcher; - -import org.elasticsearch.client.Validatable; - -import java.util.Objects; - -/** - * A request to explicitly activate a watch. - */ -public final class ActivateWatchRequest implements Validatable { - - private final String watchId; - - public ActivateWatchRequest(String watchId) { - this.watchId = Objects.requireNonNull(watchId, "Watch identifier is required"); - if (PutWatchRequest.isValidId(this.watchId) == false) { - throw new IllegalArgumentException("Watch identifier contains whitespace"); - } - } - - /** - * @return The ID of the watch to be activated. - */ - public String getWatchId() { - return watchId; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - ActivateWatchRequest that = (ActivateWatchRequest) o; - return Objects.equals(watchId, that.watchId); - } - - @Override - public int hashCode() { - int result = Objects.hash(watchId); - return result; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/ActivateWatchResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/ActivateWatchResponse.java deleted file mode 100644 index 02524091a471f..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/ActivateWatchResponse.java +++ /dev/null @@ -1,60 +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.watcher; - -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.Objects; - -/** - * Response from an 'activate watch' request. - */ -public final class ActivateWatchResponse { - - private static final ParseField STATUS_FIELD = new ParseField("status"); - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "activate_watch_response", - true, - a -> new ActivateWatchResponse((WatchStatus) a[0]) - ); - - static { - PARSER.declareObject(ConstructingObjectParser.constructorArg(), (parser, context) -> WatchStatus.parse(parser), STATUS_FIELD); - } - - private final WatchStatus status; - - public ActivateWatchResponse(WatchStatus status) { - this.status = status; - } - - public WatchStatus getStatus() { - return status; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - ActivateWatchResponse that = (ActivateWatchResponse) o; - return Objects.equals(status, that.status); - } - - @Override - public int hashCode() { - return Objects.hash(status); - } - - public static ActivateWatchResponse fromXContent(XContentParser parser) throws IOException { - return PARSER.parse(parser, null); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/DeactivateWatchRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/DeactivateWatchRequest.java deleted file mode 100644 index deb3f97c413d6..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/DeactivateWatchRequest.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.watcher; - -import org.elasticsearch.client.Validatable; - -import java.util.Objects; - -public class DeactivateWatchRequest implements Validatable { - private final String watchId; - - public DeactivateWatchRequest(String watchId) { - Objects.requireNonNull(watchId, "watch id is missing"); - if (PutWatchRequest.isValidId(watchId) == false) { - throw new IllegalArgumentException("watch id contains whitespace"); - } - - this.watchId = watchId; - } - - public String getWatchId() { - return watchId; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/DeactivateWatchResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/DeactivateWatchResponse.java deleted file mode 100644 index a5e031907b6cb..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/DeactivateWatchResponse.java +++ /dev/null @@ -1,54 +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.watcher; - -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.Objects; - -public class DeactivateWatchResponse { - private WatchStatus status; - - private static final ParseField STATUS_FIELD = new ParseField("status"); - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "x_pack_deactivate_watch_response", - true, - (fields) -> new DeactivateWatchResponse((WatchStatus) fields[0]) - ); - static { - PARSER.declareObject(ConstructingObjectParser.constructorArg(), (parser, context) -> WatchStatus.parse(parser), STATUS_FIELD); - } - - public static DeactivateWatchResponse fromXContent(XContentParser parser) throws IOException { - return PARSER.parse(parser, null); - } - - public DeactivateWatchResponse(WatchStatus status) { - this.status = status; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - DeactivateWatchResponse that = (DeactivateWatchResponse) o; - return Objects.equals(status, that.status); - } - - @Override - public int hashCode() { - return Objects.hash(status); - } - - public WatchStatus getStatus() { - return status; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/DeleteWatchRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/DeleteWatchRequest.java deleted file mode 100644 index 98f1fc2a3c898..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/DeleteWatchRequest.java +++ /dev/null @@ -1,40 +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.watcher; - -import org.elasticsearch.client.Validatable; - -import java.util.Objects; - -/** - * A delete watch request to delete an watch by name (id) - */ -public class DeleteWatchRequest implements Validatable { - - private final String id; - - public DeleteWatchRequest(String id) { - Objects.requireNonNull(id, "watch id is missing"); - if (PutWatchRequest.isValidId(id) == false) { - throw new IllegalArgumentException("watch id contains whitespace"); - } - this.id = id; - } - - /** - * @return The name of the watch to be deleted - */ - public String getId() { - return id; - } - - @Override - public String toString() { - return "delete [" + id + "]"; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/DeleteWatchResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/DeleteWatchResponse.java deleted file mode 100644 index 756a5ff20b4b9..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/DeleteWatchResponse.java +++ /dev/null @@ -1,84 +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.watcher; - -import org.elasticsearch.xcontent.ObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.Objects; - -public class DeleteWatchResponse { - - private static final ObjectParser PARSER = new ObjectParser<>( - "x_pack_delete_watch_response", - true, - DeleteWatchResponse::new - ); - static { - PARSER.declareString(DeleteWatchResponse::setId, new ParseField("_id")); - PARSER.declareLong(DeleteWatchResponse::setVersion, new ParseField("_version")); - PARSER.declareBoolean(DeleteWatchResponse::setFound, new ParseField("found")); - } - - private String id; - private long version; - private boolean found; - - public DeleteWatchResponse() {} - - public DeleteWatchResponse(String id, long version, boolean found) { - this.id = id; - this.version = version; - this.found = found; - } - - public String getId() { - return id; - } - - public long getVersion() { - return version; - } - - public boolean isFound() { - return found; - } - - private void setId(String id) { - this.id = id; - } - - private void setVersion(long version) { - this.version = version; - } - - private void setFound(boolean found) { - this.found = found; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - DeleteWatchResponse that = (DeleteWatchResponse) o; - - return Objects.equals(id, that.id) && Objects.equals(version, that.version) && Objects.equals(found, that.found); - } - - @Override - public int hashCode() { - return Objects.hash(id, version, found); - } - - public static DeleteWatchResponse fromXContent(XContentParser parser) throws IOException { - return PARSER.parse(parser, null); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/ExecuteWatchRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/ExecuteWatchRequest.java deleted file mode 100644 index 64eea83fe3e6e..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/ExecuteWatchRequest.java +++ /dev/null @@ -1,167 +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.watcher; - -import org.elasticsearch.client.Validatable; -import org.elasticsearch.common.bytes.BytesArray; -import org.elasticsearch.common.bytes.BytesReference; -import org.elasticsearch.core.Nullable; -import org.elasticsearch.xcontent.ToXContentObject; -import org.elasticsearch.xcontent.XContentBuilder; -import org.elasticsearch.xcontent.XContentType; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; - -/** - * An execute watch request to execute a watch by id or inline - */ -public class ExecuteWatchRequest implements Validatable, ToXContentObject { - - public enum ActionExecutionMode { - SIMULATE, - FORCE_SIMULATE, - EXECUTE, - FORCE_EXECUTE, - SKIP - } - - private final String id; - private final BytesReference watchContent; - - private boolean ignoreCondition = false; - private boolean recordExecution = false; - private boolean debug = false; - - @Nullable - private BytesReference triggerData = null; - - @Nullable - private BytesReference alternativeInput = null; - - private Map actionModes = new HashMap<>(); - - /** - * Execute an existing watch on the cluster - * - * @param id the id of the watch to execute - */ - public static ExecuteWatchRequest byId(String id) { - return new ExecuteWatchRequest(Objects.requireNonNull(id, "Watch id cannot be null"), null); - } - - /** - * Execute an inline watch - * @param watchContent the JSON definition of the watch - */ - public static ExecuteWatchRequest inline(String watchContent) { - return new ExecuteWatchRequest(null, Objects.requireNonNull(watchContent, "Watch content cannot be null")); - } - - private ExecuteWatchRequest(String id, String watchContent) { - this.id = id; - this.watchContent = watchContent == null ? null : new BytesArray(watchContent); - } - - public String getId() { - return this.id; - } - - /** - * @param ignoreCondition set if the condition for this execution be ignored - */ - public void setIgnoreCondition(boolean ignoreCondition) { - this.ignoreCondition = ignoreCondition; - } - - public boolean ignoreCondition() { - return ignoreCondition; - } - - /** - * @param recordExecution Sets if this execution be recorded in the history index - */ - public void setRecordExecution(boolean recordExecution) { - if (watchContent != null && recordExecution) { - throw new IllegalArgumentException("The execution of an inline watch cannot be recorded"); - } - this.recordExecution = recordExecution; - } - - public boolean recordExecution() { - return recordExecution; - } - - /** - * @param alternativeInput Sets the alternative input - */ - public void setAlternativeInput(String alternativeInput) { - this.alternativeInput = new BytesArray(alternativeInput); - } - - /** - * @param data A JSON string representing the data that should be associated with the trigger event. - */ - public void setTriggerData(String data) { - this.triggerData = new BytesArray(data); - } - - /** - * Sets the action execution mode for the give action (identified by its id). - * - * @param actionId the action id. - * @param actionMode the execution mode of the action. - */ - public void setActionMode(String actionId, ActionExecutionMode actionMode) { - Objects.requireNonNull(actionId, "actionId cannot be null"); - actionModes.put(actionId, actionMode); - } - - public Map getActionModes() { - return this.actionModes; - } - - /** - * @param debug indicates whether the watch should execute in debug mode. In debug mode the - * returned watch record will hold the execution {@code vars} - */ - public void setDebug(boolean debug) { - this.debug = debug; - } - - public boolean isDebug() { - return debug; - } - - @Override - public String toString() { - return "execute[" + id + "]"; - } - - @Override - public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { - builder.startObject(); - if (triggerData != null) { - builder.rawField("trigger_data", triggerData.streamInput(), XContentType.JSON); - } - if (alternativeInput != null) { - builder.rawField("alternative_input", alternativeInput.streamInput(), XContentType.JSON); - } - if (actionModes.size() > 0) { - builder.field("action_modes", actionModes); - } - if (watchContent != null) { - builder.rawField("watch", watchContent.streamInput(), XContentType.JSON); - } - builder.endObject(); - return builder; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/ExecuteWatchResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/ExecuteWatchResponse.java deleted file mode 100644 index cb8c77bdd26fc..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/ExecuteWatchResponse.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.watcher; - -import org.elasticsearch.ElasticsearchException; -import org.elasticsearch.common.bytes.BytesReference; -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.NamedXContentRegistry; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentBuilder; -import org.elasticsearch.xcontent.XContentFactory; -import org.elasticsearch.xcontent.XContentParser; -import org.elasticsearch.xcontent.XContentType; -import org.elasticsearch.xcontent.XContentUtils; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Map; - -public class ExecuteWatchResponse { - - public static final ParseField ID_FIELD = new ParseField("_id"); - public static final ParseField WATCH_FIELD = new ParseField("watch_record"); - - private String recordId; - private BytesReference contentSource; - - private Map data; - - public ExecuteWatchResponse() {} - - public ExecuteWatchResponse(String recordId, BytesReference contentSource) { - this.recordId = recordId; - this.contentSource = contentSource; - } - - /** - * @return The id of the watch record holding the watch execution result. - */ - public String getRecordId() { - return recordId; - } - - /** - * @return The watch record source - */ - public BytesReference getRecord() { - return contentSource; - } - - /** - * Returns the watch record as a map - * - * Use {@link org.elasticsearch.xcontent.ObjectPath} to navigate through the data - */ - @SuppressWarnings("unchecked") - public Map getRecordAsMap() { - if (data == null) { - // EMPTY is safe here because we never use namedObject - try ( - InputStream stream = contentSource.streamInput(); - XContentParser parser = XContentType.JSON.xContent().createParser(NamedXContentRegistry.EMPTY, null, stream) - ) { - data = (Map) XContentUtils.readValue(parser, parser.nextToken()); - } catch (IOException ex) { - throw new ElasticsearchException("failed to read value", ex); - } - } - return data; - } - - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "x_pack_execute_watch_response", - true, - (fields) -> new ExecuteWatchResponse((String) fields[0], (BytesReference) fields[1]) - ); - static { - PARSER.declareString(ConstructingObjectParser.constructorArg(), ID_FIELD); - PARSER.declareObject(ConstructingObjectParser.constructorArg(), (p, c) -> readBytesReference(p), WATCH_FIELD); - } - - public static ExecuteWatchResponse fromXContent(XContentParser parser) throws IOException { - return PARSER.parse(parser, null); - } - - private static BytesReference readBytesReference(XContentParser parser) throws IOException { - try (XContentBuilder builder = XContentFactory.jsonBuilder()) { - builder.copyCurrentStructure(parser); - return BytesReference.bytes(builder); - } - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/ExecutionPhase.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/ExecutionPhase.java deleted file mode 100644 index 5f95ee5309a23..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/ExecutionPhase.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.watcher; - -public enum ExecutionPhase { - - // awaiting execution of the watch - AWAITS_EXECUTION(false), - // initial phase, watch execution has started, but the input is not yet processed - STARTED(false), - // input is being executed - INPUT(false), - // condition phase is being executed - CONDITION(false), - // transform phase (optional, depends if a global transform was configured in the watch) - WATCH_TRANSFORM(false), - // actions phase, all actions, including specific action transforms - ACTIONS(false), - // missing watch, failed execution of input/condition/transform, - ABORTED(true), - // successful run - FINISHED(true); - - private final boolean sealed; - - ExecutionPhase(boolean sealed) { - this.sealed = sealed; - } - - public boolean sealed() { - return sealed; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/ExecutionState.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/ExecutionState.java deleted file mode 100644 index fe07896409edb..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/ExecutionState.java +++ /dev/null @@ -1,57 +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.watcher; - -import java.util.Locale; - -public enum ExecutionState { - - // the condition of the watch was not met - EXECUTION_NOT_NEEDED, - - // Execution has been throttled due to time-based throttling - this might only affect a single action though - THROTTLED, - - // Execution has been throttled due to ack-based throttling/muting of an action - this might only affect a single action though - ACKNOWLEDGED, - - // regular execution - EXECUTED, - - // an error in the condition or the execution of the input - FAILED, - - // a rejection due to a filled up threadpool - THREADPOOL_REJECTION, - - // the execution was scheduled, but in between the watch was deleted - NOT_EXECUTED_WATCH_MISSING, - - // even though the execution was scheduled, it was not executed, because the watch was already queued in the thread pool - NOT_EXECUTED_ALREADY_QUEUED, - - // this can happen when a watch was executed, but not completely finished (the triggered watch entry was not deleted), and then - // watcher is restarted (manually or due to host switch) - the triggered watch will be executed but the history entry already - // exists - EXECUTED_MULTIPLE_TIMES; - - public String id() { - return name().toLowerCase(Locale.ROOT); - } - - public static ExecutionState resolve(String id) { - return valueOf(id.toUpperCase(Locale.ROOT)); - } - - @Override - public String toString() { - return id(); - } - -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/GetWatchRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/GetWatchRequest.java deleted file mode 100644 index 1f044352555c2..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/GetWatchRequest.java +++ /dev/null @@ -1,43 +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.watcher; - -import org.elasticsearch.client.Validatable; -import org.elasticsearch.client.ValidationException; - -/** - * The request to get the watch by name (id) - */ -public final class GetWatchRequest implements Validatable { - - private final String id; - - public GetWatchRequest(String watchId) { - validateId(watchId); - this.id = watchId; - } - - private void validateId(String watchId) { - ValidationException exception = new ValidationException(); - if (watchId == null) { - exception.addValidationError("watch id is missing"); - } else if (PutWatchRequest.isValidId(watchId) == false) { - exception.addValidationError("watch id contains whitespace"); - } - if (exception.validationErrors().isEmpty() == false) { - throw exception; - } - } - - /** - * @return The name of the watch to retrieve - */ - public String getId() { - return id; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/GetWatchResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/GetWatchResponse.java deleted file mode 100644 index 389280ae6a811..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/GetWatchResponse.java +++ /dev/null @@ -1,176 +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.watcher; - -import org.elasticsearch.common.bytes.BytesReference; -import org.elasticsearch.common.lucene.uid.Versions; -import org.elasticsearch.common.xcontent.XContentHelper; -import org.elasticsearch.xcontent.ConstructingObjectParser; -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.Map; -import java.util.Objects; - -import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_PRIMARY_TERM; -import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO; - -public class GetWatchResponse { - private final String id; - private final long version; - private final long seqNo; - private final long primaryTerm; - private final WatchStatus status; - - private final BytesReference source; - private final XContentType xContentType; - - /** - * Ctor for missing watch - */ - public GetWatchResponse(String id) { - this(id, Versions.NOT_FOUND, UNASSIGNED_SEQ_NO, UNASSIGNED_PRIMARY_TERM, null, null, null); - } - - public GetWatchResponse( - String id, - long version, - long seqNo, - long primaryTerm, - WatchStatus status, - BytesReference source, - XContentType xContentType - ) { - this.id = id; - this.version = version; - this.status = status; - this.source = source; - this.xContentType = xContentType; - this.seqNo = seqNo; - this.primaryTerm = primaryTerm; - } - - public String getId() { - return id; - } - - public long getVersion() { - return version; - } - - public long getSeqNo() { - return seqNo; - } - - public long getPrimaryTerm() { - return primaryTerm; - } - - public boolean isFound() { - return version != Versions.NOT_FOUND; - } - - public WatchStatus getStatus() { - return status; - } - - /** - * Returns the {@link XContentType} of the source - */ - public XContentType getContentType() { - return xContentType; - } - - /** - * Returns the serialized watch - */ - public BytesReference getSource() { - return source; - } - - /** - * Returns the source as a map - */ - public Map getSourceAsMap() { - return source == null ? null : XContentHelper.convertToMap(source, false, getContentType()).v2(); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - GetWatchResponse that = (GetWatchResponse) o; - return version == that.version - && Objects.equals(id, that.id) - && Objects.equals(status, that.status) - && Objects.equals(xContentType, that.xContentType) - && Objects.equals(source, that.source); - } - - @Override - public int hashCode() { - return Objects.hash(id, status, source, version); - } - - private static final ParseField ID_FIELD = new ParseField("_id"); - private static final ParseField FOUND_FIELD = new ParseField("found"); - private static final ParseField VERSION_FIELD = new ParseField("_version"); - private static final ParseField SEQ_NO_FIELD = new ParseField("_seq_no"); - private static final ParseField PRIMARY_TERM_FIELD = new ParseField("_primary_term"); - private static final ParseField STATUS_FIELD = new ParseField("status"); - private static final ParseField WATCH_FIELD = new ParseField("watch"); - - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "get_watch_response", - true, - a -> { - boolean isFound = (boolean) a[1]; - if (isFound) { - XContentBuilder builder = (XContentBuilder) a[6]; - BytesReference source = BytesReference.bytes(builder); - return new GetWatchResponse( - (String) a[0], - (long) a[2], - (long) a[3], - (long) a[4], - (WatchStatus) a[5], - source, - builder.contentType() - ); - } else { - return new GetWatchResponse((String) a[0]); - } - } - ); - - static { - PARSER.declareString(ConstructingObjectParser.constructorArg(), ID_FIELD); - PARSER.declareBoolean(ConstructingObjectParser.constructorArg(), FOUND_FIELD); - PARSER.declareLong(ConstructingObjectParser.optionalConstructorArg(), VERSION_FIELD); - PARSER.declareLong(ConstructingObjectParser.optionalConstructorArg(), SEQ_NO_FIELD); - PARSER.declareLong(ConstructingObjectParser.optionalConstructorArg(), PRIMARY_TERM_FIELD); - PARSER.declareObject( - ConstructingObjectParser.optionalConstructorArg(), - (parser, context) -> WatchStatus.parse(parser), - STATUS_FIELD - ); - PARSER.declareObject(ConstructingObjectParser.optionalConstructorArg(), (parser, context) -> { - try (XContentBuilder builder = XContentBuilder.builder(parser.contentType().xContent())) { - builder.copyCurrentStructure(parser); - return builder; - } - }, WATCH_FIELD); - } - - public static GetWatchResponse fromXContent(XContentParser parser) throws IOException { - return PARSER.parse(parser, null); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/PutWatchRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/PutWatchRequest.java deleted file mode 100644 index bd53a0c20eb9e..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/PutWatchRequest.java +++ /dev/null @@ -1,136 +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.watcher; - -import org.elasticsearch.client.Validatable; -import org.elasticsearch.common.Strings; -import org.elasticsearch.common.bytes.BytesReference; -import org.elasticsearch.index.seqno.SequenceNumbers; -import org.elasticsearch.xcontent.XContentType; - -import java.util.Objects; -import java.util.regex.Pattern; - -import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_PRIMARY_TERM; -import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO; - -/** - * This request class contains the data needed to create a watch along with the name of the watch. - * The name of the watch will become the ID of the indexed document. - */ -public final class PutWatchRequest implements Validatable { - - private static final Pattern NO_WS_PATTERN = Pattern.compile("\\S+"); - - private final String id; - private final BytesReference source; - private final XContentType xContentType; - private boolean active = true; - private long ifSeqNo = SequenceNumbers.UNASSIGNED_SEQ_NO; - private long ifPrimaryTerm = UNASSIGNED_PRIMARY_TERM; - - public PutWatchRequest(String id, BytesReference source, XContentType xContentType) { - Objects.requireNonNull(id, "watch id is missing"); - if (isValidId(id) == false) { - throw new IllegalArgumentException("watch id contains whitespace"); - } - Objects.requireNonNull(source, "watch source is missing"); - Objects.requireNonNull(xContentType, "request body is missing"); - this.id = id; - this.source = source; - this.xContentType = xContentType; - } - - /** - * @return The name that will be the ID of the indexed document - */ - public String getId() { - return id; - } - - /** - * @return The source of the watch - */ - public BytesReference getSource() { - return source; - } - - /** - * @return The initial active state of the watch (defaults to {@code true}, e.g. "active") - */ - public boolean isActive() { - return active; - } - - /** - * Sets the initial active state of the watch - */ - public void setActive(boolean active) { - this.active = active; - } - - /** - * Get the content type for the source - */ - public XContentType xContentType() { - return xContentType; - } - - /** - * only performs this put request if the watch's last modification was assigned the given - * sequence number. Must be used in combination with {@link #setIfPrimaryTerm(long)} - * - * If the watch's last modification was assigned a different sequence number a - * {@link org.elasticsearch.index.engine.VersionConflictEngineException} will be thrown. - */ - public PutWatchRequest setIfSeqNo(long seqNo) { - if (seqNo < 0 && seqNo != UNASSIGNED_SEQ_NO) { - throw new IllegalArgumentException("sequence numbers must be non negative. got [" + seqNo + "]."); - } - ifSeqNo = seqNo; - return this; - } - - /** - * only performs this put request if the watch's last modification was assigned the given - * primary term. Must be used in combination with {@link #setIfSeqNo(long)} - * - * If the watch last modification was assigned a different term a - * {@link org.elasticsearch.index.engine.VersionConflictEngineException} will be thrown. - */ - public PutWatchRequest setIfPrimaryTerm(long term) { - if (term < 0) { - throw new IllegalArgumentException("primary term must be non negative. got [" + term + "]"); - } - ifPrimaryTerm = term; - return this; - } - - /** - * If set, only perform this put watch request if the watch's last modification was assigned this sequence number. - * If the watch last last modification was assigned a different sequence number a - * {@link org.elasticsearch.index.engine.VersionConflictEngineException} will be thrown. - */ - public long ifSeqNo() { - return ifSeqNo; - } - - /** - * If set, only perform this put watch request if the watch's last modification was assigned this primary term. - * - * If the watch's last modification was assigned a different term a - * {@link org.elasticsearch.index.engine.VersionConflictEngineException} will be thrown. - */ - public long ifPrimaryTerm() { - return ifPrimaryTerm; - } - - public static boolean isValidId(String id) { - return Strings.isEmpty(id) == false && NO_WS_PATTERN.matcher(id).matches(); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/PutWatchResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/PutWatchResponse.java deleted file mode 100644 index 7d7c23ec2cac2..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/PutWatchResponse.java +++ /dev/null @@ -1,113 +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.watcher; - -import org.elasticsearch.index.seqno.SequenceNumbers; -import org.elasticsearch.xcontent.ObjectParser; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.util.Objects; - -public class PutWatchResponse { - - private static final ObjectParser PARSER = new ObjectParser<>( - "x_pack_put_watch_response", - true, - PutWatchResponse::new - ); - - static { - PARSER.declareString(PutWatchResponse::setId, new ParseField("_id")); - PARSER.declareLong(PutWatchResponse::setSeqNo, new ParseField("_seq_no")); - PARSER.declareLong(PutWatchResponse::setPrimaryTerm, new ParseField("_primary_term")); - PARSER.declareLong(PutWatchResponse::setVersion, new ParseField("_version")); - PARSER.declareBoolean(PutWatchResponse::setCreated, new ParseField("created")); - } - - private String id; - private long version; - private long seqNo = SequenceNumbers.UNASSIGNED_SEQ_NO; - private long primaryTerm = SequenceNumbers.UNASSIGNED_PRIMARY_TERM; - private boolean created; - - public PutWatchResponse() {} - - public PutWatchResponse(String id, long version, long seqNo, long primaryTerm, boolean created) { - this.id = id; - this.version = version; - this.seqNo = seqNo; - this.primaryTerm = primaryTerm; - this.created = created; - } - - private void setId(String id) { - this.id = id; - } - - private void setVersion(long version) { - this.version = version; - } - - private void setSeqNo(long seqNo) { - this.seqNo = seqNo; - } - - private void setPrimaryTerm(long primaryTerm) { - this.primaryTerm = primaryTerm; - } - - private void setCreated(boolean created) { - this.created = created; - } - - public String getId() { - return id; - } - - public long getVersion() { - return version; - } - - public long getSeqNo() { - return seqNo; - } - - public long getPrimaryTerm() { - return primaryTerm; - } - - public boolean isCreated() { - return created; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - PutWatchResponse that = (PutWatchResponse) o; - - return Objects.equals(id, that.id) - && Objects.equals(version, that.version) - && Objects.equals(seqNo, that.seqNo) - && Objects.equals(primaryTerm, that.primaryTerm) - && Objects.equals(created, that.created); - } - - @Override - public int hashCode() { - return Objects.hash(id, version, seqNo, primaryTerm, created); - } - - public static PutWatchResponse fromXContent(XContentParser parser) throws IOException { - return PARSER.parse(parser, null); - } - -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/QueuedWatch.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/QueuedWatch.java deleted file mode 100644 index 6af59862b5278..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/QueuedWatch.java +++ /dev/null @@ -1,82 +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.watcher; - -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; - -import java.time.ZonedDateTime; -import java.util.Objects; - -public class QueuedWatch { - - @SuppressWarnings("unchecked") - public static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "watcher_stats_node", - true, - (args, c) -> new QueuedWatch( - (String) args[0], - (String) args[1], - ZonedDateTime.parse((String) args[2]), - ZonedDateTime.parse((String) args[3]) - ) - ); - - static { - PARSER.declareString(ConstructingObjectParser.constructorArg(), new ParseField("watch_id")); - PARSER.declareString(ConstructingObjectParser.constructorArg(), new ParseField("watch_record_id")); - PARSER.declareString(ConstructingObjectParser.constructorArg(), new ParseField("triggered_time")); - PARSER.declareString(ConstructingObjectParser.constructorArg(), new ParseField("execution_time")); - } - - private final String watchId; - private final String watchRecordId; - private final ZonedDateTime triggeredTime; - private final ZonedDateTime executionTime; - - public QueuedWatch(String watchId, String watchRecordId, ZonedDateTime triggeredTime, ZonedDateTime executionTime) { - this.watchId = watchId; - this.watchRecordId = watchRecordId; - this.triggeredTime = triggeredTime; - this.executionTime = executionTime; - } - - public String getWatchId() { - return watchId; - } - - public String getWatchRecordId() { - return watchRecordId; - } - - public ZonedDateTime getTriggeredTime() { - return triggeredTime; - } - - public ZonedDateTime getExecutionTime() { - return executionTime; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - QueuedWatch that = (QueuedWatch) o; - return Objects.equals(watchId, that.watchId) - && Objects.equals(watchRecordId, that.watchRecordId) - && Objects.equals(triggeredTime, that.triggeredTime) - && Objects.equals(executionTime, that.executionTime); - } - - @Override - public int hashCode() { - - return Objects.hash(watchId, watchRecordId, triggeredTime, executionTime); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/StartWatchServiceRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/StartWatchServiceRequest.java deleted file mode 100644 index 1c87c131c4fdd..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/StartWatchServiceRequest.java +++ /dev/null @@ -1,15 +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.watcher; - -import org.elasticsearch.client.Validatable; - -public class StartWatchServiceRequest implements Validatable { - -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/StopWatchServiceRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/StopWatchServiceRequest.java deleted file mode 100644 index e0ca8cdb52ddc..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/StopWatchServiceRequest.java +++ /dev/null @@ -1,15 +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.watcher; - -import org.elasticsearch.client.Validatable; - -public class StopWatchServiceRequest implements Validatable { - -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/WatchExecutionSnapshot.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/WatchExecutionSnapshot.java deleted file mode 100644 index 0c549444ec35b..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/WatchExecutionSnapshot.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.watcher; - -import org.elasticsearch.xcontent.ConstructingObjectParser; -import org.elasticsearch.xcontent.ParseField; - -import java.time.ZonedDateTime; -import java.util.Arrays; -import java.util.List; -import java.util.Locale; -import java.util.Objects; - -public class WatchExecutionSnapshot { - @SuppressWarnings("unchecked") - public static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "watcher_stats_node", - true, - (args, c) -> new WatchExecutionSnapshot( - (String) args[0], - (String) args[1], - ZonedDateTime.parse((String) args[2]), - ZonedDateTime.parse((String) args[3]), - ExecutionPhase.valueOf(((String) args[4]).toUpperCase(Locale.ROOT)), - args[5] == null ? null : ((List) args[5]).toArray(new String[0]), - args[6] == null ? null : ((List) args[6]).toArray(new String[0]) - ) - ); - - static { - PARSER.declareString(ConstructingObjectParser.constructorArg(), new ParseField("watch_id")); - PARSER.declareString(ConstructingObjectParser.constructorArg(), new ParseField("watch_record_id")); - PARSER.declareString(ConstructingObjectParser.constructorArg(), new ParseField("triggered_time")); - PARSER.declareString(ConstructingObjectParser.constructorArg(), new ParseField("execution_time")); - PARSER.declareString(ConstructingObjectParser.constructorArg(), new ParseField("execution_phase")); - PARSER.declareStringArray(ConstructingObjectParser.optionalConstructorArg(), new ParseField("executed_actions")); - PARSER.declareStringArray(ConstructingObjectParser.optionalConstructorArg(), new ParseField("stack_trace")); - } - - private final String watchId; - private final String watchRecordId; - private final ZonedDateTime triggeredTime; - private final ZonedDateTime executionTime; - private final ExecutionPhase phase; - private final String[] executedActions; - private final String[] executionStackTrace; - - public WatchExecutionSnapshot( - String watchId, - String watchRecordId, - ZonedDateTime triggeredTime, - ZonedDateTime executionTime, - ExecutionPhase phase, - String[] executedActions, - String[] executionStackTrace - ) { - this.watchId = watchId; - this.watchRecordId = watchRecordId; - this.triggeredTime = triggeredTime; - this.executionTime = executionTime; - this.phase = phase; - this.executedActions = executedActions; - this.executionStackTrace = executionStackTrace; - } - - public String getWatchId() { - return watchId; - } - - public String getWatchRecordId() { - return watchRecordId; - } - - public ZonedDateTime getTriggeredTime() { - return triggeredTime; - } - - public ZonedDateTime getExecutionTime() { - return executionTime; - } - - public ExecutionPhase getPhase() { - return phase; - } - - public String[] getExecutedActions() { - return executedActions; - } - - public String[] getExecutionStackTrace() { - return executionStackTrace; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - WatchExecutionSnapshot that = (WatchExecutionSnapshot) o; - return Objects.equals(watchId, that.watchId) - && Objects.equals(watchRecordId, that.watchRecordId) - && Objects.equals(triggeredTime, that.triggeredTime) - && Objects.equals(executionTime, that.executionTime) - && phase == that.phase - && Arrays.equals(executedActions, that.executedActions) - && Arrays.equals(executionStackTrace, that.executionStackTrace); - } - - @Override - public int hashCode() { - - int result = Objects.hash(watchId, watchRecordId, triggeredTime, executionTime, phase); - result = 31 * result + Arrays.hashCode(executedActions); - result = 31 * result + Arrays.hashCode(executionStackTrace); - return result; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/WatchStatus.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/WatchStatus.java deleted file mode 100644 index e459453c246a7..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/WatchStatus.java +++ /dev/null @@ -1,261 +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.watcher; - -import org.elasticsearch.ElasticsearchParseException; -import org.elasticsearch.core.Nullable; -import org.elasticsearch.xcontent.ParseField; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; - -import static java.util.Collections.emptyMap; -import static java.util.Collections.unmodifiableMap; -import static org.elasticsearch.client.watcher.WatchStatusDateParser.parseDate; -import static org.elasticsearch.common.xcontent.XContentParserUtils.ensureExpectedToken; - -public class WatchStatus { - - private final State state; - - private final ExecutionState executionState; - private final ZonedDateTime lastChecked; - private final ZonedDateTime lastMetCondition; - private final long version; - private final Map actions; - @Nullable - private Map headers; - - public WatchStatus( - long version, - State state, - ExecutionState executionState, - ZonedDateTime lastChecked, - ZonedDateTime lastMetCondition, - Map actions, - Map headers - ) { - this.version = version; - this.lastChecked = lastChecked; - this.lastMetCondition = lastMetCondition; - this.actions = actions; - this.state = state; - this.executionState = executionState; - this.headers = headers; - } - - public State state() { - return state; - } - - public boolean checked() { - return lastChecked != null; - } - - public ZonedDateTime lastChecked() { - return lastChecked; - } - - public ZonedDateTime lastMetCondition() { - return lastMetCondition; - } - - public ActionStatus actionStatus(String actionId) { - return actions.get(actionId); - } - - public Map getActions() { - return actions; - } - - public long version() { - return version; - } - - public ExecutionState getExecutionState() { - return executionState; - } - - public Map getHeaders() { - return headers; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - WatchStatus that = (WatchStatus) o; - - return Objects.equals(lastChecked, that.lastChecked) - && Objects.equals(lastMetCondition, that.lastMetCondition) - && Objects.equals(version, that.version) - && Objects.equals(executionState, that.executionState) - && Objects.equals(actions, that.actions) - && Objects.equals(headers, that.headers); - } - - @Override - public int hashCode() { - return Objects.hash(lastChecked, lastMetCondition, actions, version, executionState); - } - - public static WatchStatus parse(XContentParser parser) throws IOException { - State state = null; - ExecutionState executionState = null; - ZonedDateTime lastChecked = null; - ZonedDateTime lastMetCondition = null; - Map actions = null; - Map headers = Collections.emptyMap(); - long version = -1; - - ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.currentToken(), parser); - - String currentFieldName = null; - XContentParser.Token token; - - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else if (Field.STATE.match(currentFieldName, parser.getDeprecationHandler())) { - try { - state = State.parse(parser); - } catch (ElasticsearchParseException e) { - throw new ElasticsearchParseException("could not parse watch status. failed to parse field [{}]", e, currentFieldName); - } - } else if (Field.VERSION.match(currentFieldName, parser.getDeprecationHandler())) { - if (token.isValue()) { - version = parser.longValue(); - } else { - throw new ElasticsearchParseException( - "could not parse watch status. expecting field [{}] to hold a long " + "value, found [{}] instead", - currentFieldName, - token - ); - } - } else if (Field.LAST_CHECKED.match(currentFieldName, parser.getDeprecationHandler())) { - if (token.isValue()) { - lastChecked = parseDate(currentFieldName, parser); - } else { - throw new ElasticsearchParseException( - "could not parse watch status. expecting field [{}] to hold a date " + "value, found [{}] instead", - currentFieldName, - token - ); - } - } else if (Field.LAST_MET_CONDITION.match(currentFieldName, parser.getDeprecationHandler())) { - if (token.isValue()) { - lastMetCondition = parseDate(currentFieldName, parser); - } else { - throw new ElasticsearchParseException( - "could not parse watch status. expecting field [{}] to hold a date " + "value, found [{}] instead", - currentFieldName, - token - ); - } - } else if (Field.EXECUTION_STATE.match(currentFieldName, parser.getDeprecationHandler())) { - if (token.isValue()) { - executionState = ExecutionState.resolve(parser.text()); - } else { - throw new ElasticsearchParseException( - "could not parse watch status. expecting field [{}] to hold a string " + "value, found [{}] instead", - currentFieldName, - token - ); - } - } else if (Field.ACTIONS.match(currentFieldName, parser.getDeprecationHandler())) { - actions = new HashMap<>(); - if (token == XContentParser.Token.START_OBJECT) { - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else { - ActionStatus actionStatus = ActionStatus.parse(currentFieldName, parser); - actions.put(currentFieldName, actionStatus); - } - } - } else { - throw new ElasticsearchParseException( - "could not parse watch status. expecting field [{}] to be an object, " + "found [{}] instead", - currentFieldName, - token - ); - } - } else if (Field.HEADERS.match(currentFieldName, parser.getDeprecationHandler())) { - if (token == XContentParser.Token.START_OBJECT) { - headers = parser.mapStrings(); - } - } else { - parser.skipChildren(); - } - } - - actions = actions == null ? emptyMap() : unmodifiableMap(actions); - return new WatchStatus(version, state, executionState, lastChecked, lastMetCondition, actions, headers); - } - - public static class State { - - private final boolean active; - private final ZonedDateTime timestamp; - - public State(boolean active, ZonedDateTime timestamp) { - this.active = active; - this.timestamp = timestamp; - } - - public boolean isActive() { - return active; - } - - public ZonedDateTime getTimestamp() { - return timestamp; - } - - public static State parse(XContentParser parser) throws IOException { - if (parser.currentToken() != XContentParser.Token.START_OBJECT) { - throw new ElasticsearchParseException("expected an object but found [{}] instead", parser.currentToken()); - } - boolean active = true; - ZonedDateTime timestamp = ZonedDateTime.now(ZoneOffset.UTC); - String currentFieldName = null; - XContentParser.Token token; - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else if (Field.ACTIVE.match(currentFieldName, parser.getDeprecationHandler())) { - active = parser.booleanValue(); - } else if (Field.TIMESTAMP.match(currentFieldName, parser.getDeprecationHandler())) { - timestamp = parseDate(currentFieldName, parser); - } else { - parser.skipChildren(); - } - } - return new State(active, timestamp); - } - } - - public interface Field { - ParseField STATE = new ParseField("state"); - ParseField ACTIVE = new ParseField("active"); - ParseField TIMESTAMP = new ParseField("timestamp"); - ParseField LAST_CHECKED = new ParseField("last_checked"); - ParseField LAST_MET_CONDITION = new ParseField("last_met_condition"); - ParseField ACTIONS = new ParseField("actions"); - ParseField VERSION = new ParseField("version"); - ParseField EXECUTION_STATE = new ParseField("execution_state"); - ParseField HEADERS = new ParseField("headers"); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/WatchStatusDateParser.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/WatchStatusDateParser.java deleted file mode 100644 index f20dab54fd462..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/WatchStatusDateParser.java +++ /dev/null @@ -1,52 +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.watcher; - -import org.elasticsearch.ElasticsearchParseException; -import org.elasticsearch.common.time.DateFormatter; -import org.elasticsearch.common.time.DateFormatters; -import org.elasticsearch.index.mapper.DateFieldMapper; -import org.elasticsearch.xcontent.XContentParser; - -import java.io.IOException; -import java.time.Instant; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; - -public final class WatchStatusDateParser { - - private static final DateFormatter FORMATTER = DateFieldMapper.DEFAULT_DATE_TIME_FORMATTER; - - private WatchStatusDateParser() { - // Prevent instantiation. - } - - public static ZonedDateTime parseDate(String fieldName, XContentParser parser) throws IOException { - XContentParser.Token token = parser.currentToken(); - if (token == XContentParser.Token.VALUE_NUMBER) { - return Instant.ofEpochMilli(parser.longValue()).atZone(ZoneOffset.UTC); - } - if (token == XContentParser.Token.VALUE_STRING) { - ZonedDateTime dateTime = parseDate(parser.text()); - return dateTime.withZoneSameInstant(ZoneOffset.UTC); - } - if (token == XContentParser.Token.VALUE_NULL) { - return null; - } - throw new ElasticsearchParseException( - "could not parse date/time. expected date field [{}] " + "to be either a number or a string but found [{}] instead", - fieldName, - token - ); - } - - public static ZonedDateTime parseDate(String text) { - return DateFormatters.from(FORMATTER.parse(text)); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/WatcherMetadata.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/WatcherMetadata.java deleted file mode 100644 index a380114d0657a..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/WatcherMetadata.java +++ /dev/null @@ -1,44 +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.watcher; - -import java.util.Objects; - -public class WatcherMetadata { - - private final boolean manuallyStopped; - - public WatcherMetadata(boolean manuallyStopped) { - this.manuallyStopped = manuallyStopped; - } - - public boolean manuallyStopped() { - return manuallyStopped; - } - - @Override - public String toString() { - return "manuallyStopped[" + manuallyStopped + "]"; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - WatcherMetadata action = (WatcherMetadata) o; - - return manuallyStopped == action.manuallyStopped; - } - - @Override - public int hashCode() { - return Objects.hash(manuallyStopped); - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/WatcherState.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/WatcherState.java deleted file mode 100644 index 26a873e7d776a..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/WatcherState.java +++ /dev/null @@ -1,42 +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.watcher; - -public enum WatcherState { - - /** - * The watcher plugin is not running and not functional. - */ - STOPPED(0), - - /** - * The watcher plugin is performing the necessary operations to get into a started state. - */ - STARTING(1), - - /** - * The watcher plugin is running and completely functional. - */ - STARTED(2), - - /** - * The watcher plugin is shutting down and not functional. - */ - STOPPING(3); - - private final byte id; - - WatcherState(int id) { - this.id = (byte) id; - } - - public byte getId() { - return id; - } - -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/WatcherStatsRequest.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/WatcherStatsRequest.java deleted file mode 100644 index 590eec690976b..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/WatcherStatsRequest.java +++ /dev/null @@ -1,42 +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.watcher; - -import org.elasticsearch.client.Validatable; - -/** - * A request to explicitly acknowledge a watch. - */ -public class WatcherStatsRequest implements Validatable { - - private final boolean includeCurrentWatches; - private final boolean includeQueuedWatches; - - public WatcherStatsRequest() { - this(true, true); - } - - public WatcherStatsRequest(boolean includeCurrentWatches, boolean includeQueuedWatches) { - this.includeCurrentWatches = includeCurrentWatches; - this.includeQueuedWatches = includeQueuedWatches; - } - - public boolean includeCurrentWatches() { - return includeCurrentWatches; - } - - public boolean includeQueuedWatches() { - return includeQueuedWatches; - } - - @Override - public String toString() { - return "stats [current=" + includeCurrentWatches + ", " + "queued=" + includeQueuedWatches + "]"; - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/WatcherStatsResponse.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/WatcherStatsResponse.java deleted file mode 100644 index 7daaf74e9db0f..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/WatcherStatsResponse.java +++ /dev/null @@ -1,248 +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.watcher; - -import org.elasticsearch.client.NodesResponseHeader; -import org.elasticsearch.core.Tuple; -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.Locale; -import java.util.Map; -import java.util.Objects; - -/** - * The response from an 'ack watch' request. - */ -public class WatcherStatsResponse { - - private final List nodes; - private final NodesResponseHeader header; - private final String clusterName; - - private final WatcherMetadata watcherMetadata; - - public WatcherStatsResponse(NodesResponseHeader header, String clusterName, WatcherMetadata watcherMetadata, List nodes) { - this.nodes = nodes; - this.header = header; - this.clusterName = clusterName; - this.watcherMetadata = watcherMetadata; - } - - /** - * @return the status of the requested watch. If an action was - * successfully acknowledged, this will be reflected in its status. - */ - public WatcherMetadata getWatcherMetadata() { - return watcherMetadata; - } - - /** - * returns a list of nodes that returned stats - */ - public List getNodes() { - return nodes; - } - - /** - * Gets information about the number of total, successful and failed nodes the request was run on. - * Also includes exceptions if relevant. - */ - public NodesResponseHeader getHeader() { - return header; - } - - /** - * Get the cluster name associated with all of the nodes. - * - * @return Never {@code null}. - */ - public String getClusterName() { - return clusterName; - } - - @SuppressWarnings("unchecked") - private static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "watcher_stats_response", - true, - a -> new WatcherStatsResponse((NodesResponseHeader) a[0], (String) a[1], new WatcherMetadata((boolean) a[2]), (List) a[3]) - ); - - static { - PARSER.declareObject(ConstructingObjectParser.constructorArg(), NodesResponseHeader::fromXContent, new ParseField("_nodes")); - PARSER.declareString(ConstructingObjectParser.constructorArg(), new ParseField("cluster_name")); - PARSER.declareBoolean(ConstructingObjectParser.constructorArg(), new ParseField("manually_stopped")); - PARSER.declareObjectArray(ConstructingObjectParser.constructorArg(), (p, c) -> Node.PARSER.apply(p, null), new ParseField("stats")); - } - - public static WatcherStatsResponse 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; - WatcherStatsResponse that = (WatcherStatsResponse) o; - return Objects.equals(nodes, that.nodes) - && Objects.equals(header, that.header) - && Objects.equals(clusterName, that.clusterName) - && Objects.equals(watcherMetadata, that.watcherMetadata); - } - - @Override - public int hashCode() { - - return Objects.hash(nodes, header, clusterName, watcherMetadata); - } - - public static class Node { - @SuppressWarnings("unchecked") - public static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>( - "watcher_stats_node", - true, - (args, c) -> new Node( - (String) args[0], - WatcherState.valueOf(((String) args[1]).toUpperCase(Locale.ROOT)), - (long) args[2], - ((Tuple) args[3]).v1(), - ((Tuple) args[3]).v2(), - (List) args[4], - (List) args[5], - (Map) args[6] - - ) - ); - - private static final ConstructingObjectParser, Void> THREAD_POOL_PARSER = new ConstructingObjectParser<>( - "execution_thread_pool", - true, - (args, id) -> new Tuple<>((Long) args[0], (Long) args[1]) - ); - - static { - PARSER.declareString(ConstructingObjectParser.constructorArg(), new ParseField("node_id")); - PARSER.declareString(ConstructingObjectParser.constructorArg(), new ParseField("watcher_state")); - PARSER.declareLong(ConstructingObjectParser.constructorArg(), new ParseField("watch_count")); - PARSER.declareObject( - ConstructingObjectParser.constructorArg(), - THREAD_POOL_PARSER::apply, - new ParseField("execution_thread_pool") - ); - PARSER.declareObjectArray( - ConstructingObjectParser.optionalConstructorArg(), - WatchExecutionSnapshot.PARSER, - new ParseField("current_watches") - ); - PARSER.declareObjectArray( - ConstructingObjectParser.optionalConstructorArg(), - QueuedWatch.PARSER, - new ParseField("queued_watches") - ); - PARSER.declareObject(ConstructingObjectParser.optionalConstructorArg(), (p, c) -> p.map(), new ParseField("stats")); - - THREAD_POOL_PARSER.declareLong(ConstructingObjectParser.constructorArg(), new ParseField("queue_size")); - THREAD_POOL_PARSER.declareLong(ConstructingObjectParser.constructorArg(), new ParseField("max_size")); - } - - private final String nodeId; - - private WatcherState watcherState; - private long watchesCount; - private long threadPoolQueueSize; - private long threadPoolMaxSize; - private List snapshots; - private List queuedWatches; - private Map stats; - - public Node( - String nodeId, - WatcherState watcherState, - long watchesCount, - long threadPoolQueueSize, - long threadPoolMaxSize, - List snapshots, - List queuedWatches, - Map stats - ) { - this.nodeId = nodeId; - this.watcherState = watcherState; - this.watchesCount = watchesCount; - this.threadPoolQueueSize = threadPoolQueueSize; - this.threadPoolMaxSize = threadPoolMaxSize; - this.snapshots = snapshots; - this.queuedWatches = queuedWatches; - this.stats = stats; - } - - public String getNodeId() { - return nodeId; - } - - public long getWatchesCount() { - return watchesCount; - } - - public WatcherState getWatcherState() { - return watcherState; - } - - public long getThreadPoolQueueSize() { - return threadPoolQueueSize; - } - - public long getThreadPoolMaxSize() { - return threadPoolMaxSize; - } - - public List getSnapshots() { - return snapshots; - } - - public List getQueuedWatches() { - return queuedWatches; - } - - public Map getStats() { - return stats; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - Node node = (Node) o; - return watchesCount == node.watchesCount - && threadPoolQueueSize == node.threadPoolQueueSize - && threadPoolMaxSize == node.threadPoolMaxSize - && Objects.equals(nodeId, node.nodeId) - && watcherState == node.watcherState - && Objects.equals(snapshots, node.snapshots) - && Objects.equals(queuedWatches, node.queuedWatches) - && Objects.equals(stats, node.stats); - } - - @Override - public int hashCode() { - return Objects.hash( - nodeId, - watcherState, - watchesCount, - threadPoolQueueSize, - threadPoolMaxSize, - snapshots, - queuedWatches, - stats - ); - } - } -} diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/package-info.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/package-info.java deleted file mode 100644 index 6e33925ae783e..0000000000000 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/watcher/package-info.java +++ /dev/null @@ -1,13 +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. - */ - -/** - * Request and Response objects for the default distribution's Watcher - * APIs. - */ -package org.elasticsearch.client.watcher;