From f5070c7319b23853b89e37bdcad61e86a873fa56 Mon Sep 17 00:00:00 2001 From: Sylvain Wallez Date: Tue, 7 Dec 2021 11:26:50 +0100 Subject: [PATCH] Add test files to be included as doc snippets --- .../documentation/ApiConventionsTest.java | 240 ++++++++++++++++++ .../clients/documentation/ConnectingTest.java | 71 ++++++ .../documentation/FailingTransport.java | 97 +++++++ .../documentation/MigrateHlrcTest.java | 65 +++++ 4 files changed, 473 insertions(+) create mode 100644 java-client/src/test/java/co/elastic/clients/documentation/ApiConventionsTest.java create mode 100644 java-client/src/test/java/co/elastic/clients/documentation/ConnectingTest.java create mode 100644 java-client/src/test/java/co/elastic/clients/documentation/FailingTransport.java create mode 100644 java-client/src/test/java/co/elastic/clients/documentation/MigrateHlrcTest.java diff --git a/java-client/src/test/java/co/elastic/clients/documentation/ApiConventionsTest.java b/java-client/src/test/java/co/elastic/clients/documentation/ApiConventionsTest.java new file mode 100644 index 000000000..8c66b9ce6 --- /dev/null +++ b/java-client/src/test/java/co/elastic/clients/documentation/ApiConventionsTest.java @@ -0,0 +1,240 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. 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 co.elastic.clients.documentation; + +import co.elastic.clients.elasticsearch.ElasticsearchAsyncClient; +import co.elastic.clients.elasticsearch.ElasticsearchClient; +import co.elastic.clients.elasticsearch._types.SortOrder; +import co.elastic.clients.elasticsearch._types.aggregations.Aggregation; +import co.elastic.clients.elasticsearch._types.query_dsl.Query; +import co.elastic.clients.elasticsearch.core.SearchRequest; +import co.elastic.clients.elasticsearch.core.SearchResponse; +import co.elastic.clients.elasticsearch.indices.Alias; +import co.elastic.clients.elasticsearch.indices.CreateIndexRequest; +import co.elastic.clients.elasticsearch.indices.CreateIndexResponse; +import co.elastic.clients.transport.ElasticsearchTransport; +import co.elastic.clients.transport.TransportException; +import org.junit.Assert; +import org.junit.Test; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.LogManager; +import java.util.logging.Logger; + +public class ApiConventionsTest extends Assert { + + private static class SomeApplicationData {} + + private ElasticsearchTransport transport = new FailingTransport(); + Logger logger = LogManager.getLogManager().getLogger(ApiConventionsTest.class.getName()); + + @Test(expected = TransportException.class) + public void blockingAndAsync() throws Exception { + + //tag::blocking-and-async + // Synchronous blocking client + ElasticsearchClient client = new ElasticsearchClient(transport); + + if (client.exists(b -> b.index("products").id("foo")).value()) { + logger.info("product exists"); + } + + // Asynchronous non-blocking client + ElasticsearchAsyncClient asyncClient = + new ElasticsearchAsyncClient(transport); + + asyncClient + .exists(b -> b.index("products").id("foo")) + .thenAccept(response -> { + if (response.value()) { + logger.info("product exists"); + } + }); + //end::blocking-and-async + + } + + @Test(expected = TransportException.class) + public void builders() throws Exception { + ElasticsearchClient client = new ElasticsearchClient(transport); + + //tag::builders + CreateIndexResponse createResponse = client.indices().create( + new CreateIndexRequest.Builder() + .index("my-index") + .aliases("foo", + new Alias.Builder().isWriteIndex(true).build() + ) + .build() + ); + //end::builders + } + + @Test(expected = TransportException.class) + public void builderLambdas() throws Exception { + ElasticsearchClient client = new ElasticsearchClient(transport); + + //tag::builder-lambdas + CreateIndexResponse createResponse = client.indices() + .create(createIndexBuilder -> createIndexBuilder + .index("my-index") + .aliases("foo", aliasBuilder -> aliasBuilder + .isWriteIndex(true) + ) + ); + //end::builder-lambdas + } + + @Test(expected = TransportException.class) + public void builderLambdasShort() throws Exception { + ElasticsearchClient client = new ElasticsearchClient(transport); + + //tag::builder-lambdas-short + CreateIndexResponse createResponse = client.indices() + .create(c -> c + .index("my-index") + .aliases("foo", a -> a + .isWriteIndex(true) + ) + ); + //end::builder-lambdas-short + } + + @Test(expected = TransportException.class) + public void builderIntervals() throws Exception { + ElasticsearchClient client = new ElasticsearchClient(transport); + + //tag::builder-intervals + SearchResponse results = client + .search(_0 -> _0 + .query(_1 -> _1 + .intervals(_2 -> _2 + .field("my_text") + .allOf(_3 -> _3 + .ordered(true) + .intervals(_4 -> _4 + .match(_5 -> _5 + .query("my favorite food") + .maxGaps(0) + .ordered(true) + ) + ) + .intervals(_4 -> _4 + .anyOf(_5 -> _5 + .intervals(_6 -> _6 + .match(_7 -> _7 + .query("hot water") + ) + ) + .intervals(_6 -> _6 + .match(_7 -> _7 + .query("cold porridge") + ) + ) + ) + ) + ) + ) + ), + SomeApplicationData.class // <1> + ); + //end::builder-intervals + } + + @Test + public void variantCreation() { + //tag::variant-creation + Query query = new Query.Builder() + .term(t -> t // <1> + .field("name") // <2> + .value(v -> v.stringValue("foo")) + ) + .build(); // <3> + //end::variant-creation + + //tag::variant-navigation + assertEquals("foo", query.term().value().stringValue()); + //end::variant-navigation + + //tag::variant-kind + if (query.isTerm()) { // <1> + doSomething(query.term()); + } + + switch(query._kind()) { // <2> + case Term: + doSomething(query.term()); + break; + case Intervals: + doSomething(query.intervals()); + break; + default: + doSomething(query._kind(), query._get()); // <3> + } + //end::variant-kind + } + + @Test + public void collections() { + //tag::collections-list + // Prepare a list of index names + List names = Arrays.asList("idx-a", "idx-b", "idx-c"); + + // Prepare cardinality aggregations for fields "foo" and "bar" + Map cardinalities = new HashMap<>(); + cardinalities.put("foo-count", Aggregation.of(a -> a.cardinality(c -> c.field("foo")))); + cardinalities.put("bar-count", Aggregation.of(a -> a.cardinality(c -> c.field("bar")))); + + // Prepare an aggregation that computes the average of the "size" field + final Aggregation avgSize = Aggregation.of(a -> a.avg(v -> v.field("size"))); + + SearchRequest search = SearchRequest.of(r -> r + // Index list: + // - add all elements of a list + .index(names) + // - add a single element + .index("idx-d") + // - add a vararg list of elements + .index("idx-e", "idx-f", "idx-g") + + // Sort order list: add elements defined by builder lambdas + .sort(s -> s.field(f -> f.field("foo").order(SortOrder.Asc))) + .sort(s -> s.field(f -> f.field("bar").order(SortOrder.Desc))) + + // Aggregation map: + // - add all entries of an existing map + .aggregations(cardinalities) + // - add a key/value entry + .aggregations("avg-size", avgSize) + // - add a key/value defined by a builder lambda + .aggregations("price-histogram", + a -> a.histogram(h -> h.field("price"))) + ); + //end::collections-list + + } + + private void doSomething(Object... o) { + + } +} diff --git a/java-client/src/test/java/co/elastic/clients/documentation/ConnectingTest.java b/java-client/src/test/java/co/elastic/clients/documentation/ConnectingTest.java new file mode 100644 index 000000000..cb811f6c4 --- /dev/null +++ b/java-client/src/test/java/co/elastic/clients/documentation/ConnectingTest.java @@ -0,0 +1,71 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. 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 co.elastic.clients.documentation; + +import co.elastic.clients.elasticsearch.ElasticsearchClient; +import co.elastic.clients.elasticsearch.core.SearchResponse; +import co.elastic.clients.elasticsearch.core.search.Hit; +import co.elastic.clients.json.jackson.JacksonJsonpMapper; +import co.elastic.clients.transport.ElasticsearchTransport; +import co.elastic.clients.transport.rest_client.RestClientTransport; +import org.apache.http.HttpHost; +import org.elasticsearch.client.RestClient; +import org.junit.Ignore; +import org.junit.Test; + +public class ConnectingTest { + + private static class Product{} + + @Ignore // we don't have a running ES + @Test + public void createClient() throws Exception { + //tag::create-client + // Create the low-level client + RestClient restClient = RestClient.builder( + new HttpHost("localhost", 9200)).build(); + + // Create the transport with a Jackson mapper + ElasticsearchTransport transport = new RestClientTransport( + restClient, new JacksonJsonpMapper()); + + // And create the API client + ElasticsearchClient client = new ElasticsearchClient(transport); + //end::create-client + + //tag::first-request + SearchResponse search = client.search(s -> s + .index("products") + .query(q -> q + .term(t -> t + .field("name") + .value(v -> v.stringValue("bicycle")) + )), + Product.class); + + for (Hit hit: search.hits().hits()) { + processProduct(hit.source()); + } + //end::first-request + } + + private void processProduct(Product p) {} + +} diff --git a/java-client/src/test/java/co/elastic/clients/documentation/FailingTransport.java b/java-client/src/test/java/co/elastic/clients/documentation/FailingTransport.java new file mode 100644 index 000000000..a0f7443c6 --- /dev/null +++ b/java-client/src/test/java/co/elastic/clients/documentation/FailingTransport.java @@ -0,0 +1,97 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. 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 co.elastic.clients.documentation; + +import co.elastic.clients.json.JsonpMapper; +import co.elastic.clients.json.jsonb.JsonbJsonpMapper; +import co.elastic.clients.transport.ElasticsearchTransport; +import co.elastic.clients.transport.Endpoint; +import co.elastic.clients.transport.TransportException; +import co.elastic.clients.transport.TransportOptions; + +import javax.annotation.Nullable; +import java.io.IOException; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.function.Function; + +/** + * A transport implementation that always fails. Used for simple doc sections where we just want to check compilation. + */ +public class FailingTransport implements ElasticsearchTransport { + + private JsonpMapper mapper = new JsonbJsonpMapper(); + + private TransportOptions options = new TransportOptions() { + @Override + public Collection> headers() { + return Collections.emptyList(); + } + + @Override + public Map queryParameters() { + return Collections.emptyMap(); + } + + @Override + public Function, Boolean> onWarnings() { + return null; + } + + @Override + public Builder toBuilder() { + return null; + } + }; + + @Override + public ResponseT performRequest( + RequestT request, + Endpoint endpoint, + @Nullable TransportOptions options + ) throws IOException { + throw new TransportException("Not implemented", endpoint.id()); + } + + @Override + public CompletableFuture performRequestAsync(RequestT request, Endpoint endpoint, @Nullable TransportOptions options) { + CompletableFuture future = new CompletableFuture<>(); + future.completeExceptionally(new TransportException("Not implemented", endpoint.id())); + return future; + } + + @Override + public JsonpMapper jsonpMapper() { + return mapper; + } + + @Override + public TransportOptions options() { + return options; + } + + @Override + public void close() throws IOException { + } +} diff --git a/java-client/src/test/java/co/elastic/clients/documentation/MigrateHlrcTest.java b/java-client/src/test/java/co/elastic/clients/documentation/MigrateHlrcTest.java new file mode 100644 index 000000000..4d8ca3230 --- /dev/null +++ b/java-client/src/test/java/co/elastic/clients/documentation/MigrateHlrcTest.java @@ -0,0 +1,65 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. 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 co.elastic.clients.documentation; + +import co.elastic.clients.elasticsearch.ElasticsearchClient; +import co.elastic.clients.json.jackson.JacksonJsonpMapper; +import co.elastic.clients.transport.ElasticsearchTransport; +import co.elastic.clients.transport.rest_client.RestClientTransport; +import org.apache.http.HttpHost; +import org.elasticsearch.client.RestClient; +import org.elasticsearch.client.RestClientBuilder; +import org.junit.Test; + +public class MigrateHlrcTest { + + // Fake HLRC -- we don't want to import it for just one example + public static class RestHighLevelClient { + public RestHighLevelClient(RestClientBuilder builder) { + } + + public RestClient getLowLevelClient() { + return null; + } + } + + @Test + public void migrate() { + //tag::migrate + // Create the low-level client + RestClientBuilder httpClientBuilder = RestClient.builder( + new HttpHost("localhost", 9200) + ); + + // Create the HLRC + RestHighLevelClient hlrc = new RestHighLevelClient(httpClientBuilder); + + // Create the new Java Client with the same low level client + ElasticsearchTransport transport = new RestClientTransport( + hlrc.getLowLevelClient(), + new JacksonJsonpMapper() + ); + + ElasticsearchClient esClient = new ElasticsearchClient(transport); + + // hlrc and esClient share the same httpClient + //end::migrate + } +}