[PURIFY] remove all trace of x-pack enrichment processor (#9)

This commit removes all trace of the Elastic licensed enrichment processor.

Signed-off-by: Peter Nied <petern@amazon.com>
This commit is contained in:
Nick Knize 2021-01-30 00:14:38 -06:00 committed by Peter Nied
parent a0b91cb230
commit 204122aae4
21 changed files with 1 additions and 2023 deletions

View File

@ -1,274 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.client.core.AcknowledgedResponse;
import org.elasticsearch.client.enrich.DeletePolicyRequest;
import org.elasticsearch.client.enrich.ExecutePolicyRequest;
import org.elasticsearch.client.enrich.ExecutePolicyResponse;
import org.elasticsearch.client.enrich.GetPolicyRequest;
import org.elasticsearch.client.enrich.GetPolicyResponse;
import org.elasticsearch.client.enrich.PutPolicyRequest;
import org.elasticsearch.client.enrich.StatsRequest;
import org.elasticsearch.client.enrich.StatsResponse;
import java.io.IOException;
import java.util.Collections;
/**
* A wrapper for the {@link RestHighLevelClient} that provides methods for
* accessing the Elastic enrich related methods
* <p>
* See the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/enrich-apis.html">
* X-Pack Enrich Policy APIs on elastic.co</a> for more information.
*/
public final class EnrichClient {
private final RestHighLevelClient restHighLevelClient;
EnrichClient(RestHighLevelClient restHighLevelClient) {
this.restHighLevelClient = restHighLevelClient;
}
/**
* Executes the put policy api, which stores an enrich policy.
*
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/put-enrich-policy-api.html">
* the docs</a> for more.
*
* @param request the {@link PutPolicyRequest}
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public AcknowledgedResponse putPolicy(PutPolicyRequest request, RequestOptions options) throws IOException {
return restHighLevelClient.performRequestAndParseEntity(
request,
EnrichRequestConverters::putPolicy,
options,
AcknowledgedResponse::fromXContent,
Collections.emptySet()
);
}
/**
* Asynchronously executes the put policy api, which stores an enrich policy.
*
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/put-enrich-policy-api.html">
* the docs</a> for more.
*
* @param request the {@link PutPolicyRequest}
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
* @return cancellable that may be used to cancel the request
*/
public Cancellable putPolicyAsync(PutPolicyRequest request,
RequestOptions options,
ActionListener<AcknowledgedResponse> listener) {
return restHighLevelClient.performRequestAsyncAndParseEntity(
request,
EnrichRequestConverters::putPolicy,
options,
AcknowledgedResponse::fromXContent,
listener,
Collections.emptySet()
);
}
/**
* Executes the delete policy api, which deletes an enrich policy.
*
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/delete-enrich-policy-api.html">
* the docs</a> for more.
*
* @param request the {@link DeletePolicyRequest}
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public AcknowledgedResponse deletePolicy(DeletePolicyRequest request, RequestOptions options) throws IOException {
return restHighLevelClient.performRequestAndParseEntity(
request,
EnrichRequestConverters::deletePolicy,
options,
AcknowledgedResponse::fromXContent,
Collections.emptySet()
);
}
/**
* Asynchronously executes the delete policy api, which deletes an enrich policy.
*
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/delete-enrich-policy-api.html">
* the docs</a> for more.
*
* @param request the {@link DeletePolicyRequest}
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
* @return cancellable that may be used to cancel the request
*/
public Cancellable deletePolicyAsync(DeletePolicyRequest request,
RequestOptions options,
ActionListener<AcknowledgedResponse> listener) {
return restHighLevelClient.performRequestAsyncAndParseEntity(
request,
EnrichRequestConverters::deletePolicy,
options,
AcknowledgedResponse::fromXContent,
listener,
Collections.emptySet()
);
}
/**
* Executes the get policy api, which retrieves an enrich policy.
*
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/get-enrich-policy-api.html">
* the docs</a> for more.
*
* @param request the {@link PutPolicyRequest}
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public GetPolicyResponse getPolicy(GetPolicyRequest request, RequestOptions options) throws IOException {
return restHighLevelClient.performRequestAndParseEntity(
request,
EnrichRequestConverters::getPolicy,
options,
GetPolicyResponse::fromXContent,
Collections.emptySet()
);
}
/**
* Asynchronously executes the get policy api, which retrieves an enrich policy.
*
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/get-enrich-policy-api.html">
* the docs</a> for more.
*
* @param request the {@link PutPolicyRequest}
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
* @return cancellable that may be used to cancel the request
*/
public Cancellable getPolicyAsync(GetPolicyRequest request,
RequestOptions options,
ActionListener<GetPolicyResponse> listener) {
return restHighLevelClient.performRequestAsyncAndParseEntity(
request,
EnrichRequestConverters::getPolicy,
options,
GetPolicyResponse::fromXContent,
listener,
Collections.emptySet()
);
}
/**
* Executes the enrich stats api, which retrieves enrich related stats.
*
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/enrich-stats-api.html">
* the docs</a> for more.
*
* @param request the {@link StatsRequest}
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public StatsResponse stats(StatsRequest request, RequestOptions options) throws IOException {
return restHighLevelClient.performRequestAndParseEntity(
request,
EnrichRequestConverters::stats,
options,
StatsResponse::fromXContent,
Collections.emptySet()
);
}
/**
* Asynchronously executes the enrich stats api, which retrieves enrich related stats.
*
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/enrich-stats-api.html">
* the docs</a> for more.
*
* @param request the {@link StatsRequest}
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
* @return cancellable that may be used to cancel the request
*/
public Cancellable statsAsync(StatsRequest request,
RequestOptions options,
ActionListener<StatsResponse> listener) {
return restHighLevelClient.performRequestAsyncAndParseEntity(
request,
EnrichRequestConverters::stats,
options,
StatsResponse::fromXContent,
listener,
Collections.emptySet()
);
}
/**
* Executes the execute policy api, which executes an enrich policy.
*
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/execute-enrich-policy-api.html">
* the docs</a> for more.
*
* @param request the {@link ExecutePolicyRequest}
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public ExecutePolicyResponse executePolicy(ExecutePolicyRequest request, RequestOptions options) throws IOException {
return restHighLevelClient.performRequestAndParseEntity(
request,
EnrichRequestConverters::executePolicy,
options,
ExecutePolicyResponse::fromXContent,
Collections.emptySet()
);
}
/**
* Asynchronously executes the execute policy api, which executes an enrich policy.
*
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/execute-enrich-policy-api.html">
* the docs</a> for more.
*
* @param request the {@link ExecutePolicyRequest}
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
* @return cancellable that may be used to cancel the request
*/
public Cancellable executePolicyAsync(ExecutePolicyRequest request,
RequestOptions options,
ActionListener<ExecutePolicyResponse> listener) {
return restHighLevelClient.performRequestAsyncAndParseEntity(
request,
EnrichRequestConverters::executePolicy,
options,
ExecutePolicyResponse::fromXContent,
listener,
Collections.emptySet()
);
}
}

View File

@ -1,84 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
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;
}
}

