From 60ad099178e3756570f34158b53fb4c8c3cf4d7c Mon Sep 17 00:00:00 2001 From: Martijn van Groningen Date: Wed, 11 Sep 2019 14:26:42 +0200 Subject: [PATCH] Add HLRC support for enrich get policy API. (#45970) Changed the signature of AbstractResponseTestCase#createServerTestInstance(...) to include the randomly selected xcontent type. This is needed for the creating a server response instance with a query which is represented as BytesReference. Maybe this should go into a different change? This PR also includes HLRC docs for the get policy api. Relates to #32789 --- .../elasticsearch/client/EnrichClient.java | 46 +++++++ .../client/EnrichRequestConverters.java | 10 ++ .../client/enrich/GetPolicyRequest.java | 46 +++++++ .../client/enrich/GetPolicyResponse.java | 55 ++++++++ .../client/enrich/NamedPolicy.java | 130 ++++++++++++++++++ .../client/enrich/PutPolicyRequest.java | 14 +- .../org/elasticsearch/client/EnrichIT.java | 42 ++---- .../client/EnrichRequestConvertersTests.java | 28 ++++ .../documentation/EnrichDocumentationIT.java | 55 ++++++++ .../client/enrich/GetPolicyResponseTests.java | 95 +++++++++++++ .../high-level/enrich/get_policy.asciidoc | 32 +++++ .../high-level/supported-apis.asciidoc | 2 + 12 files changed, 515 insertions(+), 40 deletions(-) create mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/enrich/GetPolicyRequest.java create mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/enrich/GetPolicyResponse.java create mode 100644 client/rest-high-level/src/main/java/org/elasticsearch/client/enrich/NamedPolicy.java create mode 100644 client/rest-high-level/src/test/java/org/elasticsearch/client/enrich/GetPolicyResponseTests.java create mode 100644 docs/java-rest/high-level/enrich/get_policy.asciidoc diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/EnrichClient.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/EnrichClient.java index d7e7199f7cc..ac1136cfe1c 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/EnrichClient.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/EnrichClient.java @@ -21,6 +21,8 @@ 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.GetPolicyRequest; +import org.elasticsearch.client.enrich.GetPolicyResponse; import org.elasticsearch.client.enrich.PutPolicyRequest; import java.io.IOException; @@ -128,4 +130,48 @@ public final class EnrichClient { Collections.emptySet() ); } + + /** + * Executes the get policy api, which retrieves an enrich policy. + * + * See + * the docs 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 + * the docs 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 + */ + public void getPolicyAsync(GetPolicyRequest request, + RequestOptions options, + ActionListener listener) { + restHighLevelClient.performRequestAsyncAndParseEntity( + request, + EnrichRequestConverters::getPolicy, + options, + GetPolicyResponse::fromXContent, + listener, + Collections.emptySet() + ); + } } 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 index 6cce24cde78..5cee79659ed 100644 --- 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 @@ -19,8 +19,10 @@ package org.elasticsearch.client; import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPut; import org.elasticsearch.client.enrich.DeletePolicyRequest; +import org.elasticsearch.client.enrich.GetPolicyRequest; import org.elasticsearch.client.enrich.PutPolicyRequest; import java.io.IOException; @@ -48,4 +50,12 @@ final class EnrichRequestConverters { return new Request(HttpDelete.METHOD_NAME, endpoint); } + static Request getPolicy(GetPolicyRequest getPolicyRequest) throws IOException { + String endpoint = new RequestConverters.EndpointBuilder() + .addPathPartAsIs("_enrich", "policy") + .addCommaSeparatedPathParts(getPolicyRequest.getNames()) + .build(); + return new Request(HttpGet.METHOD_NAME, endpoint); + } + } 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 new file mode 100644 index 00000000000..cada904b31e --- /dev/null +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/enrich/GetPolicyRequest.java @@ -0,0 +1,46 @@ +/* + * 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 names; + + public GetPolicyRequest() { + this(Collections.emptyList()); + } + + public GetPolicyRequest(String... names) { + this(Arrays.asList(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 new file mode 100644 index 00000000000..d65d05f9e4e --- /dev/null +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/enrich/GetPolicyResponse.java @@ -0,0 +1,55 @@ +/* + * 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 PARSER = new ConstructingObjectParser<>( + "get_policy_response", + true, + args -> new GetPolicyResponse((List) args[0]) + ); + + static { + PARSER.declareObjectArray(ConstructingObjectParser.constructorArg(), + (p, c) -> NamedPolicy.fromXContent(p), new ParseField("policies")); + } + + 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 new file mode 100644 index 00000000000..ea0ea52e892 --- /dev/null +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/enrich/NamedPolicy.java @@ -0,0 +1,130 @@ +/* + * 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.BytesArray; +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 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 BytesArray.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 index 7385961ba59..8f2595333cb 100644 --- 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 @@ -19,7 +19,6 @@ package org.elasticsearch.client.enrich; import org.elasticsearch.client.Validatable; -import org.elasticsearch.common.ParseField; import org.elasticsearch.common.Strings; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.xcontent.ToXContentObject; @@ -36,11 +35,6 @@ import java.util.Objects; public class PutPolicyRequest implements Validatable, ToXContentObject { - 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"); - private final String name; private final String type; private BytesReference query; @@ -110,12 +104,12 @@ public class PutPolicyRequest implements Validatable, ToXContentObject { { builder.startObject(type); { - builder.field(INDICES_FIELD.getPreferredName(), indices); + builder.field(NamedPolicy.INDICES_FIELD.getPreferredName(), indices); if (query != null) { - builder.field(QUERY_FIELD.getPreferredName(), asMap(query, builder.contentType())); + builder.field(NamedPolicy.QUERY_FIELD.getPreferredName(), asMap(query, builder.contentType())); } - builder.field(MATCH_FIELD_FIELD.getPreferredName(), matchField); - builder.field(ENRICH_FIELDS_FIELD.getPreferredName(), enrichFields); + builder.field(NamedPolicy.MATCH_FIELD_FIELD.getPreferredName(), matchField); + builder.field(NamedPolicy.ENRICH_FIELDS_FIELD.getPreferredName(), enrichFields); } builder.endObject(); } diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/EnrichIT.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/EnrichIT.java index abb6c7a6800..9333f0ab946 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/EnrichIT.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/EnrichIT.java @@ -18,18 +18,13 @@ */ package org.elasticsearch.client; -import org.apache.http.util.EntityUtils; import org.elasticsearch.client.core.AcknowledgedResponse; import org.elasticsearch.client.enrich.DeletePolicyRequest; +import org.elasticsearch.client.enrich.GetPolicyRequest; +import org.elasticsearch.client.enrich.GetPolicyResponse; import org.elasticsearch.client.enrich.PutPolicyRequest; -import org.elasticsearch.common.xcontent.XContentHelper; -import org.elasticsearch.common.xcontent.json.JsonXContent; -import org.elasticsearch.common.xcontent.support.XContentMapValues; -import java.io.IOException; import java.util.Collections; -import java.util.List; -import java.util.Map; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; @@ -43,35 +38,22 @@ public class EnrichIT extends ESRestHighLevelClientTestCase { AcknowledgedResponse putPolicyResponse = execute(putPolicyRequest, enrichClient::putPolicy, enrichClient::putPolicyAsync); assertThat(putPolicyResponse.isAcknowledged(), is(true)); - // TODO: Replace with get policy hlrc code: - Request getPolicyRequest = new Request("get", "/_enrich/policy/my-policy"); - Response getPolicyResponse = highLevelClient().getLowLevelClient().performRequest(getPolicyRequest); - assertThat(getPolicyResponse.getHttpResponse().getStatusLine().getStatusCode(), equalTo(200)); - Map responseBody = toMap(getPolicyResponse); - List responsePolicies = (List) responseBody.get("policies"); - assertThat(responsePolicies.size(), equalTo(1)); - Map responsePolicy = (Map) responsePolicies.get(0); - assertThat(XContentMapValues.extractValue("match.indices", responsePolicy), equalTo(putPolicyRequest.getIndices())); - assertThat(XContentMapValues.extractValue("match.match_field", responsePolicy), equalTo(putPolicyRequest.getMatchField())); - assertThat(XContentMapValues.extractValue("match.enrich_fields", responsePolicy), - equalTo(putPolicyRequest.getEnrichFields())); + 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())); DeletePolicyRequest deletePolicyRequest = new DeletePolicyRequest("my-policy"); AcknowledgedResponse deletePolicyResponse = execute(deletePolicyRequest, enrichClient::deletePolicy, enrichClient::deletePolicyAsync); assertThat(deletePolicyResponse.isAcknowledged(), is(true)); - // TODO: Replace with get policy hlrc code: - getPolicyRequest = new Request("get", "/_enrich/policy"); - getPolicyResponse = highLevelClient().getLowLevelClient().performRequest(getPolicyRequest); - assertThat(getPolicyResponse.getHttpResponse().getStatusLine().getStatusCode(), equalTo(200)); - responseBody = toMap(getPolicyResponse); - responsePolicies = (List) responseBody.get("policies"); - assertThat(responsePolicies.size(), equalTo(0)); - } - - private static Map toMap(Response response) throws IOException { - return XContentHelper.convertToMap(JsonXContent.jsonXContent, EntityUtils.toString(response.getEntity()), false); + getPolicyRequest = new GetPolicyRequest(); + getPolicyResponse = execute(getPolicyRequest, enrichClient::getPolicy, enrichClient::getPolicyAsync); + assertThat(getPolicyResponse.getPolicies().size(), equalTo(0)); } } diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/EnrichRequestConvertersTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/EnrichRequestConvertersTests.java index 2506c22e5da..c1433d87099 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/EnrichRequestConvertersTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/EnrichRequestConvertersTests.java @@ -19,8 +19,10 @@ package org.elasticsearch.client; import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPut; import org.elasticsearch.client.enrich.DeletePolicyRequest; +import org.elasticsearch.client.enrich.GetPolicyRequest; import org.elasticsearch.client.enrich.PutPolicyRequest; import org.elasticsearch.client.enrich.PutPolicyRequestTests; import org.elasticsearch.test.ESTestCase; @@ -50,4 +52,30 @@ public class EnrichRequestConvertersTests extends ESTestCase { assertThat(result.getEntity(), nullValue()); } + public void testGetPolicy() throws Exception { + 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()); + } + } diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/EnrichDocumentationIT.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/EnrichDocumentationIT.java index 1fa3d506e27..46cc780ee53 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/EnrichDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/EnrichDocumentationIT.java @@ -25,10 +25,15 @@ 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.NamedPolicy; +import org.elasticsearch.client.enrich.GetPolicyRequest; +import org.elasticsearch.client.enrich.GetPolicyResponse; import org.elasticsearch.client.enrich.PutPolicyRequest; 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; @@ -143,4 +148,54 @@ public class EnrichDocumentationIT extends ESRestHighLevelClientTestCase { assertTrue(latch.await(30L, TimeUnit.SECONDS)); } + public void testGetPolicy() throws Exception { + RestHighLevelClient client = highLevelClient(); + + PutPolicyRequest putPolicyRequest = new PutPolicyRequest( + "users-policy", "exact_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 policies = getPolicyResponse.getPolicies(); // <1> + NamedPolicy policy = policies.get(0); + // end::enrich-get-policy-response + + // tag::enrich-get-policy-execute-listener + ActionListener listener = + new ActionListener() { + @Override + public void onResponse(GetPolicyResponse response) { // <1> + List 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)); + } + } diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/enrich/GetPolicyResponseTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/enrich/GetPolicyResponseTests.java new file mode 100644 index 00000000000..fc0cfb73339 --- /dev/null +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/enrich/GetPolicyResponseTests.java @@ -0,0 +1,95 @@ +/* + * 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.BytesArray; +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 { + + @Override + protected GetEnrichPolicyAction.Response createServerTestInstance(XContentType xContentType) { + int numPolicies = randomIntBetween(0, 8); + Map 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 = BytesArray.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); + } + } +} diff --git a/docs/java-rest/high-level/enrich/get_policy.asciidoc b/docs/java-rest/high-level/enrich/get_policy.asciidoc new file mode 100644 index 00000000000..401a78ccca6 --- /dev/null +++ b/docs/java-rest/high-level/enrich/get_policy.asciidoc @@ -0,0 +1,32 @@ +-- +:api: enrich-get-policy +:request: GetPolicyRequest +:response: GetPolicyResponse +-- + +[id="{upid}-{api}"] +=== Get Policy API + +[id="{upid}-{api}-request"] +==== Request + +The Get Policy API allows to retrieve enrich policies by name +or all policies if no name is provided. + +["source","java",subs="attributes,callouts,macros"] +-------------------------------------------------- +include-tagged::{doc-tests-file}[{api}-request] +-------------------------------------------------- + +[id="{upid}-{api}-response"] +==== Response + +The returned +{response}+ includes the requested enrich policy. + +["source","java",subs="attributes,callouts,macros"] +-------------------------------------------------- +include-tagged::{doc-tests-file}[{api}-response] +-------------------------------------------------- +<1> The actual enrich policy. + +include::../execution.asciidoc[] diff --git a/docs/java-rest/high-level/supported-apis.asciidoc b/docs/java-rest/high-level/supported-apis.asciidoc index 463a15c7b22..49c0cf050c9 100644 --- a/docs/java-rest/high-level/supported-apis.asciidoc +++ b/docs/java-rest/high-level/supported-apis.asciidoc @@ -604,6 +604,8 @@ The Java High Level REST Client supports the following Enrich APIs: * <<{upid}-enrich-put-policy>> * <<{upid}-enrich-delete-policy>> +* <<{upid}-enrich-get-policy>> include::enrich/put_policy.asciidoc[] include::enrich/delete_policy.asciidoc[] +include::enrich/get_policy.asciidoc[]