From 4d53709868c3d4ecfa729c582b515b5e614f8974 Mon Sep 17 00:00:00 2001 From: javanna Date: Mon, 14 May 2018 20:53:41 +0200 Subject: [PATCH 01/13] Replace Request#setHeaders with addHeaders Adding headers rather than setting them all at once seems more user-friendly and we already do it in a similar way for parameters (see Request#addParameter). --- .../org/elasticsearch/client/Request.java | 30 ++++++++------- .../org/elasticsearch/client/RestClient.java | 20 +++++----- .../elasticsearch/client/RequestTests.java | 38 +++++++++++-------- .../client/RestClientSingleHostTests.java | 8 ++-- .../elasticsearch/client/RestClientTests.java | 2 +- .../RestClientDocumentation.java | 6 +-- docs/java-rest/low-level/usage.asciidoc | 2 +- .../rest/yaml/ESClientYamlSuiteTestCase.java | 2 +- .../xpack/qa/sql/rest/RestSqlTestCase.java | 8 +--- 9 files changed, 59 insertions(+), 57 deletions(-) diff --git a/client/rest/src/main/java/org/elasticsearch/client/Request.java b/client/rest/src/main/java/org/elasticsearch/client/Request.java index 92610239cae92..fddf94d2a20b6 100644 --- a/client/rest/src/main/java/org/elasticsearch/client/Request.java +++ b/client/rest/src/main/java/org/elasticsearch/client/Request.java @@ -19,14 +19,16 @@ package org.elasticsearch.client; -import org.apache.http.entity.ContentType; import org.apache.http.Header; import org.apache.http.HttpEntity; +import org.apache.http.entity.ContentType; import org.apache.http.nio.entity.NStringEntity; import org.apache.http.nio.protocol.HttpAsyncResponseConsumer; -import java.util.Arrays; +import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Objects; @@ -36,13 +38,13 @@ * HTTP Request to Elasticsearch. */ public final class Request { - private static final Header[] NO_HEADERS = new Header[0]; private final String method; private final String endpoint; private final Map parameters = new HashMap<>(); private HttpEntity entity; - private Header[] headers = NO_HEADERS; + + private List
headers = new ArrayList<>(); private HttpAsyncResponseConsumerFactory httpAsyncResponseConsumerFactory = HttpAsyncResponseConsumerFactory.DEFAULT; @@ -125,21 +127,21 @@ public HttpEntity getEntity() { } /** - * Set the headers to attach to the request. + * Add the provided headers to the request. */ - public void setHeaders(Header... headers) { + public void addHeaders(Header... headers) { Objects.requireNonNull(headers, "headers cannot be null"); for (Header header : headers) { Objects.requireNonNull(header, "header cannot be null"); } - this.headers = headers; + Collections.addAll(this.headers, headers); } /** * Headers to attach to the request. */ - public Header[] getHeaders() { - return headers; + public List
getHeaders() { + return Collections.unmodifiableList(headers); } /** @@ -175,13 +177,13 @@ public String toString() { if (entity != null) { b.append(", entity=").append(entity); } - if (headers.length > 0) { + if (headers.size() > 0) { b.append(", headers="); - for (int h = 0; h < headers.length; h++) { + for (int h = 0; h < headers.size(); h++) { if (h != 0) { b.append(','); } - b.append(headers[h].toString()); + b.append(headers.get(h).toString()); } } if (httpAsyncResponseConsumerFactory != HttpAsyncResponseConsumerFactory.DEFAULT) { @@ -204,12 +206,12 @@ public boolean equals(Object obj) { && endpoint.equals(other.endpoint) && parameters.equals(other.parameters) && Objects.equals(entity, other.entity) - && Arrays.equals(headers, other.headers) + && headers.equals(other.headers) && httpAsyncResponseConsumerFactory.equals(other.httpAsyncResponseConsumerFactory); } @Override public int hashCode() { - return Objects.hash(method, endpoint, parameters, entity, Arrays.hashCode(headers), httpAsyncResponseConsumerFactory); + return Objects.hash(method, endpoint, parameters, entity, headers, httpAsyncResponseConsumerFactory); } } diff --git a/client/rest/src/main/java/org/elasticsearch/client/RestClient.java b/client/rest/src/main/java/org/elasticsearch/client/RestClient.java index 05fa4d536b3b6..ff66ec8dbde61 100644 --- a/client/rest/src/main/java/org/elasticsearch/client/RestClient.java +++ b/client/rest/src/main/java/org/elasticsearch/client/RestClient.java @@ -215,7 +215,7 @@ public void performRequestAsync(Request request, ResponseListener responseListen @Deprecated public Response performRequest(String method, String endpoint, Header... headers) throws IOException { Request request = new Request(method, endpoint); - request.setHeaders(headers); + request.addHeaders(headers); return performRequest(request); } @@ -237,7 +237,7 @@ public Response performRequest(String method, String endpoint, Header... headers public Response performRequest(String method, String endpoint, Map params, Header... headers) throws IOException { Request request = new Request(method, endpoint); addParameters(request, params); - request.setHeaders(headers); + request.addHeaders(headers); return performRequest(request); } @@ -264,7 +264,7 @@ public Response performRequest(String method, String endpoint, Map requestHeaders) { // request headers override default headers, so we don't add default headers if they exist as request headers - final Set requestNames = new HashSet<>(requestHeaders.length); + final Set requestNames = new HashSet<>(requestHeaders.size()); for (Header requestHeader : requestHeaders) { httpRequest.addHeader(requestHeader); requestNames.add(requestHeader.getName()); diff --git a/client/rest/src/test/java/org/elasticsearch/client/RequestTests.java b/client/rest/src/test/java/org/elasticsearch/client/RequestTests.java index b83115a5341dd..7dc45e414ab5c 100644 --- a/client/rest/src/test/java/org/elasticsearch/client/RequestTests.java +++ b/client/rest/src/test/java/org/elasticsearch/client/RequestTests.java @@ -19,19 +19,19 @@ package org.elasticsearch.client; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicHeader; -import org.apache.http.nio.entity.NStringEntity; -import static org.junit.Assert.assertArrayEquals; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; @@ -124,31 +124,39 @@ public void testSetJsonEntity() throws IOException { assertEquals(json, new String(os.toByteArray(), ContentType.APPLICATION_JSON.getCharset())); } - public void testSetHeaders() { + public void testAddHeaders() { final String method = randomFrom(new String[] {"GET", "PUT", "POST", "HEAD", "DELETE"}); final String endpoint = randomAsciiLettersOfLengthBetween(1, 10); Request request = new Request(method, endpoint); try { - request.setHeaders((Header[]) null); + request.addHeaders((Header[]) null); fail("expected failure"); } catch (NullPointerException e) { assertEquals("headers cannot be null", e.getMessage()); } try { - request.setHeaders(new Header [] {null}); + request.addHeaders(new Header [] {null}); fail("expected failure"); } catch (NullPointerException e) { assertEquals("header cannot be null", e.getMessage()); } - Header[] headers = new Header[between(0, 5)]; - for (int i = 0; i < headers.length; i++) { - headers[i] = new BasicHeader(randomAsciiAlphanumOfLength(3), randomAsciiAlphanumOfLength(3)); + List
headers = new ArrayList<>(between(0, 5)); + for (int i = 0; i < headers.size(); i++) { + BasicHeader header = new BasicHeader(randomAsciiAlphanumOfLength(3), randomAsciiAlphanumOfLength(3)); + headers.add(header); + request.addHeaders(header); + } + if (headers.size() > 0 && randomBoolean()) { + //check that duplicates are accepted at this stage + Header header = headers.get(randomIntBetween(0, headers.size() - 1)); + BasicHeader basicHeader = new BasicHeader(header.getName(), randomAsciiAlphanumOfLength(3)); + headers.add(basicHeader); + request.addHeaders(basicHeader); } - request.setHeaders(headers); - assertArrayEquals(headers, request.getHeaders()); + assertEquals(headers, request.getHeaders()); } // TODO equals and hashcode diff --git a/client/rest/src/test/java/org/elasticsearch/client/RestClientSingleHostTests.java b/client/rest/src/test/java/org/elasticsearch/client/RestClientSingleHostTests.java index 714d2e57e6d20..c0618c55af973 100644 --- a/client/rest/src/test/java/org/elasticsearch/client/RestClientSingleHostTests.java +++ b/client/rest/src/test/java/org/elasticsearch/client/RestClientSingleHostTests.java @@ -312,7 +312,7 @@ public void testBody() throws IOException { } /** - * @deprecated will remove method in 7.0 but needs tests until then. Replaced by {@link RequestTests#testSetHeaders()}. + * @deprecated will remove method in 7.0 but needs tests until then. Replaced by {@link RequestTests#testAddHeaders()}. */ @Deprecated public void tesPerformRequestOldStyleNullHeaders() throws IOException { @@ -333,7 +333,7 @@ public void tesPerformRequestOldStyleNullHeaders() throws IOException { } /** - * @deprecated will remove method in 7.0 but needs tests until then. Replaced by {@link RequestTests#testSetParameters()}. + * @deprecated will remove method in 7.0 but needs tests until then. Replaced by {@link RequestTests#testAddParameters()}. */ @Deprecated public void testPerformRequestOldStyleWithNullParams() throws IOException { @@ -362,7 +362,7 @@ public void testHeaders() throws IOException { final Header[] requestHeaders = RestClientTestUtil.randomHeaders(getRandom(), "Header"); final int statusCode = randomStatusCode(getRandom()); Request request = new Request(method, "/" + statusCode); - request.setHeaders(requestHeaders); + request.addHeaders(requestHeaders); Response esResponse; try { esResponse = restClient.performRequest(request); @@ -436,7 +436,7 @@ private HttpUriRequest performRandomRequest(String method) throws Exception { final Set uniqueNames = new HashSet<>(); if (randomBoolean()) { Header[] headers = RestClientTestUtil.randomHeaders(getRandom(), "Header"); - request.setHeaders(headers); + request.addHeaders(headers); for (Header header : headers) { expectedRequest.addHeader(header); uniqueNames.add(header.getName()); diff --git a/client/rest/src/test/java/org/elasticsearch/client/RestClientTests.java b/client/rest/src/test/java/org/elasticsearch/client/RestClientTests.java index ea124828e45eb..84399c1e6e1c9 100644 --- a/client/rest/src/test/java/org/elasticsearch/client/RestClientTests.java +++ b/client/rest/src/test/java/org/elasticsearch/client/RestClientTests.java @@ -120,7 +120,7 @@ public void onFailure(Exception exception) { } /** - * @deprecated will remove method in 7.0 but needs tests until then. Replaced by {@link RequestTests#testSetHeaders()}. + * @deprecated will remove method in 7.0 but needs tests until then. Replaced by {@link RequestTests#testAddHeaders()}. */ @Deprecated public void testPerformOldStyleAsyncWithNullHeaders() throws Exception { diff --git a/client/rest/src/test/java/org/elasticsearch/client/documentation/RestClientDocumentation.java b/client/rest/src/test/java/org/elasticsearch/client/documentation/RestClientDocumentation.java index 5ee97399b34e6..9848614b2e081 100644 --- a/client/rest/src/test/java/org/elasticsearch/client/documentation/RestClientDocumentation.java +++ b/client/rest/src/test/java/org/elasticsearch/client/documentation/RestClientDocumentation.java @@ -27,9 +27,7 @@ import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.config.RequestConfig; -import org.apache.http.entity.BasicHttpEntity; import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.nio.client.HttpAsyncClientBuilder; import org.apache.http.impl.nio.reactor.IOReactorConfig; @@ -52,8 +50,6 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.security.KeyStore; -import java.util.Collections; -import java.util.Map; import java.util.concurrent.CountDownLatch; /** @@ -176,7 +172,7 @@ public void onFailure(Exception exception) { request.setJsonEntity("{\"json\":\"text\"}"); //end::rest-client-body-shorter //tag::rest-client-headers - request.setHeaders( + request.addHeaders( new BasicHeader("Accept", "text/plain"), new BasicHeader("Cache-Control", "no-cache")); //end::rest-client-headers diff --git a/docs/java-rest/low-level/usage.asciidoc b/docs/java-rest/low-level/usage.asciidoc index 68367b9a64fdf..012ce418226cd 100644 --- a/docs/java-rest/low-level/usage.asciidoc +++ b/docs/java-rest/low-level/usage.asciidoc @@ -271,7 +271,7 @@ a `ContentType` of `application/json`. include-tagged::{doc-tests}/RestClientDocumentation.java[rest-client-body-shorter] -------------------------------------------------- -And you can set a list of headers to send with the request: +And you can add one or more headers to send with the request: ["source","java",subs="attributes,callouts,macros"] -------------------------------------------------- diff --git a/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/ESClientYamlSuiteTestCase.java b/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/ESClientYamlSuiteTestCase.java index ab99bc0d97ba4..22814943cb3b1 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/ESClientYamlSuiteTestCase.java +++ b/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/ESClientYamlSuiteTestCase.java @@ -333,7 +333,7 @@ public void test() throws IOException { if (useDefaultNumberOfShards == false && testCandidate.getTestSection().getSkipSection().getFeatures().contains("default_shards") == false) { final Request request = new Request("PUT", "/_template/global"); - request.setHeaders(new BasicHeader("Content-Type", XContentType.JSON.mediaTypeWithoutParameters())); + request.addHeaders(new BasicHeader("Content-Type", XContentType.JSON.mediaTypeWithoutParameters())); request.setEntity(new StringEntity("{\"index_patterns\":[\"*\"],\"settings\":{\"index.number_of_shards\":2}}")); adminClient().performRequest(request); } diff --git a/x-pack/qa/sql/src/main/java/org/elasticsearch/xpack/qa/sql/rest/RestSqlTestCase.java b/x-pack/qa/sql/src/main/java/org/elasticsearch/xpack/qa/sql/rest/RestSqlTestCase.java index 3019a00351c28..1e12ca3e4a570 100644 --- a/x-pack/qa/sql/src/main/java/org/elasticsearch/xpack/qa/sql/rest/RestSqlTestCase.java +++ b/x-pack/qa/sql/src/main/java/org/elasticsearch/xpack/qa/sql/rest/RestSqlTestCase.java @@ -6,7 +6,6 @@ package org.elasticsearch.xpack.qa.sql.rest; import com.fasterxml.jackson.core.io.JsonStringEncoder; - import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.entity.ContentType; @@ -16,7 +15,6 @@ import org.elasticsearch.client.Response; import org.elasticsearch.client.ResponseException; import org.elasticsearch.common.CheckedSupplier; -import org.elasticsearch.common.Strings; import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.common.io.Streams; import org.elasticsearch.common.xcontent.XContentHelper; @@ -35,10 +33,8 @@ import java.util.HashMap; import java.util.Locale; import java.util.Map; -import java.util.TreeMap; import static java.util.Collections.emptyList; -import static java.util.Collections.emptyMap; import static java.util.Collections.singletonList; import static java.util.Collections.singletonMap; import static java.util.Collections.unmodifiableMap; @@ -323,7 +319,7 @@ private Map runSql(String mode, HttpEntity sql, String suffix) t if (false == mode.isEmpty()) { request.addParameter("mode", mode); // JDBC or PLAIN mode } - request.setHeaders(randomFrom( + request.addHeaders(randomFrom( new Header[] {}, new Header[] {new BasicHeader("Accept", "*/*")}, new Header[] {new BasicHeader("Accpet", "application/json")})); @@ -538,7 +534,7 @@ private Tuple runSqlAsText(String suffix, HttpEntity entity, Str Request request = new Request("POST", "/_xpack/sql" + suffix); request.addParameter("error_trace", "true"); request.setEntity(entity); - request.setHeaders(new BasicHeader("Accept", accept)); + request.addHeaders(new BasicHeader("Accept", accept)); Response response = client().performRequest(request); return new Tuple<>( Streams.copyToString(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8)), From 7ce5692d05248aecef6054867ad85ad55b2362f4 Mon Sep 17 00:00:00 2001 From: javanna Date: Mon, 14 May 2018 20:55:35 +0200 Subject: [PATCH 02/13] remove empty line --- client/rest/src/main/java/org/elasticsearch/client/Request.java | 1 - 1 file changed, 1 deletion(-) diff --git a/client/rest/src/main/java/org/elasticsearch/client/Request.java b/client/rest/src/main/java/org/elasticsearch/client/Request.java index fddf94d2a20b6..d68f8ea73d1dc 100644 --- a/client/rest/src/main/java/org/elasticsearch/client/Request.java +++ b/client/rest/src/main/java/org/elasticsearch/client/Request.java @@ -43,7 +43,6 @@ public final class Request { private final Map parameters = new HashMap<>(); private HttpEntity entity; - private List
headers = new ArrayList<>(); private HttpAsyncResponseConsumerFactory httpAsyncResponseConsumerFactory = HttpAsyncResponseConsumerFactory.DEFAULT; From 608b13910bf1109e60fb832ba5e5f01e2239f38b Mon Sep 17 00:00:00 2001 From: javanna Date: Mon, 14 May 2018 21:00:08 +0200 Subject: [PATCH 03/13] fix more issues --- .../java/org/elasticsearch/client/RestHighLevelClient.java | 6 ++---- .../client/CustomRestHighLevelClientTests.java | 4 ++-- .../xpack/qa/sql/security/RestSqlSecurityIT.java | 6 +----- 3 files changed, 5 insertions(+), 11 deletions(-) diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/RestHighLevelClient.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/RestHighLevelClient.java index 1985d6bd06dd4..c8ff510a55621 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/RestHighLevelClient.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/RestHighLevelClient.java @@ -26,8 +26,6 @@ import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.ActionRequestValidationException; -import org.elasticsearch.action.admin.cluster.repositories.get.GetRepositoriesRequest; -import org.elasticsearch.action.admin.cluster.repositories.get.GetRepositoriesResponse; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.delete.DeleteRequest; @@ -564,7 +562,7 @@ protected final Resp performRequest(Req reques throw validationException; } Request req = requestConverter.apply(request); - req.setHeaders(headers); + req.addHeaders(headers); Response response; try { response = client.performRequest(req); @@ -614,7 +612,7 @@ protected final void performRequestAsync(Req r listener.onFailure(e); return; } - req.setHeaders(headers); + req.addHeaders(headers); ResponseListener responseListener = wrapResponseListener(responseConverter, listener, ignores); client.performRequestAsync(req, responseListener); diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/CustomRestHighLevelClientTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/CustomRestHighLevelClientTests.java index 617b35c4d40f3..1da9b23452892 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/CustomRestHighLevelClientTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/CustomRestHighLevelClientTests.java @@ -73,12 +73,12 @@ public void initClients() throws IOException { final RestClient restClient = mock(RestClient.class); restHighLevelClient = new CustomRestClient(restClient); - doAnswer(inv -> mockPerformRequest(((Request) inv.getArguments()[0]).getHeaders()[0])) + doAnswer(inv -> mockPerformRequest(((Request) inv.getArguments()[0]).getHeaders().get(0))) .when(restClient) .performRequest(any(Request.class)); doAnswer(inv -> mockPerformRequestAsync( - ((Request) inv.getArguments()[0]).getHeaders()[0], + ((Request) inv.getArguments()[0]).getHeaders().get(0), (ResponseListener) inv.getArguments()[1])) .when(restClient) .performRequestAsync(any(Request.class), any(ResponseListener.class)); diff --git a/x-pack/qa/sql/security/src/test/java/org/elasticsearch/xpack/qa/sql/security/RestSqlSecurityIT.java b/x-pack/qa/sql/security/src/test/java/org/elasticsearch/xpack/qa/sql/security/RestSqlSecurityIT.java index f7abb6f64f63c..e91d8e4449feb 100644 --- a/x-pack/qa/sql/security/src/test/java/org/elasticsearch/xpack/qa/sql/security/RestSqlSecurityIT.java +++ b/x-pack/qa/sql/security/src/test/java/org/elasticsearch/xpack/qa/sql/security/RestSqlSecurityIT.java @@ -5,7 +5,6 @@ */ package org.elasticsearch.xpack.qa.sql.security; -import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; @@ -14,11 +13,9 @@ import org.elasticsearch.client.Response; import org.elasticsearch.client.ResponseException; import org.elasticsearch.common.Nullable; -import org.elasticsearch.common.Strings; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.test.NotEqualMessageBuilder; -import org.elasticsearch.xpack.qa.sql.security.SqlSecurityTestCase.AuditLogAsserter; import org.hamcrest.Matcher; import org.hamcrest.Matchers; @@ -30,7 +27,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.TreeMap; import java.util.stream.Collectors; import static org.elasticsearch.xpack.qa.sql.rest.RestSqlTestCase.columnInfo; @@ -182,7 +178,7 @@ private static Map runSql(@Nullable String asUser, String mode, request.addParameter("mode", mode); } if (asUser != null) { - request.setHeaders(new BasicHeader("es-security-runas-user", asUser)); + request.addHeaders(new BasicHeader("es-security-runas-user", asUser)); } request.setEntity(entity); return toMap(client().performRequest(request)); From d953894ddf76a18ea8734b3b75f993bd40111156 Mon Sep 17 00:00:00 2001 From: javanna Date: Tue, 15 May 2018 10:59:46 +0200 Subject: [PATCH 04/13] Remove varargs argument, replace addHeaders with addHeader --- .../client/RestHighLevelClient.java | 11 +++- .../CustomRestHighLevelClientTests.java | 4 +- .../org/elasticsearch/client/Request.java | 13 ++-- .../org/elasticsearch/client/RestClient.java | 33 +++++++--- .../elasticsearch/client/RequestTests.java | 64 ++++++++++++------- .../RestClientSingleHostIntegTests.java | 3 - .../client/RestClientSingleHostTests.java | 6 +- .../RestClientDocumentation.java | 5 +- .../rest/yaml/ESClientYamlSuiteTestCase.java | 2 +- .../qa/sql/security/RestSqlSecurityIT.java | 2 +- .../xpack/qa/sql/rest/RestSqlTestCase.java | 10 ++- 11 files changed, 93 insertions(+), 60 deletions(-) diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/RestHighLevelClient.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/RestHighLevelClient.java index c8ff510a55621..0841ab9b01a9c 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/RestHighLevelClient.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/RestHighLevelClient.java @@ -562,7 +562,7 @@ protected final Resp performRequest(Req reques throw validationException; } Request req = requestConverter.apply(request); - req.addHeaders(headers); + addHeaders(req, headers); Response response; try { response = client.performRequest(req); @@ -612,12 +612,19 @@ protected final void performRequestAsync(Req r listener.onFailure(e); return; } - req.addHeaders(headers); + addHeaders(req, headers); ResponseListener responseListener = wrapResponseListener(responseConverter, listener, ignores); client.performRequestAsync(req, responseListener); } + private static void addHeaders(Request request, Header... headers) { + Objects.requireNonNull(headers, "headers cannot be null"); + for (Header header : headers) { + request.addHeader(header); + } + } + final ResponseListener wrapResponseListener(CheckedFunction responseConverter, ActionListener actionListener, Set ignores) { return new ResponseListener() { diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/CustomRestHighLevelClientTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/CustomRestHighLevelClientTests.java index 1da9b23452892..0bd6ecef8fb5c 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/CustomRestHighLevelClientTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/CustomRestHighLevelClientTests.java @@ -73,12 +73,12 @@ public void initClients() throws IOException { final RestClient restClient = mock(RestClient.class); restHighLevelClient = new CustomRestClient(restClient); - doAnswer(inv -> mockPerformRequest(((Request) inv.getArguments()[0]).getHeaders().get(0))) + doAnswer(inv -> mockPerformRequest(((Request) inv.getArguments()[0]).getHeaders().iterator().next())) .when(restClient) .performRequest(any(Request.class)); doAnswer(inv -> mockPerformRequestAsync( - ((Request) inv.getArguments()[0]).getHeaders().get(0), + ((Request) inv.getArguments()[0]).getHeaders().iterator().next(), (ResponseListener) inv.getArguments()[1])) .when(restClient) .performRequestAsync(any(Request.class), any(ResponseListener.class)); diff --git a/client/rest/src/main/java/org/elasticsearch/client/Request.java b/client/rest/src/main/java/org/elasticsearch/client/Request.java index d68f8ea73d1dc..93be5b62a0509 100644 --- a/client/rest/src/main/java/org/elasticsearch/client/Request.java +++ b/client/rest/src/main/java/org/elasticsearch/client/Request.java @@ -41,9 +41,9 @@ public final class Request { private final String method; private final String endpoint; private final Map parameters = new HashMap<>(); + private final List
headers = new ArrayList<>(); private HttpEntity entity; - private List
headers = new ArrayList<>(); private HttpAsyncResponseConsumerFactory httpAsyncResponseConsumerFactory = HttpAsyncResponseConsumerFactory.DEFAULT; @@ -126,14 +126,11 @@ public HttpEntity getEntity() { } /** - * Add the provided headers to the request. + * Add the provided header to the request. */ - public void addHeaders(Header... headers) { - Objects.requireNonNull(headers, "headers cannot be null"); - for (Header header : headers) { - Objects.requireNonNull(header, "header cannot be null"); - } - Collections.addAll(this.headers, headers); + public void addHeader(Header header) { + Objects.requireNonNull(header, "header cannot be null"); + this.headers.add(header); } /** diff --git a/client/rest/src/main/java/org/elasticsearch/client/RestClient.java b/client/rest/src/main/java/org/elasticsearch/client/RestClient.java index ff66ec8dbde61..1bcd4e72efa51 100644 --- a/client/rest/src/main/java/org/elasticsearch/client/RestClient.java +++ b/client/rest/src/main/java/org/elasticsearch/client/RestClient.java @@ -215,7 +215,9 @@ public void performRequestAsync(Request request, ResponseListener responseListen @Deprecated public Response performRequest(String method, String endpoint, Header... headers) throws IOException { Request request = new Request(method, endpoint); - request.addHeaders(headers); + for (Header header : headers) { + request.addHeader(header); + } return performRequest(request); } @@ -237,7 +239,7 @@ public Response performRequest(String method, String endpoint, Header... headers public Response performRequest(String method, String endpoint, Map params, Header... headers) throws IOException { Request request = new Request(method, endpoint); addParameters(request, params); - request.addHeaders(headers); + addHeaders(request, headers); return performRequest(request); } @@ -264,7 +266,7 @@ public Response performRequest(String method, String endpoint, Map requestHeaders) { + private void setHeaders(HttpRequest httpRequest, Collection
requestHeaders) { // request headers override default headers, so we don't add default headers if they exist as request headers final Set requestNames = new HashSet<>(requestHeaders.size()); for (Header requestHeader : requestHeaders) { @@ -881,6 +883,19 @@ private static class HostTuple { * Add all parameters from a map to a {@link Request}. This only exists * to support methods that exist for backwards compatibility. */ + @Deprecated + private static void addHeaders(Request request, Header... headers) { + Objects.requireNonNull(headers, "headers cannot be null"); + for (Header header : headers) { + request.addHeader(header); + } + } + + /** + * Add all parameters from a map to a {@link Request}. This only exists + * to support methods that exist for backwards compatibility. + */ + @Deprecated private static void addParameters(Request request, Map parameters) { Objects.requireNonNull(parameters, "parameters cannot be null"); for (Map.Entry entry : parameters.entrySet()) { diff --git a/client/rest/src/test/java/org/elasticsearch/client/RequestTests.java b/client/rest/src/test/java/org/elasticsearch/client/RequestTests.java index caed2e86390dd..e89282f04d9eb 100644 --- a/client/rest/src/test/java/org/elasticsearch/client/RequestTests.java +++ b/client/rest/src/test/java/org/elasticsearch/client/RequestTests.java @@ -32,8 +32,10 @@ import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; -import java.util.List; +import java.util.HashSet; +import java.util.Locale; import java.util.Map; +import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; @@ -134,33 +136,47 @@ public void testAddHeaders() { Request request = new Request(method, endpoint); try { - request.addHeaders((Header[]) null); - fail("expected failure"); - } catch (NullPointerException e) { - assertEquals("headers cannot be null", e.getMessage()); - } - - try { - request.addHeaders(new Header [] {null}); + request.addHeader(null); fail("expected failure"); } catch (NullPointerException e) { assertEquals("header cannot be null", e.getMessage()); } - List
headers = new ArrayList<>(between(0, 5)); - for (int i = 0; i < headers.size(); i++) { - BasicHeader header = new BasicHeader(randomAsciiAlphanumOfLength(3), randomAsciiAlphanumOfLength(3)); + int numHeaders = between(0, 5); + Set
headers = new HashSet<>(); + for (int i = 0; i < numHeaders; i++) { + BasicHeader header = new BasicHeader(randomAsciiAlphanumOfLengthBetween(5, 10), randomAsciiAlphanumOfLength(3)); headers.add(header); - request.addHeaders(header); + request.addHeader(header); + } + assertEquals(headers, new HashSet<>(request.getHeaders())); + } + + public void testDuplicatedHeaders() { + final String method = randomFrom(new String[] {"GET", "PUT", "POST", "HEAD", "DELETE"}); + final String endpoint = randomAsciiLettersOfLengthBetween(1, 10); + Request request = new Request(method, endpoint); + + int numHeaders = between(1, 3); + for (int i = 0; i < numHeaders; i++) { + request.addHeader(new BasicHeader(randomAsciiAlphanumOfLengthBetween(5, 10), randomAsciiAlphanumOfLength(3))); } - if (headers.size() > 0 && randomBoolean()) { - //check that duplicates are accepted at this stage - Header header = headers.get(randomIntBetween(0, headers.size() - 1)); - BasicHeader basicHeader = new BasicHeader(header.getName(), randomAsciiAlphanumOfLength(3)); - headers.add(basicHeader); - request.addHeaders(basicHeader); + + Header existingHeader = randomFrom(new ArrayList<>(request.getHeaders())); + String headerName = existingHeader.getName(); + if (randomBoolean()) { + headerName = headerName.toUpperCase(Locale.ROOT); + } else if (randomBoolean()) { + headerName = headerName.toLowerCase(Locale.ROOT); } - assertEquals(headers, request.getHeaders()); + try { + request.addHeader(new BasicHeader(headerName, randomAsciiAlphanumOfLength(3))); + fail("expected failure"); + } catch(IllegalArgumentException e) { + assertEquals("Unable to add header with name [" + headerName + "] conflicting header [" + + existingHeader + "] already present", e.getMessage()); + } + assertEquals(numHeaders, request.getHeaders().size()); } public void testEqualsAndHashCode() { @@ -202,7 +218,7 @@ private static Request randomRequest() { if (randomBoolean()) { int headerCount = between(1, 5); for (int i = 0; i < headerCount; i++) { - request.addHeaders(new BasicHeader(randomAsciiAlphanumOfLength(3), randomAsciiAlphanumOfLength(3))); + request.addHeader(new BasicHeader(randomAsciiAlphanumOfLength(3), randomAsciiAlphanumOfLength(3))); } } @@ -238,7 +254,7 @@ private static Request mutate(Request request) { mutant.setJsonEntity("mutant"); // randomRequest can't produce this value return mutant; case 2: - mutant.addHeaders(new BasicHeader("extra", "m")); + mutant.addHeader(new BasicHeader("extra", "m")); return mutant; case 3: mutant.setHttpAsyncResponseConsumerFactory(new HeapBufferedResponseConsumerFactory(5)); @@ -253,7 +269,9 @@ private static void copyMutables(Request from, Request to) { to.addParameter(param.getKey(), param.getValue()); } to.setEntity(from.getEntity()); - to.addHeaders(from.getHeaders().toArray(new Header[0])); + for (Header header : from.getHeaders()) { + to.addHeader(header); + } to.setHttpAsyncResponseConsumerFactory(from.getHttpAsyncResponseConsumerFactory()); } } diff --git a/client/rest/src/test/java/org/elasticsearch/client/RestClientSingleHostIntegTests.java b/client/rest/src/test/java/org/elasticsearch/client/RestClientSingleHostIntegTests.java index 667e38a5167d7..d08b435eee07b 100644 --- a/client/rest/src/test/java/org/elasticsearch/client/RestClientSingleHostIntegTests.java +++ b/client/rest/src/test/java/org/elasticsearch/client/RestClientSingleHostIntegTests.java @@ -29,16 +29,13 @@ import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.nio.client.HttpAsyncClientBuilder; import org.apache.http.nio.entity.NStringEntity; import org.apache.http.util.EntityUtils; import org.elasticsearch.mocksocket.MockHttpServer; import org.junit.After; -import org.junit.AfterClass; import org.junit.Before; -import org.junit.BeforeClass; import java.io.IOException; import java.io.InputStreamReader; diff --git a/client/rest/src/test/java/org/elasticsearch/client/RestClientSingleHostTests.java b/client/rest/src/test/java/org/elasticsearch/client/RestClientSingleHostTests.java index c0618c55af973..b4a9703630fdd 100644 --- a/client/rest/src/test/java/org/elasticsearch/client/RestClientSingleHostTests.java +++ b/client/rest/src/test/java/org/elasticsearch/client/RestClientSingleHostTests.java @@ -362,7 +362,9 @@ public void testHeaders() throws IOException { final Header[] requestHeaders = RestClientTestUtil.randomHeaders(getRandom(), "Header"); final int statusCode = randomStatusCode(getRandom()); Request request = new Request(method, "/" + statusCode); - request.addHeaders(requestHeaders); + for (Header requestHeader : requestHeaders) { + request.addHeader(requestHeader); + } Response esResponse; try { esResponse = restClient.performRequest(request); @@ -436,8 +438,8 @@ private HttpUriRequest performRandomRequest(String method) throws Exception { final Set uniqueNames = new HashSet<>(); if (randomBoolean()) { Header[] headers = RestClientTestUtil.randomHeaders(getRandom(), "Header"); - request.addHeaders(headers); for (Header header : headers) { + request.addHeader(header); expectedRequest.addHeader(header); uniqueNames.add(header.getName()); } diff --git a/client/rest/src/test/java/org/elasticsearch/client/documentation/RestClientDocumentation.java b/client/rest/src/test/java/org/elasticsearch/client/documentation/RestClientDocumentation.java index 9848614b2e081..69716cd7063c2 100644 --- a/client/rest/src/test/java/org/elasticsearch/client/documentation/RestClientDocumentation.java +++ b/client/rest/src/test/java/org/elasticsearch/client/documentation/RestClientDocumentation.java @@ -172,9 +172,8 @@ public void onFailure(Exception exception) { request.setJsonEntity("{\"json\":\"text\"}"); //end::rest-client-body-shorter //tag::rest-client-headers - request.addHeaders( - new BasicHeader("Accept", "text/plain"), - new BasicHeader("Cache-Control", "no-cache")); + request.addHeader(new BasicHeader("Accept", "text/plain")); + request.addHeader(new BasicHeader("Cache-Control", "no-cache")); //end::rest-client-headers //tag::rest-client-response-consumer request.setHttpAsyncResponseConsumerFactory( diff --git a/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/ESClientYamlSuiteTestCase.java b/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/ESClientYamlSuiteTestCase.java index 22814943cb3b1..466446edb711b 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/ESClientYamlSuiteTestCase.java +++ b/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/ESClientYamlSuiteTestCase.java @@ -333,7 +333,7 @@ public void test() throws IOException { if (useDefaultNumberOfShards == false && testCandidate.getTestSection().getSkipSection().getFeatures().contains("default_shards") == false) { final Request request = new Request("PUT", "/_template/global"); - request.addHeaders(new BasicHeader("Content-Type", XContentType.JSON.mediaTypeWithoutParameters())); + request.addHeader(new BasicHeader("Content-Type", XContentType.JSON.mediaTypeWithoutParameters())); request.setEntity(new StringEntity("{\"index_patterns\":[\"*\"],\"settings\":{\"index.number_of_shards\":2}}")); adminClient().performRequest(request); } diff --git a/x-pack/qa/sql/security/src/test/java/org/elasticsearch/xpack/qa/sql/security/RestSqlSecurityIT.java b/x-pack/qa/sql/security/src/test/java/org/elasticsearch/xpack/qa/sql/security/RestSqlSecurityIT.java index e91d8e4449feb..8f1743dfb3cb8 100644 --- a/x-pack/qa/sql/security/src/test/java/org/elasticsearch/xpack/qa/sql/security/RestSqlSecurityIT.java +++ b/x-pack/qa/sql/security/src/test/java/org/elasticsearch/xpack/qa/sql/security/RestSqlSecurityIT.java @@ -178,7 +178,7 @@ private static Map runSql(@Nullable String asUser, String mode, request.addParameter("mode", mode); } if (asUser != null) { - request.addHeaders(new BasicHeader("es-security-runas-user", asUser)); + request.addHeader(new BasicHeader("es-security-runas-user", asUser)); } request.setEntity(entity); return toMap(client().performRequest(request)); diff --git a/x-pack/qa/sql/src/main/java/org/elasticsearch/xpack/qa/sql/rest/RestSqlTestCase.java b/x-pack/qa/sql/src/main/java/org/elasticsearch/xpack/qa/sql/rest/RestSqlTestCase.java index 1e12ca3e4a570..a34a8d5e2c6c4 100644 --- a/x-pack/qa/sql/src/main/java/org/elasticsearch/xpack/qa/sql/rest/RestSqlTestCase.java +++ b/x-pack/qa/sql/src/main/java/org/elasticsearch/xpack/qa/sql/rest/RestSqlTestCase.java @@ -6,7 +6,6 @@ package org.elasticsearch.xpack.qa.sql.rest; import com.fasterxml.jackson.core.io.JsonStringEncoder; -import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; @@ -319,10 +318,9 @@ private Map runSql(String mode, HttpEntity sql, String suffix) t if (false == mode.isEmpty()) { request.addParameter("mode", mode); // JDBC or PLAIN mode } - request.addHeaders(randomFrom( - new Header[] {}, - new Header[] {new BasicHeader("Accept", "*/*")}, - new Header[] {new BasicHeader("Accpet", "application/json")})); + if (randomBoolean()) { + request.addHeader(randomFrom(new BasicHeader("Accept", "*/*"), new BasicHeader("Accpet", "application/json"))); + } request.setEntity(sql); Response response = client().performRequest(request); try (InputStream content = response.getEntity().getContent()) { @@ -534,7 +532,7 @@ private Tuple runSqlAsText(String suffix, HttpEntity entity, Str Request request = new Request("POST", "/_xpack/sql" + suffix); request.addParameter("error_trace", "true"); request.setEntity(entity); - request.addHeaders(new BasicHeader("Accept", accept)); + request.addHeader(new BasicHeader("Accept", accept)); Response response = client().performRequest(request); return new Tuple<>( Streams.copyToString(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8)), From f4116ad4ba5fbf3f59dcec18e5e25079610425ee Mon Sep 17 00:00:00 2001 From: javanna Date: Tue, 15 May 2018 14:00:00 +0200 Subject: [PATCH 05/13] fixes --- .../org/elasticsearch/client/RestClient.java | 6 ++-- .../elasticsearch/client/RequestTests.java | 29 +------------------ 2 files changed, 3 insertions(+), 32 deletions(-) diff --git a/client/rest/src/main/java/org/elasticsearch/client/RestClient.java b/client/rest/src/main/java/org/elasticsearch/client/RestClient.java index 1bcd4e72efa51..41b4cba5b19e7 100644 --- a/client/rest/src/main/java/org/elasticsearch/client/RestClient.java +++ b/client/rest/src/main/java/org/elasticsearch/client/RestClient.java @@ -215,9 +215,7 @@ public void performRequestAsync(Request request, ResponseListener responseListen @Deprecated public Response performRequest(String method, String endpoint, Header... headers) throws IOException { Request request = new Request(method, endpoint); - for (Header header : headers) { - request.addHeader(header); - } + addHeaders(request, headers); return performRequest(request); } @@ -880,7 +878,7 @@ private static class HostTuple { } /** - * Add all parameters from a map to a {@link Request}. This only exists + * Add all headers from the provided varargs argument to a {@link Request}. This only exists * to support methods that exist for backwards compatibility. */ @Deprecated diff --git a/client/rest/src/test/java/org/elasticsearch/client/RequestTests.java b/client/rest/src/test/java/org/elasticsearch/client/RequestTests.java index e89282f04d9eb..96dd5a7270a3f 100644 --- a/client/rest/src/test/java/org/elasticsearch/client/RequestTests.java +++ b/client/rest/src/test/java/org/elasticsearch/client/RequestTests.java @@ -151,34 +151,7 @@ public void testAddHeaders() { } assertEquals(headers, new HashSet<>(request.getHeaders())); } - - public void testDuplicatedHeaders() { - final String method = randomFrom(new String[] {"GET", "PUT", "POST", "HEAD", "DELETE"}); - final String endpoint = randomAsciiLettersOfLengthBetween(1, 10); - Request request = new Request(method, endpoint); - - int numHeaders = between(1, 3); - for (int i = 0; i < numHeaders; i++) { - request.addHeader(new BasicHeader(randomAsciiAlphanumOfLengthBetween(5, 10), randomAsciiAlphanumOfLength(3))); - } - - Header existingHeader = randomFrom(new ArrayList<>(request.getHeaders())); - String headerName = existingHeader.getName(); - if (randomBoolean()) { - headerName = headerName.toUpperCase(Locale.ROOT); - } else if (randomBoolean()) { - headerName = headerName.toLowerCase(Locale.ROOT); - } - try { - request.addHeader(new BasicHeader(headerName, randomAsciiAlphanumOfLength(3))); - fail("expected failure"); - } catch(IllegalArgumentException e) { - assertEquals("Unable to add header with name [" + headerName + "] conflicting header [" - + existingHeader + "] already present", e.getMessage()); - } - assertEquals(numHeaders, request.getHeaders().size()); - } - + public void testEqualsAndHashCode() { Request request = randomRequest(); assertEquals(request, request); From 5b91a565bf351a87f72f77ef5d24f71949ea9894 Mon Sep 17 00:00:00 2001 From: javanna Date: Tue, 15 May 2018 14:15:01 +0200 Subject: [PATCH 06/13] remove unused imports --- .../src/test/java/org/elasticsearch/client/RequestTests.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/client/rest/src/test/java/org/elasticsearch/client/RequestTests.java b/client/rest/src/test/java/org/elasticsearch/client/RequestTests.java index 96dd5a7270a3f..adb80527d353d 100644 --- a/client/rest/src/test/java/org/elasticsearch/client/RequestTests.java +++ b/client/rest/src/test/java/org/elasticsearch/client/RequestTests.java @@ -30,10 +30,8 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; -import java.util.Locale; import java.util.Map; import java.util.Set; @@ -151,7 +149,7 @@ public void testAddHeaders() { } assertEquals(headers, new HashSet<>(request.getHeaders())); } - + public void testEqualsAndHashCode() { Request request = randomRequest(); assertEquals(request, request); From c9a560ab217adf4cfa2bac29e369c6969a512a6a Mon Sep 17 00:00:00 2001 From: javanna Date: Tue, 15 May 2018 17:07:56 +0200 Subject: [PATCH 07/13] addHeader(String,String) --- .../client/RestHighLevelClient.java | 2 +- .../org/elasticsearch/client/Request.java | 10 ++++--- .../org/elasticsearch/client/RestClient.java | 2 +- .../elasticsearch/client/RequestTests.java | 27 ++++++++++++------- .../client/RestClientSingleHostTests.java | 4 +-- .../RestClientDocumentation.java | 4 +-- .../rest/yaml/ESClientYamlSuiteTestCase.java | 3 +-- .../qa/sql/security/RestSqlSecurityIT.java | 3 +-- .../xpack/qa/sql/rest/RestSqlTestCase.java | 5 ++-- 9 files changed, 33 insertions(+), 27 deletions(-) diff --git a/client/rest-high-level/src/main/java/org/elasticsearch/client/RestHighLevelClient.java b/client/rest-high-level/src/main/java/org/elasticsearch/client/RestHighLevelClient.java index 0841ab9b01a9c..010374f79a014 100644 --- a/client/rest-high-level/src/main/java/org/elasticsearch/client/RestHighLevelClient.java +++ b/client/rest-high-level/src/main/java/org/elasticsearch/client/RestHighLevelClient.java @@ -621,7 +621,7 @@ protected final void performRequestAsync(Req r private static void addHeaders(Request request, Header... headers) { Objects.requireNonNull(headers, "headers cannot be null"); for (Header header : headers) { - request.addHeader(header); + request.addHeader(header.getName(), header.getValue()); } } diff --git a/client/rest/src/main/java/org/elasticsearch/client/Request.java b/client/rest/src/main/java/org/elasticsearch/client/Request.java index 93be5b62a0509..9c480c6a1910f 100644 --- a/client/rest/src/main/java/org/elasticsearch/client/Request.java +++ b/client/rest/src/main/java/org/elasticsearch/client/Request.java @@ -22,6 +22,7 @@ import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.entity.ContentType; +import org.apache.http.message.BasicHeader; import org.apache.http.nio.entity.NStringEntity; import org.apache.http.nio.protocol.HttpAsyncResponseConsumer; @@ -128,15 +129,16 @@ public HttpEntity getEntity() { /** * Add the provided header to the request. */ - public void addHeader(Header header) { - Objects.requireNonNull(header, "header cannot be null"); - this.headers.add(header); + public void addHeader(String name, String value) { + Objects.requireNonNull(name, "header name cannot be null"); + Objects.requireNonNull(value, "header value cannot be null"); + this.headers.add(new BasicHeader(name, value)); } /** * Headers to attach to the request. */ - public List
getHeaders() { + List
getHeaders() { return Collections.unmodifiableList(headers); } diff --git a/client/rest/src/main/java/org/elasticsearch/client/RestClient.java b/client/rest/src/main/java/org/elasticsearch/client/RestClient.java index 41b4cba5b19e7..a04dfdb5e17bd 100644 --- a/client/rest/src/main/java/org/elasticsearch/client/RestClient.java +++ b/client/rest/src/main/java/org/elasticsearch/client/RestClient.java @@ -885,7 +885,7 @@ private static class HostTuple { private static void addHeaders(Request request, Header... headers) { Objects.requireNonNull(headers, "headers cannot be null"); for (Header header : headers) { - request.addHeader(header); + request.addHeader(header.getName(), header.getValue()); } } diff --git a/client/rest/src/test/java/org/elasticsearch/client/RequestTests.java b/client/rest/src/test/java/org/elasticsearch/client/RequestTests.java index adb80527d353d..fa041ed2f7c62 100644 --- a/client/rest/src/test/java/org/elasticsearch/client/RequestTests.java +++ b/client/rest/src/test/java/org/elasticsearch/client/RequestTests.java @@ -30,10 +30,10 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.util.ArrayList; import java.util.HashMap; -import java.util.HashSet; +import java.util.List; import java.util.Map; -import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; @@ -134,20 +134,27 @@ public void testAddHeaders() { Request request = new Request(method, endpoint); try { - request.addHeader(null); + request.addHeader(null, randomAsciiLettersOfLengthBetween(3, 10)); fail("expected failure"); } catch (NullPointerException e) { - assertEquals("header cannot be null", e.getMessage()); + assertEquals("header name cannot be null", e.getMessage()); + } + + try { + request.addHeader(randomAsciiLettersOfLengthBetween(3, 10), null); + fail("expected failure"); + } catch (NullPointerException e) { + assertEquals("header value cannot be null", e.getMessage()); } int numHeaders = between(0, 5); - Set
headers = new HashSet<>(); + List
headers = new ArrayList<>(); for (int i = 0; i < numHeaders; i++) { BasicHeader header = new BasicHeader(randomAsciiAlphanumOfLengthBetween(5, 10), randomAsciiAlphanumOfLength(3)); headers.add(header); - request.addHeader(header); + request.addHeader(header.getName(), header.getValue()); } - assertEquals(headers, new HashSet<>(request.getHeaders())); + assertEquals(headers, request.getHeaders()); } public void testEqualsAndHashCode() { @@ -189,7 +196,7 @@ private static Request randomRequest() { if (randomBoolean()) { int headerCount = between(1, 5); for (int i = 0; i < headerCount; i++) { - request.addHeader(new BasicHeader(randomAsciiAlphanumOfLength(3), randomAsciiAlphanumOfLength(3))); + request.addHeader(randomAsciiAlphanumOfLength(3), randomAsciiAlphanumOfLength(3)); } } @@ -225,7 +232,7 @@ private static Request mutate(Request request) { mutant.setJsonEntity("mutant"); // randomRequest can't produce this value return mutant; case 2: - mutant.addHeader(new BasicHeader("extra", "m")); + mutant.addHeader("extra", "m"); return mutant; case 3: mutant.setHttpAsyncResponseConsumerFactory(new HeapBufferedResponseConsumerFactory(5)); @@ -241,7 +248,7 @@ private static void copyMutables(Request from, Request to) { } to.setEntity(from.getEntity()); for (Header header : from.getHeaders()) { - to.addHeader(header); + to.addHeader(header.getName(), header.getValue()); } to.setHttpAsyncResponseConsumerFactory(from.getHttpAsyncResponseConsumerFactory()); } diff --git a/client/rest/src/test/java/org/elasticsearch/client/RestClientSingleHostTests.java b/client/rest/src/test/java/org/elasticsearch/client/RestClientSingleHostTests.java index b4a9703630fdd..9c920f32032cb 100644 --- a/client/rest/src/test/java/org/elasticsearch/client/RestClientSingleHostTests.java +++ b/client/rest/src/test/java/org/elasticsearch/client/RestClientSingleHostTests.java @@ -363,7 +363,7 @@ public void testHeaders() throws IOException { final int statusCode = randomStatusCode(getRandom()); Request request = new Request(method, "/" + statusCode); for (Header requestHeader : requestHeaders) { - request.addHeader(requestHeader); + request.addHeader(requestHeader.getName(), requestHeader.getValue()); } Response esResponse; try { @@ -439,7 +439,7 @@ private HttpUriRequest performRandomRequest(String method) throws Exception { if (randomBoolean()) { Header[] headers = RestClientTestUtil.randomHeaders(getRandom(), "Header"); for (Header header : headers) { - request.addHeader(header); + request.addHeader(header.getName(), header.getValue()); expectedRequest.addHeader(header); uniqueNames.add(header.getName()); } diff --git a/client/rest/src/test/java/org/elasticsearch/client/documentation/RestClientDocumentation.java b/client/rest/src/test/java/org/elasticsearch/client/documentation/RestClientDocumentation.java index 69716cd7063c2..f3ce112fea1a1 100644 --- a/client/rest/src/test/java/org/elasticsearch/client/documentation/RestClientDocumentation.java +++ b/client/rest/src/test/java/org/elasticsearch/client/documentation/RestClientDocumentation.java @@ -172,8 +172,8 @@ public void onFailure(Exception exception) { request.setJsonEntity("{\"json\":\"text\"}"); //end::rest-client-body-shorter //tag::rest-client-headers - request.addHeader(new BasicHeader("Accept", "text/plain")); - request.addHeader(new BasicHeader("Cache-Control", "no-cache")); + request.addHeader("Accept", "text/plain"); + request.addHeader("Cache-Control", "no-cache"); //end::rest-client-headers //tag::rest-client-response-consumer request.setHttpAsyncResponseConsumerFactory( diff --git a/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/ESClientYamlSuiteTestCase.java b/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/ESClientYamlSuiteTestCase.java index 466446edb711b..27f26aa657af1 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/ESClientYamlSuiteTestCase.java +++ b/test/framework/src/main/java/org/elasticsearch/test/rest/yaml/ESClientYamlSuiteTestCase.java @@ -22,7 +22,6 @@ import com.carrotsearch.randomizedtesting.RandomizedTest; import org.apache.http.HttpHost; import org.apache.http.entity.StringEntity; -import org.apache.http.message.BasicHeader; import org.elasticsearch.Version; import org.elasticsearch.client.Request; import org.elasticsearch.client.Response; @@ -333,7 +332,7 @@ public void test() throws IOException { if (useDefaultNumberOfShards == false && testCandidate.getTestSection().getSkipSection().getFeatures().contains("default_shards") == false) { final Request request = new Request("PUT", "/_template/global"); - request.addHeader(new BasicHeader("Content-Type", XContentType.JSON.mediaTypeWithoutParameters())); + request.addHeader("Content-Type", XContentType.JSON.mediaTypeWithoutParameters()); request.setEntity(new StringEntity("{\"index_patterns\":[\"*\"],\"settings\":{\"index.number_of_shards\":2}}")); adminClient().performRequest(request); } diff --git a/x-pack/qa/sql/security/src/test/java/org/elasticsearch/xpack/qa/sql/security/RestSqlSecurityIT.java b/x-pack/qa/sql/security/src/test/java/org/elasticsearch/xpack/qa/sql/security/RestSqlSecurityIT.java index 8f1743dfb3cb8..bdbb75491ca87 100644 --- a/x-pack/qa/sql/security/src/test/java/org/elasticsearch/xpack/qa/sql/security/RestSqlSecurityIT.java +++ b/x-pack/qa/sql/security/src/test/java/org/elasticsearch/xpack/qa/sql/security/RestSqlSecurityIT.java @@ -8,7 +8,6 @@ import org.apache.http.HttpEntity; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; -import org.apache.http.message.BasicHeader; import org.elasticsearch.client.Request; import org.elasticsearch.client.Response; import org.elasticsearch.client.ResponseException; @@ -178,7 +177,7 @@ private static Map runSql(@Nullable String asUser, String mode, request.addParameter("mode", mode); } if (asUser != null) { - request.addHeader(new BasicHeader("es-security-runas-user", asUser)); + request.addHeader("es-security-runas-user", asUser); } request.setEntity(entity); return toMap(client().performRequest(request)); diff --git a/x-pack/qa/sql/src/main/java/org/elasticsearch/xpack/qa/sql/rest/RestSqlTestCase.java b/x-pack/qa/sql/src/main/java/org/elasticsearch/xpack/qa/sql/rest/RestSqlTestCase.java index a34a8d5e2c6c4..b694e253d0b16 100644 --- a/x-pack/qa/sql/src/main/java/org/elasticsearch/xpack/qa/sql/rest/RestSqlTestCase.java +++ b/x-pack/qa/sql/src/main/java/org/elasticsearch/xpack/qa/sql/rest/RestSqlTestCase.java @@ -9,7 +9,6 @@ import org.apache.http.HttpEntity; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; -import org.apache.http.message.BasicHeader; import org.elasticsearch.client.Request; import org.elasticsearch.client.Response; import org.elasticsearch.client.ResponseException; @@ -319,7 +318,7 @@ private Map runSql(String mode, HttpEntity sql, String suffix) t request.addParameter("mode", mode); // JDBC or PLAIN mode } if (randomBoolean()) { - request.addHeader(randomFrom(new BasicHeader("Accept", "*/*"), new BasicHeader("Accpet", "application/json"))); + request.addHeader("Accept", randomFrom("*/*", "application/json")); } request.setEntity(sql); Response response = client().performRequest(request); @@ -532,7 +531,7 @@ private Tuple runSqlAsText(String suffix, HttpEntity entity, Str Request request = new Request("POST", "/_xpack/sql" + suffix); request.addParameter("error_trace", "true"); request.setEntity(entity); - request.addHeader(new BasicHeader("Accept", accept)); + request.addHeader("Accept", accept); Response response = client().performRequest(request); return new Tuple<>( Streams.copyToString(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8)), From 6e456e9749fd0f74c5481890a2d0808fa279aeb0 Mon Sep 17 00:00:00 2001 From: javanna Date: Tue, 15 May 2018 18:08:10 +0200 Subject: [PATCH 08/13] fix tests --- .../org/elasticsearch/client/Request.java | 29 +++++++++++++++++-- .../org/elasticsearch/client/RestClient.java | 1 + .../elasticsearch/client/RequestTests.java | 5 ++-- .../client/RestClientSingleHostTests.java | 2 +- .../client/RestClientTestUtil.java | 2 +- 5 files changed, 32 insertions(+), 7 deletions(-) diff --git a/client/rest/src/main/java/org/elasticsearch/client/Request.java b/client/rest/src/main/java/org/elasticsearch/client/Request.java index 9c480c6a1910f..69d838022e41a 100644 --- a/client/rest/src/main/java/org/elasticsearch/client/Request.java +++ b/client/rest/src/main/java/org/elasticsearch/client/Request.java @@ -132,7 +132,7 @@ public HttpEntity getEntity() { public void addHeader(String name, String value) { Objects.requireNonNull(name, "header name cannot be null"); Objects.requireNonNull(value, "header value cannot be null"); - this.headers.add(new BasicHeader(name, value)); + this.headers.add(new ReqHeader(name, value)); } /** @@ -210,6 +210,31 @@ public boolean equals(Object obj) { @Override public int hashCode() { - return Objects.hash(method, endpoint, parameters, entity, headers, httpAsyncResponseConsumerFactory); + return Objects.hash(method, endpoint, parameters, entity, headers.hashCode(), httpAsyncResponseConsumerFactory); + } + + static final class ReqHeader extends BasicHeader { + + ReqHeader(String name, String value) { + super(name, value); + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (other instanceof ReqHeader) { + Header otherHeader = (Header) other; + return Objects.equals(getName(), otherHeader.getName()) && + Objects.equals(getValue(), otherHeader.getValue()); + } + return false; + } + + @Override + public int hashCode() { + return Objects.hash(getName(), getValue()); + } } } diff --git a/client/rest/src/main/java/org/elasticsearch/client/RestClient.java b/client/rest/src/main/java/org/elasticsearch/client/RestClient.java index a04dfdb5e17bd..33171e18e743d 100644 --- a/client/rest/src/main/java/org/elasticsearch/client/RestClient.java +++ b/client/rest/src/main/java/org/elasticsearch/client/RestClient.java @@ -885,6 +885,7 @@ private static class HostTuple { private static void addHeaders(Request request, Header... headers) { Objects.requireNonNull(headers, "headers cannot be null"); for (Header header : headers) { + Objects.requireNonNull(header, "header cannot be null"); request.addHeader(header.getName(), header.getValue()); } } diff --git a/client/rest/src/test/java/org/elasticsearch/client/RequestTests.java b/client/rest/src/test/java/org/elasticsearch/client/RequestTests.java index fa041ed2f7c62..33df2ac00ae6b 100644 --- a/client/rest/src/test/java/org/elasticsearch/client/RequestTests.java +++ b/client/rest/src/test/java/org/elasticsearch/client/RequestTests.java @@ -24,7 +24,6 @@ import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; -import org.apache.http.message.BasicHeader; import org.apache.http.nio.entity.NStringEntity; import org.elasticsearch.client.HttpAsyncResponseConsumerFactory.HeapBufferedResponseConsumerFactory; @@ -150,11 +149,11 @@ public void testAddHeaders() { int numHeaders = between(0, 5); List
headers = new ArrayList<>(); for (int i = 0; i < numHeaders; i++) { - BasicHeader header = new BasicHeader(randomAsciiAlphanumOfLengthBetween(5, 10), randomAsciiAlphanumOfLength(3)); + Header header = new Request.ReqHeader(randomAsciiAlphanumOfLengthBetween(5, 10), randomAsciiAlphanumOfLength(3)); headers.add(header); request.addHeader(header.getName(), header.getValue()); } - assertEquals(headers, request.getHeaders()); + assertEquals(headers, new ArrayList<>(request.getHeaders())); } public void testEqualsAndHashCode() { diff --git a/client/rest/src/test/java/org/elasticsearch/client/RestClientSingleHostTests.java b/client/rest/src/test/java/org/elasticsearch/client/RestClientSingleHostTests.java index 9c920f32032cb..3811b60023b43 100644 --- a/client/rest/src/test/java/org/elasticsearch/client/RestClientSingleHostTests.java +++ b/client/rest/src/test/java/org/elasticsearch/client/RestClientSingleHostTests.java @@ -440,7 +440,7 @@ private HttpUriRequest performRandomRequest(String method) throws Exception { Header[] headers = RestClientTestUtil.randomHeaders(getRandom(), "Header"); for (Header header : headers) { request.addHeader(header.getName(), header.getValue()); - expectedRequest.addHeader(header); + expectedRequest.addHeader(new Request.ReqHeader(header.getName(), header.getValue())); uniqueNames.add(header.getName()); } } diff --git a/client/test/src/main/java/org/elasticsearch/client/RestClientTestUtil.java b/client/test/src/main/java/org/elasticsearch/client/RestClientTestUtil.java index a0a6641abbc5f..07bae6c17fdd2 100644 --- a/client/test/src/main/java/org/elasticsearch/client/RestClientTestUtil.java +++ b/client/test/src/main/java/org/elasticsearch/client/RestClientTestUtil.java @@ -100,7 +100,7 @@ static Header[] randomHeaders(Random random, final String baseName) { if (random.nextBoolean()) { headerName = headerName + i; } - headers[i] = new BasicHeader(headerName, RandomStrings.randomAsciiOfLengthBetween(random, 3, 10)); + headers[i] = new BasicHeader(headerName, RandomStrings.randomAsciiLettersOfLengthBetween(random, 3, 10)); } return headers; } From e3c74c28c0b10e49dff70fc2c0655d6ceeab5431 Mon Sep 17 00:00:00 2001 From: javanna Date: Tue, 15 May 2018 18:13:11 +0200 Subject: [PATCH 09/13] rename test method --- .../src/test/java/org/elasticsearch/client/RequestTests.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/rest/src/test/java/org/elasticsearch/client/RequestTests.java b/client/rest/src/test/java/org/elasticsearch/client/RequestTests.java index 33df2ac00ae6b..29bbf23a1f20e 100644 --- a/client/rest/src/test/java/org/elasticsearch/client/RequestTests.java +++ b/client/rest/src/test/java/org/elasticsearch/client/RequestTests.java @@ -127,7 +127,7 @@ public void testSetJsonEntity() throws IOException { assertEquals(json, new String(os.toByteArray(), ContentType.APPLICATION_JSON.getCharset())); } - public void testAddHeaders() { + public void testAddHeader() { final String method = randomFrom(new String[] {"GET", "PUT", "POST", "HEAD", "DELETE"}); final String endpoint = randomAsciiLettersOfLengthBetween(1, 10); Request request = new Request(method, endpoint); From a2721b558086e22eaa9705ae0121f9ed2436192c Mon Sep 17 00:00:00 2001 From: javanna Date: Tue, 22 May 2018 12:12:12 +0200 Subject: [PATCH 10/13] add javadocs for ReqHeader --- .../rest/src/main/java/org/elasticsearch/client/Request.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/client/rest/src/main/java/org/elasticsearch/client/Request.java b/client/rest/src/main/java/org/elasticsearch/client/Request.java index 69d838022e41a..59b82e5bf9649 100644 --- a/client/rest/src/main/java/org/elasticsearch/client/Request.java +++ b/client/rest/src/main/java/org/elasticsearch/client/Request.java @@ -213,6 +213,9 @@ public int hashCode() { return Objects.hash(method, endpoint, parameters, entity, headers.hashCode(), httpAsyncResponseConsumerFactory); } + /** + * Custom implementation of {@link BasicHeader} that overrides equals and hashCode. + */ static final class ReqHeader extends BasicHeader { ReqHeader(String name, String value) { From ed19946cf74560e9e55119d8492bcfbcf53b3e12 Mon Sep 17 00:00:00 2001 From: javanna Date: Tue, 22 May 2018 12:18:28 +0200 Subject: [PATCH 11/13] fix compile error --- .../elasticsearch/client/RestClientSingleHostIntegTests.java | 4 +++- .../test/java/org/elasticsearch/client/RestClientTests.java | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/client/rest/src/test/java/org/elasticsearch/client/RestClientSingleHostIntegTests.java b/client/rest/src/test/java/org/elasticsearch/client/RestClientSingleHostIntegTests.java index 1b6872010eb94..a3d0196dab9a8 100644 --- a/client/rest/src/test/java/org/elasticsearch/client/RestClientSingleHostIntegTests.java +++ b/client/rest/src/test/java/org/elasticsearch/client/RestClientSingleHostIntegTests.java @@ -378,7 +378,9 @@ private Response bodyTest(RestClient restClient, String method, int statusCode, String requestBody = "{ \"field\": \"value\" }"; Request request = new Request(method, "/" + statusCode); request.setJsonEntity(requestBody); - request.setHeaders(headers); + for (Header header : headers) { + request.addHeader(header.getName(), header.getValue()); + } Response esResponse; try { esResponse = restClient.performRequest(request); diff --git a/client/rest/src/test/java/org/elasticsearch/client/RestClientTests.java b/client/rest/src/test/java/org/elasticsearch/client/RestClientTests.java index 84399c1e6e1c9..dd751c48c9383 100644 --- a/client/rest/src/test/java/org/elasticsearch/client/RestClientTests.java +++ b/client/rest/src/test/java/org/elasticsearch/client/RestClientTests.java @@ -120,7 +120,7 @@ public void onFailure(Exception exception) { } /** - * @deprecated will remove method in 7.0 but needs tests until then. Replaced by {@link RequestTests#testAddHeaders()}. + * @deprecated will remove method in 7.0 but needs tests until then. Replaced by {@link RequestTests#testAddHeader()}. */ @Deprecated public void testPerformOldStyleAsyncWithNullHeaders() throws Exception { From 61e4361a720f38a1a09f660a6ba6534abda273de Mon Sep 17 00:00:00 2001 From: javanna Date: Tue, 22 May 2018 14:27:21 +0200 Subject: [PATCH 12/13] fix compile errors --- .../http/ContextAndHeaderTransportIT.java | 5 ++- .../org/elasticsearch/http/CorsNotSetIT.java | 4 +-- .../org/elasticsearch/http/CorsRegexIT.java | 35 +++++++++---------- .../elasticsearch/http/HttpCompressionIT.java | 3 +- .../org/elasticsearch/http/NoHandlerIT.java | 3 +- .../http/ResponseHeaderPluginIT.java | 5 ++- 6 files changed, 25 insertions(+), 30 deletions(-) diff --git a/qa/smoke-test-http/src/test/java/org/elasticsearch/http/ContextAndHeaderTransportIT.java b/qa/smoke-test-http/src/test/java/org/elasticsearch/http/ContextAndHeaderTransportIT.java index bfa856e381b12..99132f0c89d5b 100644 --- a/qa/smoke-test-http/src/test/java/org/elasticsearch/http/ContextAndHeaderTransportIT.java +++ b/qa/smoke-test-http/src/test/java/org/elasticsearch/http/ContextAndHeaderTransportIT.java @@ -19,7 +19,6 @@ package org.elasticsearch.http; -import org.apache.http.message.BasicHeader; import org.apache.lucene.util.SetOnce; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.ActionRequest; @@ -222,8 +221,8 @@ public void testThatMoreLikeThisQueryMultiTermVectorRequestContainsContextAndHea public void testThatRelevantHttpHeadersBecomeRequestHeaders() throws IOException { final String IRRELEVANT_HEADER = "SomeIrrelevantHeader"; Request request = new Request("GET", "/" + queryIndex + "/_search"); - request.setHeaders(new BasicHeader(CUSTOM_HEADER, randomHeaderValue), - new BasicHeader(IRRELEVANT_HEADER, randomHeaderValue)); + request.addHeader(CUSTOM_HEADER, randomHeaderValue); + request.addHeader(IRRELEVANT_HEADER, randomHeaderValue); Response response = getRestClient().performRequest(request); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); List searchRequests = getRequests(SearchRequest.class); diff --git a/qa/smoke-test-http/src/test/java/org/elasticsearch/http/CorsNotSetIT.java b/qa/smoke-test-http/src/test/java/org/elasticsearch/http/CorsNotSetIT.java index 4ab64abda453b..2d139e7955ea9 100644 --- a/qa/smoke-test-http/src/test/java/org/elasticsearch/http/CorsNotSetIT.java +++ b/qa/smoke-test-http/src/test/java/org/elasticsearch/http/CorsNotSetIT.java @@ -19,7 +19,6 @@ package org.elasticsearch.http; -import org.apache.http.message.BasicHeader; import org.elasticsearch.client.Request; import org.elasticsearch.client.Response; @@ -33,7 +32,8 @@ public class CorsNotSetIT extends HttpSmokeTestCase { public void testCorsSettingDefaultBehaviourDoesNotReturnAnything() throws IOException { String corsValue = "http://localhost:9200"; Request request = new Request("GET", "/"); - request.setHeaders(new BasicHeader("User-Agent", "Mozilla Bar"), new BasicHeader("Origin", corsValue)); + request.addHeader("User-Agent", "Mozilla Bar"); + request.addHeader("Origin", corsValue); Response response = getRestClient().performRequest(request); assertThat(response.getStatusLine().getStatusCode(), is(200)); assertThat(response.getHeader("Access-Control-Allow-Origin"), nullValue()); diff --git a/qa/smoke-test-http/src/test/java/org/elasticsearch/http/CorsRegexIT.java b/qa/smoke-test-http/src/test/java/org/elasticsearch/http/CorsRegexIT.java index da48e51b63bbe..42ddb6dfe7d1a 100644 --- a/qa/smoke-test-http/src/test/java/org/elasticsearch/http/CorsRegexIT.java +++ b/qa/smoke-test-http/src/test/java/org/elasticsearch/http/CorsRegexIT.java @@ -18,7 +18,6 @@ */ package org.elasticsearch.http; -import org.apache.http.message.BasicHeader; import org.elasticsearch.client.Request; import org.elasticsearch.client.Response; import org.elasticsearch.client.ResponseException; @@ -55,23 +54,23 @@ protected Settings nodeSettings(int nodeOrdinal) { public void testThatRegularExpressionWorksOnMatch() throws IOException { String corsValue = "http://localhost:9200"; Request request = new Request("GET", "/"); - request.setHeaders(new BasicHeader("User-Agent", "Mozilla Bar"), - new BasicHeader("Origin", corsValue)); + request.addHeader("User-Agent", "Mozilla Bar"); + request.addHeader("Origin", corsValue); Response response = getRestClient().performRequest(request); - assertResponseWithOriginheader(response, corsValue); + assertResponseWithOriginHeader(response, corsValue); corsValue = "https://localhost:9201"; - request.setHeaders(new BasicHeader("User-Agent", "Mozilla Bar"), - new BasicHeader("Origin", corsValue)); + request.addHeader("User-Agent", "Mozilla Bar"); + request.addHeader("Origin", corsValue); response = getRestClient().performRequest(request); - assertResponseWithOriginheader(response, corsValue); + assertResponseWithOriginHeader(response, corsValue); assertThat(response.getHeader("Access-Control-Allow-Credentials"), is("true")); } public void testThatRegularExpressionReturnsForbiddenOnNonMatch() throws IOException { Request request = new Request("GET", "/"); - request.setHeaders(new BasicHeader("User-Agent", "Mozilla Bar"), - new BasicHeader("Origin", "http://evil-host:9200")); + request.addHeader("User-Agent", "Mozilla Bar"); + request.addHeader("Origin", "http://evil-host:9200"); try { getRestClient().performRequest(request); fail("request should have failed"); @@ -85,7 +84,7 @@ public void testThatRegularExpressionReturnsForbiddenOnNonMatch() throws IOExcep public void testThatSendingNoOriginHeaderReturnsNoAccessControlHeader() throws IOException { Request request = new Request("GET", "/"); - request.setHeaders(new BasicHeader("User-Agent", "Mozilla Bar")); + request.addHeader("User-Agent", "Mozilla Bar"); Response response = getRestClient().performRequest(request); assertThat(response.getStatusLine().getStatusCode(), is(200)); assertThat(response.getHeader("Access-Control-Allow-Origin"), nullValue()); @@ -100,20 +99,20 @@ public void testThatRegularExpressionIsNotAppliedWithoutCorrectBrowserOnMatch() public void testThatPreFlightRequestWorksOnMatch() throws IOException { String corsValue = "http://localhost:9200"; Request request = new Request("OPTIONS", "/"); - request.setHeaders(new BasicHeader("User-Agent", "Mozilla Bar"), - new BasicHeader("Origin", corsValue), - new BasicHeader("Access-Control-Request-Method", "GET")); + request.addHeader("User-Agent", "Mozilla Bar"); + request.addHeader("Origin", corsValue); + request.addHeader("Access-Control-Request-Method", "GET"); Response response = getRestClient().performRequest(request); - assertResponseWithOriginheader(response, corsValue); + assertResponseWithOriginHeader(response, corsValue); assertNotNull(response.getHeader("Access-Control-Allow-Methods")); } public void testThatPreFlightRequestReturnsNullOnNonMatch() throws IOException { String corsValue = "http://evil-host:9200"; Request request = new Request("OPTIONS", "/"); - request.setHeaders(new BasicHeader("User-Agent", "Mozilla Bar"), - new BasicHeader("Origin", corsValue), - new BasicHeader("Access-Control-Request-Method", "GET")); + request.addHeader("User-Agent", "Mozilla Bar"); + request.addHeader("Origin", corsValue); + request.addHeader("Access-Control-Request-Method", "GET"); try { getRestClient().performRequest(request); fail("request should have failed"); @@ -126,7 +125,7 @@ public void testThatPreFlightRequestReturnsNullOnNonMatch() throws IOException { } } - protected static void assertResponseWithOriginheader(Response response, String expectedCorsHeader) { + private static void assertResponseWithOriginHeader(Response response, String expectedCorsHeader) { assertThat(response.getStatusLine().getStatusCode(), is(200)); assertThat(response.getHeader("Access-Control-Allow-Origin"), is(expectedCorsHeader)); } diff --git a/qa/smoke-test-http/src/test/java/org/elasticsearch/http/HttpCompressionIT.java b/qa/smoke-test-http/src/test/java/org/elasticsearch/http/HttpCompressionIT.java index 6af08577393d9..a9a0a0c7ed945 100644 --- a/qa/smoke-test-http/src/test/java/org/elasticsearch/http/HttpCompressionIT.java +++ b/qa/smoke-test-http/src/test/java/org/elasticsearch/http/HttpCompressionIT.java @@ -19,7 +19,6 @@ package org.elasticsearch.http; import org.apache.http.HttpHeaders; -import org.apache.http.message.BasicHeader; import org.elasticsearch.client.Request; import org.elasticsearch.client.Response; import org.elasticsearch.test.rest.ESRestTestCase; @@ -39,7 +38,7 @@ public class HttpCompressionIT extends ESRestTestCase { public void testCompressesResponseIfRequested() throws IOException { Request request = new Request("GET", "/"); - request.setHeaders(new BasicHeader(HttpHeaders.ACCEPT_ENCODING, GZIP_ENCODING)); + request.addHeader(HttpHeaders.ACCEPT_ENCODING, GZIP_ENCODING); Response response = client().performRequest(request); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals(GZIP_ENCODING, response.getHeader(HttpHeaders.CONTENT_ENCODING)); diff --git a/qa/smoke-test-http/src/test/java/org/elasticsearch/http/NoHandlerIT.java b/qa/smoke-test-http/src/test/java/org/elasticsearch/http/NoHandlerIT.java index e1d55afea1b54..976ba3131151f 100644 --- a/qa/smoke-test-http/src/test/java/org/elasticsearch/http/NoHandlerIT.java +++ b/qa/smoke-test-http/src/test/java/org/elasticsearch/http/NoHandlerIT.java @@ -19,7 +19,6 @@ package org.elasticsearch.http; -import org.apache.http.message.BasicHeader; import org.apache.http.util.EntityUtils; import org.elasticsearch.client.Request; import org.elasticsearch.client.Response; @@ -47,7 +46,7 @@ public void testNoHandlerRespectsAcceptHeader() throws IOException { private void runTestNoHandlerRespectsAcceptHeader( final String accept, final String contentType, final String expect) throws IOException { Request request = new Request("GET", "/foo/bar/baz/qux/quux"); - request.setHeaders(new BasicHeader("Accept", accept)); + request.addHeader("Accept", accept); final ResponseException e = expectThrows(ResponseException.class, () -> getRestClient().performRequest(request)); diff --git a/qa/smoke-test-http/src/test/java/org/elasticsearch/http/ResponseHeaderPluginIT.java b/qa/smoke-test-http/src/test/java/org/elasticsearch/http/ResponseHeaderPluginIT.java index b4dbc50d52db7..ac2503f2c525c 100644 --- a/qa/smoke-test-http/src/test/java/org/elasticsearch/http/ResponseHeaderPluginIT.java +++ b/qa/smoke-test-http/src/test/java/org/elasticsearch/http/ResponseHeaderPluginIT.java @@ -18,7 +18,6 @@ */ package org.elasticsearch.http; -import org.apache.http.message.BasicHeader; import org.elasticsearch.client.Request; import org.elasticsearch.client.Response; import org.elasticsearch.client.ResponseException; @@ -26,8 +25,8 @@ import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.test.ESIntegTestCase.Scope; -import java.util.ArrayList; import java.io.IOException; +import java.util.ArrayList; import java.util.Collection; import static org.hamcrest.Matchers.equalTo; @@ -62,7 +61,7 @@ public void testThatSettingHeadersWorks() throws IOException { } Request request = new Request("GET", "/_protected"); - request.setHeaders(new BasicHeader("Secret", "password")); + request.addHeader("Secret", "password"); Response authResponse = getRestClient().performRequest(request); assertThat(authResponse.getStatusLine().getStatusCode(), equalTo(200)); assertThat(authResponse.getHeader("Secret"), equalTo("granted")); From 08e1d41baeea364f3d4780493582d8edfee4baef Mon Sep 17 00:00:00 2001 From: javanna Date: Tue, 22 May 2018 16:39:52 +0200 Subject: [PATCH 13/13] fix failing test --- .../org/elasticsearch/http/CorsRegexIT.java | 30 +++++++++++-------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/qa/smoke-test-http/src/test/java/org/elasticsearch/http/CorsRegexIT.java b/qa/smoke-test-http/src/test/java/org/elasticsearch/http/CorsRegexIT.java index 42ddb6dfe7d1a..e79e80315501b 100644 --- a/qa/smoke-test-http/src/test/java/org/elasticsearch/http/CorsRegexIT.java +++ b/qa/smoke-test-http/src/test/java/org/elasticsearch/http/CorsRegexIT.java @@ -52,19 +52,23 @@ protected Settings nodeSettings(int nodeOrdinal) { } public void testThatRegularExpressionWorksOnMatch() throws IOException { - String corsValue = "http://localhost:9200"; - Request request = new Request("GET", "/"); - request.addHeader("User-Agent", "Mozilla Bar"); - request.addHeader("Origin", corsValue); - Response response = getRestClient().performRequest(request); - assertResponseWithOriginHeader(response, corsValue); - - corsValue = "https://localhost:9201"; - request.addHeader("User-Agent", "Mozilla Bar"); - request.addHeader("Origin", corsValue); - response = getRestClient().performRequest(request); - assertResponseWithOriginHeader(response, corsValue); - assertThat(response.getHeader("Access-Control-Allow-Credentials"), is("true")); + { + String corsValue = "http://localhost:9200"; + Request request = new Request("GET", "/"); + request.addHeader("User-Agent", "Mozilla Bar"); + request.addHeader("Origin", corsValue); + Response response = getRestClient().performRequest(request); + assertResponseWithOriginHeader(response, corsValue); + } + { + String corsValue = "https://localhost:9201"; + Request request = new Request("GET", "/"); + request.addHeader("User-Agent", "Mozilla Bar"); + request.addHeader("Origin", corsValue); + Response response = getRestClient().performRequest(request); + assertResponseWithOriginHeader(response, corsValue); + assertThat(response.getHeader("Access-Control-Allow-Credentials"), is("true")); + } } public void testThatRegularExpressionReturnsForbiddenOnNonMatch() throws IOException {