View File

@ -271,7 +271,6 @@ public class RestHighLevelClient implements Closeable {
private final RollupClient rollupClient = new RollupClient(this);
private final CcrClient ccrClient = new CcrClient(this);
private final TransformClient transformClient = new TransformClient(this);
private final EnrichClient enrichClient = new EnrichClient(this);
private final AsyncSearchClient asyncSearchClient = new AsyncSearchClient(this);
/**
@ -507,10 +506,6 @@ public class RestHighLevelClient implements Closeable {
return transformClient;
}
public EnrichClient enrich() {
return enrichClient;
}
/**
* Executes a bulk request using the Bulk API.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html">Bulk API on elastic.co</a>

View File

@ -1,38 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
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;
}
}

View File

@ -1,43 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
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;
}
}

View File

@ -1,85 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.enrich;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.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<ExecutePolicyResponse, Void> 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<ExecutionStatus, Void> 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;
}
}
}

View File

@ -1,46 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.enrich;
import org.elasticsearch.client.Validatable;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public final class GetPolicyRequest implements Validatable {
private final List<String> names;
public GetPolicyRequest() {
this(Collections.emptyList());
}
public GetPolicyRequest(String... names) {
this(Arrays.asList(names));
}
public GetPolicyRequest(List<String> names) {
this.names = names;
}
public List<String> getNames() {
return names;
}
}

View File

@ -1,64 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.enrich;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException;
import java.util.List;
public final class GetPolicyResponse {
@SuppressWarnings("unchecked")
private static final ConstructingObjectParser<GetPolicyResponse, Void> PARSER = new ConstructingObjectParser<>(
"get_policy_response",
true,
args -> new GetPolicyResponse((List<NamedPolicy>) args[0])
);
@SuppressWarnings("unchecked")
private static final ConstructingObjectParser<NamedPolicy, Void> 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<NamedPolicy> policies;
public static GetPolicyResponse fromXContent(XContentParser parser) throws IOException {
return PARSER.apply(parser, null);
}
public GetPolicyResponse(List<NamedPolicy> policies) {
this.policies = policies;
}
public List<NamedPolicy> getPolicies() {
return policies;
}
}

View File

@ -1,129 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.enrich;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.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<NamedPolicy, String> PARSER = new ConstructingObjectParser<>(
"policy",
true,
(args, policyType) -> new NamedPolicy(
policyType,
(String) args[0],
(BytesReference) args[1],
(List<String>) args[2],
(String) args[3],
(List<String>) 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<String> indices;
private final String matchField;
private final List<String> enrichFields;
NamedPolicy(String type, String name, BytesReference query, List<String> indices, String matchField, List<String> 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<String> getIndices() {
return indices;
}
public String getMatchField() {
return matchField;
}
public List<String> getEnrichFields() {
return enrichFields;
}
}

View File

@ -1,151 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
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.ToXContentObject;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.index.query.QueryBuilder;
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<String> indices;
private final String matchField;
private final List<String> enrichFields;
public PutPolicyRequest(String name, String type, List<String> indices, String matchField, List<String> 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) == 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<String> getIndices() {
return indices;
}
public String getMatchField() {
return matchField;
}
public List<String> getEnrichFields() {
return enrichFields;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
{
builder.startObject(type);
{
builder.field(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.field(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<String, Object> asMap(BytesReference bytesReference, XContentType xContentType) {
return bytesReference == null ? null : XContentHelper.convertToMap(bytesReference, true, xContentType).v2();
}
}

View File

@ -1,24 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.enrich;
import org.elasticsearch.client.Validatable;
public final class StatsRequest implements Validatable {
}

View File

@ -1,191 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.enrich;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.tasks.TaskInfo;
import java.util.List;
import java.util.Objects;
public final class StatsResponse {
private static ParseField EXECUTING_POLICIES_FIELD = new ParseField("executing_policies");
private static ParseField COORDINATOR_STATS_FIELD = new ParseField("coordinator_stats");
@SuppressWarnings("unchecked")
private static final ConstructingObjectParser<StatsResponse, Void> PARSER = new ConstructingObjectParser<>(
"stats_response",
true,
args -> new StatsResponse((List<ExecutingPolicy>) args[0], (List<CoordinatorStats>) args[1])
);
static {
PARSER.declareObjectArray(ConstructingObjectParser.constructorArg(), ExecutingPolicy.PARSER::apply, EXECUTING_POLICIES_FIELD);
PARSER.declareObjectArray(ConstructingObjectParser.constructorArg(), CoordinatorStats.PARSER::apply, COORDINATOR_STATS_FIELD);
}
public static StatsResponse fromXContent(XContentParser parser) {
return PARSER.apply(parser, null);
}
private final List<ExecutingPolicy> executingPolicies;
private final List<CoordinatorStats> coordinatorStats;
public StatsResponse(List<ExecutingPolicy> executingPolicies, List<CoordinatorStats> coordinatorStats) {
this.executingPolicies = executingPolicies;
this.coordinatorStats = coordinatorStats;
}
public List<ExecutingPolicy> getExecutingPolicies() {
return executingPolicies;
}
public List<CoordinatorStats> getCoordinatorStats() {
return coordinatorStats;
}
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<CoordinatorStats, Void> 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<ExecutingPolicy, Void> 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);
}
}
}

View File

@ -323,12 +323,11 @@ public final class Role {
public static final String READ_CCR = "read_ccr";
public static final String MANAGE_ILM = "manage_ilm";
public static final String READ_ILM = "read_ilm";
public static final String MANAGE_ENRICH = "manage_enrich";
public static final String[] ALL_ARRAY = new String[] { NONE, ALL, MONITOR, MONITOR_TRANSFORM_DEPRECATED, MONITOR_TRANSFORM,
MONITOR_ML, MONITOR_WATCHER, MONITOR_ROLLUP, MANAGE, MANAGE_TRANSFORM_DEPRECATED, MANAGE_TRANSFORM,
MANAGE_ML, MANAGE_WATCHER, MANAGE_ROLLUP, MANAGE_INDEX_TEMPLATES, MANAGE_INGEST_PIPELINES, TRANSPORT_CLIENT,
MANAGE_SECURITY, MANAGE_SAML, MANAGE_OIDC, MANAGE_TOKEN, MANAGE_PIPELINE, MANAGE_AUTOSCALING, MANAGE_CCR, READ_CCR,
MANAGE_ILM, READ_ILM, MANAGE_ENRICH };
MANAGE_ILM, READ_ILM };
}
/**

View File

@ -1,86 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client;
import org.elasticsearch.client.core.AcknowledgedResponse;
import org.elasticsearch.client.enrich.DeletePolicyRequest;
import org.elasticsearch.client.enrich.ExecutePolicyRequest;
import org.elasticsearch.client.enrich.ExecutePolicyResponse;
import org.elasticsearch.client.enrich.GetPolicyRequest;
import org.elasticsearch.client.enrich.GetPolicyResponse;
import org.elasticsearch.client.enrich.PutPolicyRequest;
import org.elasticsearch.client.enrich.StatsRequest;
import org.elasticsearch.client.enrich.StatsResponse;
import org.elasticsearch.client.indices.CreateIndexRequest;
import java.util.Collections;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
public class EnrichIT extends ESRestHighLevelClientTestCase {
public void testCRUD() throws Exception {
CreateIndexRequest createIndexRequest = new CreateIndexRequest("my-index")
.mapping(Collections.singletonMap("properties", Collections.singletonMap("enrich_key",
Collections.singletonMap("type", "keyword"))));
highLevelClient().indices().create(createIndexRequest, RequestOptions.DEFAULT);
final EnrichClient enrichClient = highLevelClient().enrich();
PutPolicyRequest putPolicyRequest = new PutPolicyRequest("my-policy", "match",
Collections.singletonList("my-index"), "enrich_key", Collections.singletonList("enrich_value"));
AcknowledgedResponse putPolicyResponse = execute(putPolicyRequest, enrichClient::putPolicy, enrichClient::putPolicyAsync);
assertThat(putPolicyResponse.isAcknowledged(), is(true));
GetPolicyRequest getPolicyRequest = randomBoolean() ? new GetPolicyRequest("my-policy") : new GetPolicyRequest();
GetPolicyResponse getPolicyResponse = execute(getPolicyRequest, enrichClient::getPolicy, enrichClient::getPolicyAsync);
assertThat(getPolicyResponse.getPolicies().size(), equalTo(1));
assertThat(getPolicyResponse.getPolicies().get(0).getType(), equalTo(putPolicyRequest.getType()));
assertThat(getPolicyResponse.getPolicies().get(0).getIndices(), equalTo(putPolicyRequest.getIndices()));
assertThat(getPolicyResponse.getPolicies().get(0).getMatchField(), equalTo(putPolicyRequest.getMatchField()));
assertThat(getPolicyResponse.getPolicies().get(0).getEnrichFields(), equalTo(putPolicyRequest.getEnrichFields()));
StatsRequest statsRequest = new StatsRequest();
StatsResponse statsResponse = execute(statsRequest, enrichClient::stats, enrichClient::statsAsync);
assertThat(statsResponse.getExecutingPolicies().size(), equalTo(0));
assertThat(statsResponse.getCoordinatorStats().size(), equalTo(1));
assertThat(statsResponse.getCoordinatorStats().get(0).getNodeId(), notNullValue());
assertThat(statsResponse.getCoordinatorStats().get(0).getQueueSize(), greaterThanOrEqualTo(0));
assertThat(statsResponse.getCoordinatorStats().get(0).getRemoteRequestsCurrent(), greaterThanOrEqualTo(0));
assertThat(statsResponse.getCoordinatorStats().get(0).getRemoteRequestsTotal(), greaterThanOrEqualTo(0L));
assertThat(statsResponse.getCoordinatorStats().get(0).getExecutedSearchesTotal(), greaterThanOrEqualTo(0L));
ExecutePolicyRequest executePolicyRequest = new ExecutePolicyRequest("my-policy");
ExecutePolicyResponse executePolicyResponse =
execute(executePolicyRequest, enrichClient::executePolicy, enrichClient::executePolicyAsync);
assertThat(executePolicyResponse.getExecutionStatus().getPhase(), equalTo("COMPLETE"));
DeletePolicyRequest deletePolicyRequest = new DeletePolicyRequest("my-policy");
AcknowledgedResponse deletePolicyResponse =
execute(deletePolicyRequest, enrichClient::deletePolicy, enrichClient::deletePolicyAsync);
assertThat(deletePolicyResponse.isAcknowledged(), is(true));
getPolicyRequest = new GetPolicyRequest();
getPolicyResponse = execute(getPolicyRequest, enrichClient::getPolicy, enrichClient::getPolicyAsync);
assertThat(getPolicyResponse.getPolicies().size(), equalTo(0));
}
}

View File

@ -1,114 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
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.PutPolicyRequestTests;
import org.elasticsearch.client.enrich.StatsRequest;
import org.elasticsearch.test.ESTestCase;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
public class EnrichRequestConvertersTests extends ESTestCase {
public void testPutPolicy() throws Exception {
PutPolicyRequest request = PutPolicyRequestTests.createTestInstance();
Request result = EnrichRequestConverters.putPolicy(request);
assertThat(result.getMethod(), equalTo(HttpPut.METHOD_NAME));
assertThat(result.getEndpoint(), equalTo("/_enrich/policy/" + request.getName()));
assertThat(result.getParameters().size(), equalTo(0));
RequestConvertersTests.assertToXContentBody(request, result.getEntity());
}
public void testDeletePolicy() {
DeletePolicyRequest request = new DeletePolicyRequest(randomAlphaOfLength(4));
Request result = EnrichRequestConverters.deletePolicy(request);
assertThat(result.getMethod(), equalTo(HttpDelete.METHOD_NAME));
assertThat(result.getEndpoint(), equalTo("/_enrich/policy/" + request.getName()));
assertThat(result.getParameters().size(), equalTo(0));
assertThat(result.getEntity(), nullValue());
}
public void testGetPolicy() {
GetPolicyRequest request = new GetPolicyRequest(randomAlphaOfLength(4));
Request result = EnrichRequestConverters.getPolicy(request);
assertThat(result.getMethod(), equalTo(HttpGet.METHOD_NAME));
assertThat(result.getEndpoint(), equalTo("/_enrich/policy/" + request.getNames().get(0)));
assertThat(result.getParameters().size(), equalTo(0));
assertThat(result.getEntity(), nullValue());
request = new GetPolicyRequest(randomAlphaOfLength(4), randomAlphaOfLength(4));
result = EnrichRequestConverters.getPolicy(request);
assertThat(result.getMethod(), equalTo(HttpGet.METHOD_NAME));
assertThat(result.getEndpoint(), equalTo("/_enrich/policy/" + request.getNames().get(0) + "," + request.getNames().get(1)));
assertThat(result.getParameters().size(), equalTo(0));
assertThat(result.getEntity(), nullValue());
request = new GetPolicyRequest();
result = EnrichRequestConverters.getPolicy(request);
assertThat(result.getMethod(), equalTo(HttpGet.METHOD_NAME));
assertThat(result.getEndpoint(), equalTo("/_enrich/policy"));
assertThat(result.getParameters().size(), equalTo(0));
assertThat(result.getEntity(), nullValue());
}
public void testStats() {
StatsRequest request = new StatsRequest();
Request result = EnrichRequestConverters.stats(request);
assertThat(result.getMethod(), equalTo(HttpGet.METHOD_NAME));
assertThat(result.getEndpoint(), equalTo("/_enrich/_stats"));
assertThat(result.getParameters().size(), equalTo(0));
assertThat(result.getEntity(), nullValue());
}
public void testExecutePolicy() {
ExecutePolicyRequest request = new ExecutePolicyRequest(randomAlphaOfLength(4));
Request result = EnrichRequestConverters.executePolicy(request);
assertThat(result.getMethod(), equalTo(HttpPost.METHOD_NAME));
assertThat(result.getEndpoint(), equalTo("/_enrich/policy/" + request.getName() + "/_execute"));
assertThat(result.getParameters().size(), equalTo(0));
assertThat(result.getEntity(), nullValue());
request = new ExecutePolicyRequest(randomAlphaOfLength(4));
request.setWaitForCompletion(randomBoolean());
result = EnrichRequestConverters.executePolicy(request);
assertThat(result.getMethod(), equalTo(HttpPost.METHOD_NAME));
assertThat(result.getEndpoint(), equalTo("/_enrich/policy/" + request.getName() + "/_execute"));
assertThat(result.getParameters().size(), equalTo(1));
assertThat(result.getParameters().get("wait_for_completion"), equalTo(request.getWaitForCompletion().toString()));
assertThat(result.getEntity(), nullValue());
}
}

View File

@ -917,7 +917,6 @@ public class RestHighLevelClientTests extends ESTestCase {
apiName.startsWith("security.") == false &&
apiName.startsWith("index_lifecycle.") == false &&
apiName.startsWith("ccr.") == false &&
apiName.startsWith("enrich.") == false &&
apiName.startsWith("transform.") == false &&
apiName.endsWith("freeze") == false &&
apiName.endsWith("reload_analyzers") == false &&

View File

@ -1,328 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.documentation;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.LatchedActionListener;
import org.elasticsearch.client.ESRestHighLevelClientTestCase;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.core.AcknowledgedResponse;
import org.elasticsearch.client.enrich.DeletePolicyRequest;
import org.elasticsearch.client.enrich.ExecutePolicyRequest;
import org.elasticsearch.client.enrich.ExecutePolicyResponse;
import org.elasticsearch.client.enrich.NamedPolicy;
import org.elasticsearch.client.enrich.GetPolicyRequest;
import org.elasticsearch.client.enrich.GetPolicyResponse;
import org.elasticsearch.client.enrich.PutPolicyRequest;
import org.elasticsearch.client.enrich.StatsRequest;
import org.elasticsearch.client.enrich.StatsResponse;
import org.elasticsearch.client.enrich.StatsResponse.CoordinatorStats;
import org.elasticsearch.client.enrich.StatsResponse.ExecutingPolicy;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.junit.After;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static java.util.Collections.singletonMap;
public class EnrichDocumentationIT extends ESRestHighLevelClientTestCase {
@After
public void cleanup() {
RestHighLevelClient client = highLevelClient();
DeletePolicyRequest deletePolicyRequest = new DeletePolicyRequest("users-policy");
try {
client.enrich().deletePolicy(deletePolicyRequest, RequestOptions.DEFAULT);
} catch (Exception e) {
// ignore... it is ok if policy has already been removed
}
}
public void testPutPolicy() throws Exception {
RestHighLevelClient client = highLevelClient();
CreateIndexRequest createIndexRequest = new CreateIndexRequest("users")
.mapping(singletonMap("properties", singletonMap("email", singletonMap("type", "keyword"))));
client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
// tag::enrich-put-policy-request
PutPolicyRequest putPolicyRequest = new PutPolicyRequest(
"users-policy", "match", Arrays.asList("users"),
"email", Arrays.asList("address", "zip", "city", "state"));
// end::enrich-put-policy-request
// tag::enrich-put-policy-execute
AcknowledgedResponse putPolicyResponse =
client.enrich().putPolicy(putPolicyRequest, RequestOptions.DEFAULT);
// end::enrich-put-policy-execute
// tag::enrich-put-policy-response
boolean isAcknowledged =
putPolicyResponse.isAcknowledged(); // <1>
// end::enrich-put-policy-response
// tag::enrich-put-policy-execute-listener
ActionListener<AcknowledgedResponse> listener =
new ActionListener<AcknowledgedResponse>() {
@Override
public void onResponse(AcknowledgedResponse response) { // <1>
boolean isAcknowledged = response.isAcknowledged();
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::enrich-put-policy-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::enrich-put-policy-execute-async
client.enrich().putPolicyAsync(putPolicyRequest,
RequestOptions.DEFAULT, listener); // <1>
// end::enrich-put-policy-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
public void testDeletePolicy() throws Exception {
RestHighLevelClient client = highLevelClient();
{
CreateIndexRequest createIndexRequest = new CreateIndexRequest("users")
.mapping(singletonMap("properties", singletonMap("email", singletonMap("type", "keyword"))));
client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
// Add a policy, so that it can be deleted:
PutPolicyRequest putPolicyRequest = new PutPolicyRequest(
"users-policy", "match", Arrays.asList("users"),
"email", Arrays.asList("address", "zip", "city", "state"));
client.enrich().putPolicy(putPolicyRequest, RequestOptions.DEFAULT);
}
// tag::enrich-delete-policy-request
DeletePolicyRequest deletePolicyRequest =
new DeletePolicyRequest("users-policy");
// end::enrich-delete-policy-request
// tag::enrich-delete-policy-execute
AcknowledgedResponse deletePolicyResponse = client.enrich()
.deletePolicy(deletePolicyRequest, RequestOptions.DEFAULT);
// end::enrich-delete-policy-execute
// tag::enrich-delete-policy-response
boolean isAcknowledged =
deletePolicyResponse.isAcknowledged(); // <1>
// end::enrich-delete-policy-response
// tag::enrich-delete-policy-execute-listener
ActionListener<AcknowledgedResponse> listener =
new ActionListener<AcknowledgedResponse>() {
@Override
public void onResponse(AcknowledgedResponse response) { // <1>
boolean isAcknowledged = response.isAcknowledged();
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::enrich-delete-policy-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::enrich-delete-policy-execute-async
client.enrich().deletePolicyAsync(deletePolicyRequest,
RequestOptions.DEFAULT, listener); // <1>
// end::enrich-delete-policy-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
public void testGetPolicy() throws Exception {
RestHighLevelClient client = highLevelClient();
CreateIndexRequest createIndexRequest = new CreateIndexRequest("users")
.mapping(singletonMap("properties", singletonMap("email", singletonMap("type", "keyword"))));
client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
PutPolicyRequest putPolicyRequest = new PutPolicyRequest(
"users-policy", "match", Collections.singletonList("users"),
"email", Arrays.asList("address", "zip", "city", "state"));
client.enrich().putPolicy(putPolicyRequest, RequestOptions.DEFAULT);
// tag::enrich-get-policy-request
GetPolicyRequest getPolicyRequest = new GetPolicyRequest("users-policy");
// end::enrich-get-policy-request
// tag::enrich-get-policy-execute
GetPolicyResponse getPolicyResponse =
client.enrich().getPolicy(getPolicyRequest, RequestOptions.DEFAULT);
// end::enrich-get-policy-execute
// tag::enrich-get-policy-response
List<NamedPolicy> policies = getPolicyResponse.getPolicies(); // <1>
NamedPolicy policy = policies.get(0);
// end::enrich-get-policy-response
// tag::enrich-get-policy-execute-listener
ActionListener<GetPolicyResponse> listener =
new ActionListener<GetPolicyResponse>() {
@Override
public void onResponse(GetPolicyResponse response) { // <1>
List<NamedPolicy> policies = response.getPolicies();
NamedPolicy policy = policies.get(0);
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::enrich-get-policy-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::enrich-get-policy-execute-async
client.enrich().getPolicyAsync(getPolicyRequest,
RequestOptions.DEFAULT, listener); // <1>
// end::enrich-get-policy-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
public void testStats() throws Exception {
RestHighLevelClient client = highLevelClient();
// tag::enrich-stats-request
StatsRequest statsRequest = new StatsRequest();
// end::enrich-stats-request
// tag::enrich-stats-execute
StatsResponse statsResponse =
client.enrich().stats(statsRequest, RequestOptions.DEFAULT);
// end::enrich-stats-execute
// tag::enrich-stats-response
List<ExecutingPolicy> executingPolicies =
statsResponse.getExecutingPolicies(); // <1>
List<CoordinatorStats> coordinatorStats =
statsResponse.getCoordinatorStats(); // <2>
// end::enrich-stats-response
// tag::enrich-stats-execute-listener
ActionListener<StatsResponse> listener =
new ActionListener<StatsResponse>() {
@Override
public void onResponse(StatsResponse response) { // <1>
List<ExecutingPolicy> executingPolicies =
statsResponse.getExecutingPolicies();
List<CoordinatorStats> coordinatorStats =
statsResponse.getCoordinatorStats();
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::enrich-stats-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::enrich-stats-execute-async
client.enrich().statsAsync(statsRequest, RequestOptions.DEFAULT,
listener); // <1>
// end::enrich-stats-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
public void testExecutePolicy() throws Exception {
RestHighLevelClient client = highLevelClient();
{
CreateIndexRequest createIndexRequest = new CreateIndexRequest("users")
.mapping(singletonMap("properties", singletonMap("email",
singletonMap("type", "keyword"))));
client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
PutPolicyRequest putPolicyRequest = new PutPolicyRequest(
"users-policy", "match", Collections.singletonList("users"),
"email", Arrays.asList("address", "zip", "city", "state"));
client.enrich().putPolicy(putPolicyRequest, RequestOptions.DEFAULT);
}
// tag::enrich-execute-policy-request
ExecutePolicyRequest request =
new ExecutePolicyRequest("users-policy");
// end::enrich-execute-policy-request
// tag::enrich-execute-policy-execute
ExecutePolicyResponse response =
client.enrich().executePolicy(request, RequestOptions.DEFAULT);
// end::enrich-execute-policy-execute
// tag::enrich-execute-policy-response
ExecutePolicyResponse.ExecutionStatus status =
response.getExecutionStatus();
// end::enrich-execute-policy-response
// tag::enrich-execute-policy-execute-listener
ActionListener<ExecutePolicyResponse> listener =
new ActionListener<ExecutePolicyResponse>() {
@Override
public void onResponse(ExecutePolicyResponse response) { // <1>
ExecutePolicyResponse.ExecutionStatus status =
response.getExecutionStatus();
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::enrich-execute-policy-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::enrich-execute-policy-execute-async
client.enrich().executePolicyAsync(request, RequestOptions.DEFAULT,
listener); // <1>
// end::enrich-execute-policy-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}

View File

@ -1,61 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.enrich;
import org.elasticsearch.client.AbstractResponseTestCase;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.tasks.TaskId;
import org.elasticsearch.xpack.core.enrich.action.ExecuteEnrichPolicyAction;
import org.elasticsearch.xpack.core.enrich.action.ExecuteEnrichPolicyStatus;
import java.io.IOException;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
public class ExecutePolicyResponseTests extends AbstractResponseTestCase<ExecuteEnrichPolicyAction.Response, ExecutePolicyResponse> {
@Override
protected ExecuteEnrichPolicyAction.Response createServerTestInstance(XContentType xContentType) {
if (randomBoolean()) {
return new ExecuteEnrichPolicyAction.Response(new ExecuteEnrichPolicyStatus(randomAlphaOfLength(4)));
} else {
return new ExecuteEnrichPolicyAction.Response(new TaskId(randomAlphaOfLength(4), randomNonNegativeLong()));
}
}
@Override
protected ExecutePolicyResponse doParseToClientInstance(XContentParser parser) throws IOException {
return ExecutePolicyResponse.fromXContent(parser);
}
@Override
protected void assertInstances(ExecuteEnrichPolicyAction.Response serverTestInstance, ExecutePolicyResponse clientInstance) {
if (serverTestInstance.getStatus() != null) {
assertThat(clientInstance.getExecutionStatus().getPhase(), equalTo(serverTestInstance.getStatus().getPhase()));
assertThat(clientInstance.getTaskId(), nullValue());
} else if (serverTestInstance.getTaskId() != null) {
assertThat(clientInstance.getTaskId(), equalTo(clientInstance.getTaskId()));
assertThat(clientInstance.getExecutionStatus(), nullValue());
} else {
assert false;
}
}
}

View File

@ -1,94 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.enrich;
import org.elasticsearch.client.AbstractResponseTestCase;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.xpack.core.enrich.EnrichPolicy;
import org.elasticsearch.xpack.core.enrich.action.GetEnrichPolicyAction;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
public class GetPolicyResponseTests extends AbstractResponseTestCase<GetEnrichPolicyAction.Response, GetPolicyResponse> {
@Override
protected GetEnrichPolicyAction.Response createServerTestInstance(XContentType xContentType) {
int numPolicies = randomIntBetween(0, 8);
Map<String, EnrichPolicy> policies = new HashMap<>(numPolicies);
for (int i = 0; i < numPolicies; i++) {
policies.put(randomAlphaOfLength(4), createRandomEnrichPolicy(xContentType));
}
return new GetEnrichPolicyAction.Response(policies);
}
@Override
protected GetPolicyResponse doParseToClientInstance(XContentParser parser) throws IOException {
return GetPolicyResponse.fromXContent(parser);
}
@Override
protected void assertInstances(GetEnrichPolicyAction.Response serverTestInstance, GetPolicyResponse clientInstance) {
assertThat(clientInstance.getPolicies().size(), equalTo(serverTestInstance.getPolicies().size()));
for (int i = 0; i < clientInstance.getPolicies().size(); i++) {
assertThat(clientInstance.getPolicies().get(i).getType(),
equalTo(serverTestInstance.getPolicies().get(i).getPolicy().getType()));
assertThat(clientInstance.getPolicies().get(i).getName(),
equalTo(serverTestInstance.getPolicies().get(i).getName()));
assertThat(clientInstance.getPolicies().get(i).getIndices(),
equalTo(serverTestInstance.getPolicies().get(i).getPolicy().getIndices()));
if (clientInstance.getPolicies().get(i).getQuery() != null) {
assertThat(clientInstance.getPolicies().get(i).getQuery(),
equalTo(serverTestInstance.getPolicies().get(i).getPolicy().getQuery().getQuery()));
} else {
assertThat(serverTestInstance.getPolicies().get(i).getPolicy().getQuery(), nullValue());
}
assertThat(clientInstance.getPolicies().get(i).getMatchField(),
equalTo(serverTestInstance.getPolicies().get(i).getPolicy().getMatchField()));
assertThat(clientInstance.getPolicies().get(i).getEnrichFields(),
equalTo(serverTestInstance.getPolicies().get(i).getPolicy().getEnrichFields()));
}
}
private static EnrichPolicy createRandomEnrichPolicy(XContentType xContentType){
try (XContentBuilder builder = XContentBuilder.builder(xContentType.xContent())) {
builder.startObject();
builder.endObject();
BytesReference querySource = BytesReference.bytes(builder);
return new EnrichPolicy(
randomAlphaOfLength(4),
randomBoolean() ? new EnrichPolicy.QuerySource(querySource, xContentType) : null,
Arrays.asList(generateRandomStringArray(8, 4, false, false)),
randomAlphaOfLength(4),
Arrays.asList(generateRandomStringArray(8, 4, false, false))
);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}

View File

@ -1,105 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.enrich;
import org.elasticsearch.client.AbstractRequestTestCase;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.test.EqualsHashCodeTestUtils;
import org.elasticsearch.xpack.core.enrich.action.PutEnrichPolicyAction;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Arrays;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
public class PutPolicyRequestTests extends AbstractRequestTestCase<PutPolicyRequest, PutEnrichPolicyAction.Request> {
public void testValidate() {
PutPolicyRequest request = createClientTestInstance();
assertThat(request.validate().isPresent(), is(false));
Exception e = expectThrows(IllegalArgumentException.class,
() -> new PutPolicyRequest(request.getName(), request.getType(), request.getIndices(), null, request.getEnrichFields()));
assertThat(e.getMessage(), containsString("matchField must be a non-null and non-empty string"));
}
public void testEqualsAndHashcode() {
PutPolicyRequest testInstance = createTestInstance();
EqualsHashCodeTestUtils.checkEqualsAndHashCode(testInstance, (original) -> {
PutPolicyRequest copy = new PutPolicyRequest(original.getName(), original.getType(), original.getIndices(),
original.getMatchField(), original.getEnrichFields());
copy.setQuery(original.getQuery());
return copy;
});
}
@Override
protected PutPolicyRequest createClientTestInstance() {
return createTestInstance("name");
}
public static PutPolicyRequest createTestInstance() {
return createTestInstance(randomAlphaOfLength(4));
}
public static PutPolicyRequest createTestInstance(String name) {
PutPolicyRequest testInstance = new PutPolicyRequest(
name,
randomAlphaOfLength(4),
Arrays.asList(generateRandomStringArray(4, 4, false, false)),
randomAlphaOfLength(4),
Arrays.asList(generateRandomStringArray(4, 4, false, false))
);
if (randomBoolean()) {
try {
testInstance.setQuery(new MatchAllQueryBuilder());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
return testInstance;
}
@Override
protected PutEnrichPolicyAction.Request doParseToServerInstance(XContentParser parser) throws IOException {
return PutEnrichPolicyAction.fromXContent(parser, "name");
}
@Override
protected void assertInstances(PutEnrichPolicyAction.Request serverInstance, PutPolicyRequest clientTestInstance) {
assertThat(clientTestInstance.getName(), equalTo(serverInstance.getName()));
assertThat(clientTestInstance.getType(), equalTo(serverInstance.getPolicy().getType()));
assertThat(clientTestInstance.getIndices(), equalTo(serverInstance.getPolicy().getIndices()));
if (clientTestInstance.getQuery() != null) {
XContentType type = serverInstance.getPolicy().getQuery().getContentType();
assertThat(PutPolicyRequest.asMap(clientTestInstance.getQuery(), XContentType.JSON),
equalTo(PutPolicyRequest.asMap(serverInstance.getPolicy().getQuery().getQuery(), type)));
} else {
assertThat(serverInstance.getPolicy().getQuery(), nullValue());
}
assertThat(clientTestInstance.getMatchField(), equalTo(serverInstance.getPolicy().getMatchField()));
assertThat(clientTestInstance.getEnrichFields(), equalTo(serverInstance.getPolicy().getEnrichFields()));
}
}

View File

@ -1,98 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.enrich;
import org.elasticsearch.client.AbstractResponseTestCase;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.tasks.TaskId;
import org.elasticsearch.tasks.TaskInfo;
import org.elasticsearch.xpack.core.enrich.action.EnrichStatsAction;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static org.hamcrest.Matchers.equalTo;
public class StatsResponseTests extends AbstractResponseTestCase<EnrichStatsAction.Response, StatsResponse> {
@Override
protected EnrichStatsAction.Response createServerTestInstance(XContentType xContentType) {
int numExecutingPolicies = randomIntBetween(0, 16);
List<EnrichStatsAction.Response.ExecutingPolicy> executingPolicies = new ArrayList<>(numExecutingPolicies);
for (int i = 0; i < numExecutingPolicies; i++) {
TaskInfo taskInfo = randomTaskInfo();
executingPolicies.add(new EnrichStatsAction.Response.ExecutingPolicy(randomAlphaOfLength(4), taskInfo));
}
int numCoordinatingStats = randomIntBetween(0, 16);
List<EnrichStatsAction.Response.CoordinatorStats> coordinatorStats = new ArrayList<>(numCoordinatingStats);
for (int i = 0; i < numCoordinatingStats; i++) {
EnrichStatsAction.Response.CoordinatorStats stats = new EnrichStatsAction.Response.CoordinatorStats(
randomAlphaOfLength(4), randomIntBetween(0, 8096), randomIntBetween(0, 8096), randomNonNegativeLong(),
randomNonNegativeLong());
coordinatorStats.add(stats);
}
return new EnrichStatsAction.Response(executingPolicies, coordinatorStats);
}
@Override
protected StatsResponse doParseToClientInstance(XContentParser parser) throws IOException {
return StatsResponse.fromXContent(parser);
}
@Override
protected void assertInstances(EnrichStatsAction.Response serverTestInstance, StatsResponse clientInstance) {
assertThat(clientInstance.getExecutingPolicies().size(), equalTo(serverTestInstance.getExecutingPolicies().size()));
for (int i = 0; i < clientInstance.getExecutingPolicies().size(); i++) {
StatsResponse.ExecutingPolicy actual = clientInstance.getExecutingPolicies().get(i);
EnrichStatsAction.Response.ExecutingPolicy expected = serverTestInstance.getExecutingPolicies().get(i);
assertThat(actual.getName(), equalTo(expected.getName()));
assertThat(actual.getTaskInfo(), equalTo(actual.getTaskInfo()));
}
assertThat(clientInstance.getCoordinatorStats().size(), equalTo(serverTestInstance.getCoordinatorStats().size()));
for (int i = 0; i < clientInstance.getCoordinatorStats().size(); i++) {
StatsResponse.CoordinatorStats actual = clientInstance.getCoordinatorStats().get(i);
EnrichStatsAction.Response.CoordinatorStats expected = serverTestInstance.getCoordinatorStats().get(i);
assertThat(actual.getNodeId(), equalTo(expected.getNodeId()));
assertThat(actual.getQueueSize(), equalTo(expected.getQueueSize()));
assertThat(actual.getRemoteRequestsCurrent(), equalTo(expected.getRemoteRequestsCurrent()));
assertThat(actual.getRemoteRequestsTotal(), equalTo(expected.getRemoteRequestsTotal()));
assertThat(actual.getExecutedSearchesTotal(), equalTo(expected.getExecutedSearchesTotal()));
}
}
private static TaskInfo randomTaskInfo() {
TaskId taskId = new TaskId(randomAlphaOfLength(5), randomLong());
String type = randomAlphaOfLength(5);
String action = randomAlphaOfLength(5);
String description = randomAlphaOfLength(5);
long startTime = randomLong();
long runningTimeNanos = randomNonNegativeLong();
boolean cancellable = randomBoolean();
TaskId parentTaskId = TaskId.EMPTY_TASK_ID;
Map<String, String> headers = randomBoolean() ?
Collections.emptyMap() :
Collections.singletonMap(randomAlphaOfLength(5), randomAlphaOfLength(5));
return new TaskInfo(taskId, type, action, description, null, startTime, runningTimeNanos, cancellable, parentTaskId, headers);
}
}