diff options
14 files changed, 242 insertions, 209 deletions
diff --git a/buildSrc/src/main/resources/checkstyle_suppressions.xml b/buildSrc/src/main/resources/checkstyle_suppressions.xml index c77ef0f9d5..d6a38e76e3 100644 --- a/buildSrc/src/main/resources/checkstyle_suppressions.xml +++ b/buildSrc/src/main/resources/checkstyle_suppressions.xml @@ -1049,7 +1049,6 @@ <suppress files="core[/\\]src[/\\]test[/\\]java[/\\]org[/\\]elasticsearch[/\\]monitor[/\\]jvm[/\\]JvmGcMonitorServiceSettingsTests.java" checks="LineLength" /> <suppress files="core[/\\]src[/\\]test[/\\]java[/\\]org[/\\]elasticsearch[/\\]monitor[/\\]os[/\\]OsProbeTests.java" checks="LineLength" /> <suppress files="core[/\\]src[/\\]test[/\\]java[/\\]org[/\\]elasticsearch[/\\]nodesinfo[/\\]NodeInfoStreamingTests.java" checks="LineLength" /> - <suppress files="core[/\\]src[/\\]test[/\\]java[/\\]org[/\\]elasticsearch[/\\]options[/\\]detailederrors[/\\]DetailedErrorsEnabledIT.java" checks="LineLength" /> <suppress files="core[/\\]src[/\\]test[/\\]java[/\\]org[/\\]elasticsearch[/\\]plugins[/\\]PluginInfoTests.java" checks="LineLength" /> <suppress files="core[/\\]src[/\\]test[/\\]java[/\\]org[/\\]elasticsearch[/\\]plugins[/\\]PluginsServiceTests.java" checks="LineLength" /> <suppress files="core[/\\]src[/\\]test[/\\]java[/\\]org[/\\]elasticsearch[/\\]recovery[/\\]FullRollingRestartIT.java" checks="LineLength" /> diff --git a/client/src/main/java/org/elasticsearch/client/RestClient.java b/client/src/main/java/org/elasticsearch/client/RestClient.java index 6c37fd58ae..31914f4628 100644 --- a/client/src/main/java/org/elasticsearch/client/RestClient.java +++ b/client/src/main/java/org/elasticsearch/client/RestClient.java @@ -20,6 +20,7 @@ package org.elasticsearch.client; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.apache.http.Consts; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; @@ -32,6 +33,7 @@ import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.utils.URIBuilder; +import org.apache.http.entity.ContentType; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; @@ -55,6 +57,7 @@ import java.util.concurrent.atomic.AtomicInteger; public final class RestClient implements Closeable { private static final Log logger = LogFactory.getLog(RestClient.class); + public static ContentType JSON_CONTENT_TYPE = ContentType.create("application/json", Consts.UTF_8); private final CloseableHttpClient client; private final long maxRetryTimeout; diff --git a/core/src/test/java/org/elasticsearch/http/netty/NettyHttpCompressionIT.java b/core/src/test/java/org/elasticsearch/http/netty/NettyHttpCompressionIT.java index bb7a78ab43..9e995f0a01 100644 --- a/core/src/test/java/org/elasticsearch/http/netty/NettyHttpCompressionIT.java +++ b/core/src/test/java/org/elasticsearch/http/netty/NettyHttpCompressionIT.java @@ -22,27 +22,31 @@ import org.apache.http.Header; import org.apache.http.HttpException; import org.apache.http.HttpHeaders; import org.apache.http.HttpResponseInterceptor; +import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicHeader; import org.apache.http.protocol.HttpContext; +import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.RestClient; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.http.HttpTransportSettings; import org.elasticsearch.test.ESIntegTestCase; -import org.elasticsearch.test.rest.client.http.HttpResponse; import java.io.IOException; +import java.util.Collections; @ESIntegTestCase.ClusterScope(scope = ESIntegTestCase.Scope.SUITE, numDataNodes = 1, numClientNodes = 1) public class NettyHttpCompressionIT extends ESIntegTestCase { private static final String GZIP_ENCODING = "gzip"; - private static final String SAMPLE_DOCUMENT = "{\n" + + private static final StringEntity SAMPLE_DOCUMENT = new StringEntity("{\n" + " \"name\": {\n" + " \"first name\": \"Steve\",\n" + " \"last name\": \"Jobs\"\n" + " }\n" + - "}"; + "}", RestClient.JSON_CONTENT_TYPE); @Override protected Settings nodeSettings(int nodeOrdinal) { @@ -55,69 +59,49 @@ public class NettyHttpCompressionIT extends ESIntegTestCase { public void testCompressesResponseIfRequested() throws Exception { ensureGreen(); - // we need to intercept early, otherwise internal logic in HttpClient will just remove the header and we cannot verify it ContentEncodingHeaderExtractor headerExtractor = new ContentEncodingHeaderExtractor(); - CloseableHttpClient internalClient = HttpClients.custom().addInterceptorFirst(headerExtractor).build(); - - HttpResponse response = httpClient(internalClient).path("/").addHeader(HttpHeaders.ACCEPT_ENCODING, GZIP_ENCODING).execute(); - assertEquals(200, response.getStatusCode()); - assertTrue(headerExtractor.hasContentEncodingHeader()); - assertEquals(GZIP_ENCODING, headerExtractor.getContentEncodingHeader().getValue()); + try (RestClient client = restClient(HttpClients.custom().addInterceptorFirst(headerExtractor).build())) { + ElasticsearchResponse response = client.performRequest("GET", "/", Collections.emptyMap(), null, + new BasicHeader(HttpHeaders.ACCEPT_ENCODING, GZIP_ENCODING)); + assertEquals(200, response.getStatusLine().getStatusCode()); + assertTrue(headerExtractor.hasContentEncodingHeader()); + assertEquals(GZIP_ENCODING, headerExtractor.getContentEncodingHeader().getValue()); + } } public void testUncompressedResponseByDefault() throws Exception { ensureGreen(); - ContentEncodingHeaderExtractor headerExtractor = new ContentEncodingHeaderExtractor(); - CloseableHttpClient internalClient = HttpClients - .custom() - .disableContentCompression() - .addInterceptorFirst(headerExtractor) - .build(); - - HttpResponse response = httpClient(internalClient).path("/").execute(); - assertEquals(200, response.getStatusCode()); - assertFalse(headerExtractor.hasContentEncodingHeader()); + CloseableHttpClient httpClient = HttpClients.custom().disableContentCompression().addInterceptorFirst(headerExtractor).build(); + try (RestClient client = restClient(httpClient)) { + ElasticsearchResponse response = client.performRequest("GET", "/", Collections.emptyMap(), null); + assertEquals(200, response.getStatusLine().getStatusCode()); + assertFalse(headerExtractor.hasContentEncodingHeader()); + } } public void testCanInterpretUncompressedRequest() throws Exception { ensureGreen(); - ContentEncodingHeaderExtractor headerExtractor = new ContentEncodingHeaderExtractor(); - CloseableHttpClient internalClient = HttpClients - .custom() - // this disable content compression in both directions (request and response) - .disableContentCompression() - .addInterceptorFirst(headerExtractor) - .build(); - - HttpResponse response = httpClient(internalClient) - .path("/company/employees/1") - .method("POST") - .body(SAMPLE_DOCUMENT) - .execute(); - - assertEquals(201, response.getStatusCode()); - assertFalse(headerExtractor.hasContentEncodingHeader()); + // this disable content compression in both directions (request and response) + CloseableHttpClient httpClient = HttpClients.custom().disableContentCompression().addInterceptorFirst(headerExtractor).build(); + try (RestClient client = restClient(httpClient)) { + ElasticsearchResponse response = client.performRequest("POST", "/company/employees/1", Collections.emptyMap(), SAMPLE_DOCUMENT); + assertEquals(201, response.getStatusLine().getStatusCode()); + assertFalse(headerExtractor.hasContentEncodingHeader()); + } } public void testCanInterpretCompressedRequest() throws Exception { ensureGreen(); - ContentEncodingHeaderExtractor headerExtractor = new ContentEncodingHeaderExtractor(); // we don't call #disableContentCompression() hence the client will send the content compressed - CloseableHttpClient internalClient = HttpClients.custom().addInterceptorFirst(headerExtractor).build(); - - HttpResponse response = httpClient(internalClient) - .path("/company/employees/2") - .method("POST") - .body(SAMPLE_DOCUMENT) - .execute(); - - assertEquals(201, response.getStatusCode()); - assertTrue(headerExtractor.hasContentEncodingHeader()); - assertEquals(GZIP_ENCODING, headerExtractor.getContentEncodingHeader().getValue()); + try (RestClient client = restClient(HttpClients.custom().addInterceptorFirst(headerExtractor).build())) { + ElasticsearchResponse response = client.performRequest("POST", "/company/employees/2", Collections.emptyMap(), SAMPLE_DOCUMENT); + assertEquals(201, response.getStatusLine().getStatusCode()); + assertEquals(GZIP_ENCODING, headerExtractor.getContentEncodingHeader().getValue()); + } } private static class ContentEncodingHeaderExtractor implements HttpResponseInterceptor { @@ -141,6 +125,4 @@ public class NettyHttpCompressionIT extends ESIntegTestCase { return contentEncodingHeader; } } - - } diff --git a/core/src/test/java/org/elasticsearch/options/detailederrors/DetailedErrorsDisabledIT.java b/core/src/test/java/org/elasticsearch/options/detailederrors/DetailedErrorsDisabledIT.java index 683ae71a11..ba8840bbc2 100644 --- a/core/src/test/java/org/elasticsearch/options/detailederrors/DetailedErrorsDisabledIT.java +++ b/core/src/test/java/org/elasticsearch/options/detailederrors/DetailedErrorsDisabledIT.java @@ -19,17 +19,17 @@ package org.elasticsearch.options.detailederrors; -import org.apache.http.impl.client.HttpClients; +import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.ElasticsearchResponseException; +import org.elasticsearch.client.RestClient; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.http.HttpServerTransport; import org.elasticsearch.http.HttpTransportSettings; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.test.ESIntegTestCase.Scope; -import org.elasticsearch.test.rest.client.http.HttpDeleteWithEntity; -import org.elasticsearch.test.rest.client.http.HttpRequestBuilder; -import org.elasticsearch.test.rest.client.http.HttpResponse; + +import java.util.Collections; import static org.hamcrest.Matchers.is; @@ -49,15 +49,14 @@ public class DetailedErrorsDisabledIT extends ESIntegTestCase { } public void testThatErrorTraceParamReturns400() throws Exception { - // Make the HTTP request - HttpResponse response = new HttpRequestBuilder(HttpClients.createDefault()) - .httpTransport(internalCluster().getDataNodeInstance(HttpServerTransport.class)) - .addParam("error_trace", "true") - .method(HttpDeleteWithEntity.METHOD_NAME) - .execute(); - - assertThat(response.getHeaders().get("Content-Type"), is("application/json")); - assertThat(response.getBody(), is("{\"error\":\"error traces in responses are disabled.\"}")); - assertThat(response.getStatusCode(), is(400)); + try (RestClient restClient = restClient()) { + restClient.performRequest("DELETE", "/", Collections.singletonMap("error_trace", "true"), null); + fail("request should have failed"); + } catch(ElasticsearchResponseException e) { + ElasticsearchResponse response = e.getElasticsearchResponse(); + assertThat(response.getFirstHeader("Content-Type"), is("application/json")); + assertThat(e.getResponseBody(), is("{\"error\":\"error traces in responses are disabled.\"}")); + assertThat(response.getStatusLine().getStatusCode(), is(400)); + } } } diff --git a/core/src/test/java/org/elasticsearch/options/detailederrors/DetailedErrorsEnabledIT.java b/core/src/test/java/org/elasticsearch/options/detailederrors/DetailedErrorsEnabledIT.java index d98db83ddd..a040c31299 100644 --- a/core/src/test/java/org/elasticsearch/options/detailederrors/DetailedErrorsEnabledIT.java +++ b/core/src/test/java/org/elasticsearch/options/detailederrors/DetailedErrorsEnabledIT.java @@ -19,16 +19,16 @@ package org.elasticsearch.options.detailederrors; -import org.apache.http.impl.client.HttpClients; +import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.ElasticsearchResponseException; +import org.elasticsearch.client.RestClient; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.http.HttpServerTransport; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.test.ESIntegTestCase.Scope; -import org.elasticsearch.test.rest.client.http.HttpDeleteWithEntity; -import org.elasticsearch.test.rest.client.http.HttpRequestBuilder; -import org.elasticsearch.test.rest.client.http.HttpResponse; + +import java.util.Collections; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.not; @@ -47,25 +47,26 @@ public class DetailedErrorsEnabledIT extends ESIntegTestCase { } public void testThatErrorTraceWorksByDefault() throws Exception { - // Make the HTTP request - HttpResponse response = new HttpRequestBuilder(HttpClients.createDefault()) - .httpTransport(internalCluster().getDataNodeInstance(HttpServerTransport.class)) - .path("/") - .addParam("error_trace", "true") - .method(HttpDeleteWithEntity.METHOD_NAME) - .execute(); - - assertThat(response.getHeaders().get("Content-Type"), containsString("application/json")); - assertThat(response.getBody(), containsString("\"stack_trace\":\"[Validation Failed: 1: index / indices is missing;]; nested: ActionRequestValidationException[Validation Failed: 1:")); - - // Make the HTTP request - response = new HttpRequestBuilder(HttpClients.createDefault()) - .httpTransport(internalCluster().getDataNodeInstance(HttpServerTransport.class)) - .path("/") - .method(HttpDeleteWithEntity.METHOD_NAME) - .execute(); + try (RestClient restClient = restClient()) { + try { + restClient.performRequest("DELETE", "/", Collections.singletonMap("error_trace", "true"), null); + fail("request should have failed"); + } catch(ElasticsearchResponseException e) { + ElasticsearchResponse response = e.getElasticsearchResponse(); + assertThat(response.getFirstHeader("Content-Type"), containsString("application/json")); + assertThat(e.getResponseBody(), containsString("\"stack_trace\":\"[Validation Failed: 1: index / indices is missing;]; " + + "nested: ActionRequestValidationException[Validation Failed: 1:")); + } - assertThat(response.getHeaders().get("Content-Type"), containsString("application/json")); - assertThat(response.getBody(), not(containsString("\"stack_trace\":\"[Validation Failed: 1: index / indices is missing;]; nested: ActionRequestValidationException[Validation Failed: 1:"))); + try { + restClient.performRequest("DELETE", "/", Collections.emptyMap(), null); + fail("request should have failed"); + } catch(ElasticsearchResponseException e) { + ElasticsearchResponse response = e.getElasticsearchResponse(); + assertThat(response.getFirstHeader("Content-Type"), containsString("application/json")); + assertThat(e.getResponseBody(), not(containsString("\"stack_trace\":\"[Validation Failed: 1: index / indices is missing;]; " + + "nested: ActionRequestValidationException[Validation Failed: 1:"))); + } + } } } diff --git a/core/src/test/java/org/elasticsearch/plugins/ResponseHeaderPluginIT.java b/core/src/test/java/org/elasticsearch/plugins/ResponseHeaderPluginIT.java index ac6d8fddd8..4ae9e3912b 100644 --- a/core/src/test/java/org/elasticsearch/plugins/ResponseHeaderPluginIT.java +++ b/core/src/test/java/org/elasticsearch/plugins/ResponseHeaderPluginIT.java @@ -18,14 +18,18 @@ */ package org.elasticsearch.plugins; +import org.apache.http.message.BasicHeader; +import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.ElasticsearchResponseException; +import org.elasticsearch.client.RestClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.plugins.responseheader.TestResponseHeaderPlugin; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.test.ESIntegTestCase.Scope; -import org.elasticsearch.test.rest.client.http.HttpResponse; import java.util.Collection; +import java.util.Collections; import static org.elasticsearch.rest.RestStatus.OK; import static org.elasticsearch.rest.RestStatus.UNAUTHORIZED; @@ -52,12 +56,20 @@ public class ResponseHeaderPluginIT extends ESIntegTestCase { public void testThatSettingHeadersWorks() throws Exception { ensureGreen(); - HttpResponse response = httpClient().method("GET").path("/_protected").execute(); - assertThat(response, hasStatus(UNAUTHORIZED)); - assertThat(response.getHeaders().get("Secret"), equalTo("required")); + try (RestClient client = restClient()) { + try { + client.performRequest("GET", "/_protected", Collections.emptyMap(), null); + fail("request should have failed"); + } catch(ElasticsearchResponseException e) { + ElasticsearchResponse response = e.getElasticsearchResponse(); + assertThat(response, hasStatus(UNAUTHORIZED)); + assertThat(response.getFirstHeader("Secret"), equalTo("required")); + } - HttpResponse authResponse = httpClient().method("GET").path("/_protected").addHeader("Secret", "password").execute(); - assertThat(authResponse, hasStatus(OK)); - assertThat(authResponse.getHeaders().get("Secret"), equalTo("granted")); + ElasticsearchResponse authResponse = client.performRequest("GET", "/_protected", Collections.emptyMap(), null, + new BasicHeader("Secret", "password")); + assertThat(authResponse, hasStatus(OK)); + assertThat(authResponse.getFirstHeader("Secret"), equalTo("granted")); + } } } diff --git a/core/src/test/java/org/elasticsearch/rest/CorsNotSetIT.java b/core/src/test/java/org/elasticsearch/rest/CorsNotSetIT.java index dfdd88d198..e407bccf87 100644 --- a/core/src/test/java/org/elasticsearch/rest/CorsNotSetIT.java +++ b/core/src/test/java/org/elasticsearch/rest/CorsNotSetIT.java @@ -19,15 +19,18 @@ package org.elasticsearch.rest; +import org.apache.http.message.BasicHeader; +import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.RestClient; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; -import org.elasticsearch.test.rest.client.http.HttpResponse; -import static org.hamcrest.Matchers.hasKey; +import java.util.Collections; + import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.nullValue; /** * @@ -44,18 +47,21 @@ public class CorsNotSetIT extends ESIntegTestCase { public void testCorsSettingDefaultBehaviourDoesNotReturnAnything() throws Exception { String corsValue = "http://localhost:9200"; - HttpResponse response = httpClient().method("GET").path("/").addHeader("User-Agent", "Mozilla Bar").addHeader("Origin", corsValue).execute(); - - assertThat(response.getStatusCode(), is(200)); - assertThat(response.getHeaders(), not(hasKey("Access-Control-Allow-Origin"))); - assertThat(response.getHeaders(), not(hasKey("Access-Control-Allow-Credentials"))); + try (RestClient restClient = restClient()) { + ElasticsearchResponse response = restClient.performRequest("GET", "/", Collections.emptyMap(), null, + new BasicHeader("User-Agent", "Mozilla Bar"), new BasicHeader("Origin", corsValue)); + assertThat(response.getStatusLine().getStatusCode(), is(200)); + assertThat(response.getFirstHeader("Access-Control-Allow-Origin"), nullValue()); + assertThat(response.getFirstHeader("Access-Control-Allow-Credentials"), nullValue()); + } } public void testThatOmittingCorsHeaderDoesNotReturnAnything() throws Exception { - HttpResponse response = httpClient().method("GET").path("/").execute(); - - assertThat(response.getStatusCode(), is(200)); - assertThat(response.getHeaders(), not(hasKey("Access-Control-Allow-Origin"))); - assertThat(response.getHeaders(), not(hasKey("Access-Control-Allow-Credentials"))); + try (RestClient restClient = restClient()) { + ElasticsearchResponse response = restClient.performRequest("GET", "/", Collections.emptyMap(), null); + assertThat(response.getStatusLine().getStatusCode(), is(200)); + assertThat(response.getFirstHeader("Access-Control-Allow-Origin"), nullValue()); + assertThat(response.getFirstHeader("Access-Control-Allow-Credentials"), nullValue()); + } } } diff --git a/core/src/test/java/org/elasticsearch/rest/CorsRegexIT.java b/core/src/test/java/org/elasticsearch/rest/CorsRegexIT.java index 18351dcb29..729fed8e96 100644 --- a/core/src/test/java/org/elasticsearch/rest/CorsRegexIT.java +++ b/core/src/test/java/org/elasticsearch/rest/CorsRegexIT.java @@ -18,6 +18,10 @@ */ package org.elasticsearch.rest; +import org.apache.http.message.BasicHeader; +import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.ElasticsearchResponseException; +import org.elasticsearch.client.RestClient; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.network.NetworkModule; @@ -25,16 +29,16 @@ import org.elasticsearch.common.settings.Settings; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.test.ESIntegTestCase.Scope; -import org.elasticsearch.test.rest.client.http.HttpResponse; import org.jboss.netty.handler.codec.http.HttpHeaders; +import java.util.Collections; + import static org.elasticsearch.http.HttpTransportSettings.SETTING_CORS_ALLOW_CREDENTIALS; import static org.elasticsearch.http.HttpTransportSettings.SETTING_CORS_ALLOW_METHODS; import static org.elasticsearch.http.HttpTransportSettings.SETTING_CORS_ALLOW_ORIGIN; import static org.elasticsearch.http.HttpTransportSettings.SETTING_CORS_ENABLED; -import static org.hamcrest.Matchers.hasKey; import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.nullValue; /** * Test CORS where the allow origin value is a regular expression. @@ -58,64 +62,77 @@ public class CorsRegexIT extends ESIntegTestCase { public void testThatRegularExpressionWorksOnMatch() throws Exception { String corsValue = "http://localhost:9200"; - HttpResponse response = httpClient().method("GET").path("/").addHeader("User-Agent", "Mozilla Bar").addHeader("Origin", corsValue).execute(); - assertResponseWithOriginheader(response, corsValue); + try (RestClient client = restClient()) { + ElasticsearchResponse response = client.performRequest("GET", "/", Collections.emptyMap(), null, + new BasicHeader("User-Agent", "Mozilla Bar"), new BasicHeader("Origin", corsValue)); + assertResponseWithOriginheader(response, corsValue); - corsValue = "https://localhost:9200"; - response = httpClient().method("GET").path("/").addHeader("User-Agent", "Mozilla Bar").addHeader("Origin", corsValue).execute(); - assertResponseWithOriginheader(response, corsValue); - assertThat(response.getHeaders(), hasKey("Access-Control-Allow-Credentials")); - assertThat(response.getHeaders().get("Access-Control-Allow-Credentials"), is("true")); + corsValue = "https://localhost:9200"; + response = client.performRequest("GET", "/", Collections.emptyMap(), null, + new BasicHeader("User-Agent", "Mozilla Bar"), new BasicHeader("Origin", corsValue)); + assertResponseWithOriginheader(response, corsValue); + assertThat(response.getFirstHeader("Access-Control-Allow-Credentials"), is("true")); + } } public void testThatRegularExpressionReturnsForbiddenOnNonMatch() throws Exception { - HttpResponse response = httpClient().method("GET").path("/").addHeader("User-Agent", "Mozilla Bar").addHeader("Origin", "http://evil-host:9200").execute(); - // a rejected origin gets a FORBIDDEN - 403 - assertThat(response.getStatusCode(), is(403)); - assertThat(response.getHeaders(), not(hasKey("Access-Control-Allow-Origin"))); + try (RestClient client = restClient()) { + client.performRequest("GET", "/", Collections.emptyMap(), null, new BasicHeader("User-Agent", "Mozilla Bar"), + new BasicHeader("Origin", "http://evil-host:9200")); + fail("request should have failed"); + } catch(ElasticsearchResponseException e) { + ElasticsearchResponse response = e.getElasticsearchResponse(); + // a rejected origin gets a FORBIDDEN - 403 + assertThat(response.getStatusLine().getStatusCode(), is(403)); + assertThat(response.getFirstHeader("Access-Control-Allow-Origin"), nullValue()); + } } public void testThatSendingNoOriginHeaderReturnsNoAccessControlHeader() throws Exception { - HttpResponse response = httpClient().method("GET").path("/").addHeader("User-Agent", "Mozilla Bar").execute(); - assertThat(response.getStatusCode(), is(200)); - assertThat(response.getHeaders(), not(hasKey("Access-Control-Allow-Origin"))); + try (RestClient client = restClient()) { + ElasticsearchResponse response = client.performRequest("GET", "/", Collections.emptyMap(), null, + new BasicHeader("User-Agent", "Mozilla Bar")); + assertThat(response.getStatusLine().getStatusCode(), is(200)); + assertThat(response.getFirstHeader("Access-Control-Allow-Origin"), nullValue()); + } } public void testThatRegularExpressionIsNotAppliedWithoutCorrectBrowserOnMatch() throws Exception { - HttpResponse response = httpClient().method("GET").path("/").execute(); - assertThat(response.getStatusCode(), is(200)); - assertThat(response.getHeaders(), not(hasKey("Access-Control-Allow-Origin"))); + try (RestClient client = restClient()) { + ElasticsearchResponse response = client.performRequest("GET", "/", Collections.emptyMap(), null); + assertThat(response.getStatusLine().getStatusCode(), is(200)); + assertThat(response.getFirstHeader("Access-Control-Allow-Origin"), nullValue()); + } } public void testThatPreFlightRequestWorksOnMatch() throws Exception { String corsValue = "http://localhost:9200"; - HttpResponse response = httpClient().method("OPTIONS") - .path("/") - .addHeader("User-Agent", "Mozilla Bar") - .addHeader("Origin", corsValue) - .addHeader(HttpHeaders.Names.ACCESS_CONTROL_REQUEST_METHOD, "GET") - .execute(); - assertResponseWithOriginheader(response, corsValue); - assertThat(response.getHeaders(), hasKey("Access-Control-Allow-Methods")); + try (RestClient client = restClient()) { + ElasticsearchResponse response = client.performRequest("OPTIONS", "/", Collections.emptyMap(), null, + new BasicHeader("User-Agent", "Mozilla Bar"), new BasicHeader("Origin", corsValue), + new BasicHeader(HttpHeaders.Names.ACCESS_CONTROL_REQUEST_METHOD, "GET")); + assertResponseWithOriginheader(response, corsValue); + assertNotNull(response.getFirstHeader("Access-Control-Allow-Methods")); + } } public void testThatPreFlightRequestReturnsNullOnNonMatch() throws Exception { - HttpResponse response = httpClient().method("OPTIONS") - .path("/") - .addHeader("User-Agent", "Mozilla Bar") - .addHeader("Origin", "http://evil-host:9200") - .addHeader(HttpHeaders.Names.ACCESS_CONTROL_REQUEST_METHOD, "GET") - .execute(); - // a rejected origin gets a FORBIDDEN - 403 - assertThat(response.getStatusCode(), is(403)); - assertThat(response.getHeaders(), not(hasKey("Access-Control-Allow-Origin"))); - assertThat(response.getHeaders(), not(hasKey("Access-Control-Allow-Methods"))); + try (RestClient client = restClient()) { + client.performRequest("OPTIONS", "/", Collections.emptyMap(), null, new BasicHeader("User-Agent", "Mozilla Bar"), + new BasicHeader("Origin", "http://evil-host:9200"), + new BasicHeader(HttpHeaders.Names.ACCESS_CONTROL_REQUEST_METHOD, "GET")); + fail("request should have failed"); + } catch(ElasticsearchResponseException e) { + ElasticsearchResponse response = e.getElasticsearchResponse(); + // a rejected origin gets a FORBIDDEN - 403 + assertThat(response.getStatusLine().getStatusCode(), is(403)); + assertThat(response.getFirstHeader("Access-Control-Allow-Origin"), nullValue()); + assertThat(response.getFirstHeader("Access-Control-Allow-Methods"), nullValue()); + } } - protected static void assertResponseWithOriginheader(HttpResponse response, String expectedCorsHeader) { - assertThat(response.getStatusCode(), is(200)); - assertThat(response.getHeaders(), hasKey("Access-Control-Allow-Origin")); - assertThat(response.getHeaders().get("Access-Control-Allow-Origin"), is(expectedCorsHeader)); + protected static void assertResponseWithOriginheader(ElasticsearchResponse response, String expectedCorsHeader) { + assertThat(response.getStatusLine().getStatusCode(), is(200)); + assertThat(response.getFirstHeader("Access-Control-Allow-Origin"), is(expectedCorsHeader)); } - } diff --git a/core/src/test/java/org/elasticsearch/rest/action/main/RestMainActionIT.java b/core/src/test/java/org/elasticsearch/rest/action/main/RestMainActionIT.java index 0ad40f84cf..9c2b0284ef 100644 --- a/core/src/test/java/org/elasticsearch/rest/action/main/RestMainActionIT.java +++ b/core/src/test/java/org/elasticsearch/rest/action/main/RestMainActionIT.java @@ -18,16 +18,18 @@ */ package org.elasticsearch.rest.action.main; +import org.apache.http.util.EntityUtils; +import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.RestClient; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.test.ESIntegTestCase; -import org.elasticsearch.test.rest.client.http.HttpResponse; import java.io.IOException; +import java.util.Collections; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.nullValue; public class RestMainActionIT extends ESIntegTestCase { @Override @@ -39,14 +41,19 @@ public class RestMainActionIT extends ESIntegTestCase { } public void testHeadRequest() throws IOException { - final HttpResponse response = httpClient().method("HEAD").path("/").execute(); - assertThat(response.getStatusCode(), equalTo(200)); - assertThat(response.getBody(), nullValue()); + try (RestClient client = restClient()) { + ElasticsearchResponse response = client.performRequest("HEAD", "/", Collections.emptyMap(), null); + assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + assertNull(response.getEntity()); + } } public void testGetRequest() throws IOException { - final HttpResponse response = httpClient().path("/").execute(); - assertThat(response.getStatusCode(), equalTo(200)); - assertThat(response.getBody(), containsString("cluster_name")); + try (RestClient client = restClient()) { + ElasticsearchResponse response = client.performRequest("GET", "/", Collections.emptyMap(), null); + assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + assertNotNull(response.getEntity()); + assertThat(EntityUtils.toString(response.getEntity()), containsString("cluster_name")); + } } } diff --git a/core/src/test/java/org/elasticsearch/transport/ContextAndHeaderTransportIT.java b/core/src/test/java/org/elasticsearch/transport/ContextAndHeaderTransportIT.java index eb13de3485..aae15dc778 100644 --- a/core/src/test/java/org/elasticsearch/transport/ContextAndHeaderTransportIT.java +++ b/core/src/test/java/org/elasticsearch/transport/ContextAndHeaderTransportIT.java @@ -19,8 +19,7 @@ package org.elasticsearch.transport; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicHeader; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.ActionModule; import org.elasticsearch.action.ActionRequest; @@ -33,12 +32,13 @@ import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.support.ActionFilter; import org.elasticsearch.action.termvectors.MultiTermVectorsRequest; import org.elasticsearch.client.Client; +import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.RestClient; import org.elasticsearch.common.inject.AbstractModule; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Module; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.http.HttpServerTransport; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.GeoShapeQueryBuilder; import org.elasticsearch.index.query.MoreLikeThisQueryBuilder; @@ -50,8 +50,6 @@ import org.elasticsearch.plugins.Plugin; import org.elasticsearch.rest.RestController; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; -import org.elasticsearch.test.rest.client.http.HttpRequestBuilder; -import org.elasticsearch.test.rest.client.http.HttpResponse; import org.elasticsearch.threadpool.ThreadPool; import org.junit.After; import org.junit.Before; @@ -217,26 +215,22 @@ public class ContextAndHeaderTransportIT extends ESIntegTestCase { } public void testThatRelevantHttpHeadersBecomeRequestHeaders() throws Exception { - String releventHeaderName = "relevant_" + randomHeaderKey; - for (RestController restController : internalCluster().getDataNodeInstances(RestController.class)) { - restController.registerRelevantHeaders(releventHeaderName); + String relevantHeaderName = "relevant_" + randomHeaderKey; + for (RestController restController : internalCluster().getInstances(RestController.class)) { + restController.registerRelevantHeaders(relevantHeaderName); } - CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpResponse response = new HttpRequestBuilder(httpClient) - .httpTransport(internalCluster().getDataNodeInstance(HttpServerTransport.class)) - .addHeader(randomHeaderKey, randomHeaderValue) - .addHeader(releventHeaderName, randomHeaderValue) - .path("/" + queryIndex + "/_search") - .execute(); - - assertThat(response, hasStatus(OK)); - List<RequestAndHeaders> searchRequests = getRequests(SearchRequest.class); - assertThat(searchRequests, hasSize(greaterThan(0))); - for (RequestAndHeaders requestAndHeaders : searchRequests) { - assertThat(requestAndHeaders.headers.containsKey(releventHeaderName), is(true)); - // was not specified, thus is not included - assertThat(requestAndHeaders.headers.containsKey(randomHeaderKey), is(false)); + try (RestClient client = restClient()) { + ElasticsearchResponse response = client.performRequest("GET", "/" + queryIndex + "/_search", Collections.emptyMap(), null, + new BasicHeader(randomHeaderKey, randomHeaderValue), new BasicHeader(relevantHeaderName, randomHeaderValue)); + assertThat(response, hasStatus(OK)); + List<RequestAndHeaders> searchRequests = getRequests(SearchRequest.class); + assertThat(searchRequests, hasSize(greaterThan(0))); + for (RequestAndHeaders requestAndHeaders : searchRequests) { + assertThat(requestAndHeaders.headers.containsKey(relevantHeaderName), is(true)); + // was not specified, thus is not included + assertThat(requestAndHeaders.headers.containsKey(randomHeaderKey), is(false)); + } } } diff --git a/test/framework/build.gradle b/test/framework/build.gradle index af65c9ff7c..078511611f 100644 --- a/test/framework/build.gradle +++ b/test/framework/build.gradle @@ -23,14 +23,15 @@ dependencies { compile "org.elasticsearch:elasticsearch:${version}" compile "com.carrotsearch.randomizedtesting:randomizedtesting-runner:${versions.randomizedrunner}" compile "junit:junit:${versions.junit}" - compile 'org.hamcrest:hamcrest-all:1.3' + compile "org.hamcrest:hamcrest-all:1.3" compile "org.apache.lucene:lucene-test-framework:${versions.lucene}" compile "org.apache.lucene:lucene-codecs:${versions.lucene}" + compile "org.elasticsearch:client:${version}" compile "org.apache.httpcomponents:httpclient:${versions.httpclient}" compile "org.apache.httpcomponents:httpcore:${versions.httpcore}" compile "commons-logging:commons-logging:${versions.commonslogging}" compile "commons-codec:commons-codec:${versions.commonscodec}" - compile 'org.elasticsearch:securemock:1.2' + compile "org.elasticsearch:securemock:1.2" } compileJava.options.compilerArgs << '-Xlint:-cast,-rawtypes,-try,-unchecked' diff --git a/test/framework/src/main/java/org/elasticsearch/test/ESIntegTestCase.java b/test/framework/src/main/java/org/elasticsearch/test/ESIntegTestCase.java index 2a3eecf4cc..67f2a65492 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/ESIntegTestCase.java +++ b/test/framework/src/main/java/org/elasticsearch/test/ESIntegTestCase.java @@ -22,8 +22,8 @@ import com.carrotsearch.randomizedtesting.RandomizedContext; import com.carrotsearch.randomizedtesting.annotations.TestGroup; import com.carrotsearch.randomizedtesting.generators.RandomInts; import com.carrotsearch.randomizedtesting.generators.RandomPicks; +import org.apache.http.HttpHost; import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; import org.apache.lucene.util.IOUtils; import org.apache.lucene.util.LuceneTestCase; import org.apache.lucene.util.TestUtil; @@ -57,6 +57,7 @@ import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.client.AdminClient; import org.elasticsearch.client.Client; import org.elasticsearch.client.Requests; +import org.elasticsearch.client.RestClient; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.elasticsearch.cluster.metadata.IndexMetaData; @@ -118,7 +119,6 @@ import org.elasticsearch.search.MockSearchService; import org.elasticsearch.search.SearchHit; import org.elasticsearch.test.client.RandomizingClient; import org.elasticsearch.test.disruption.ServiceDisruptionScheme; -import org.elasticsearch.test.rest.client.http.HttpRequestBuilder; import org.elasticsearch.test.store.MockFSIndexStore; import org.elasticsearch.test.transport.AssertingLocalTransport; import org.elasticsearch.test.transport.MockTransportService; @@ -2033,20 +2033,34 @@ public abstract class ESIntegTestCase extends ESTestCase { return builder.build(); } - protected HttpRequestBuilder httpClient() { - return httpClient(HttpClients.createDefault()); + protected static RestClient restClient() { + return restClient(null); } - protected HttpRequestBuilder httpClient(CloseableHttpClient httpClient) { + protected static RestClient restClient(CloseableHttpClient httpClient) { + return restClient(httpClient, "http"); + } + + protected static RestClient restClient(CloseableHttpClient httpClient, String protocol) { final NodesInfoResponse nodeInfos = client().admin().cluster().prepareNodesInfo().get(); final List<NodeInfo> nodes = nodeInfos.getNodes(); assertFalse(nodeInfos.hasFailures()); - TransportAddress publishAddress = randomFrom(nodes).getHttp().address().publishAddress(); - assertEquals(1, publishAddress.uniqueAddressTypeId()); - InetSocketAddress address = ((InetSocketTransportAddress) publishAddress).address(); - return new HttpRequestBuilder(httpClient).host(NetworkAddress.format(address.getAddress())).port(address.getPort()); - } + List<HttpHost> hosts = new ArrayList<>(); + for (NodeInfo node : nodes) { + if (node.getHttp() != null) { + TransportAddress publishAddress = node.getHttp().address().publishAddress(); + assertEquals(1, publishAddress.uniqueAddressTypeId()); + InetSocketAddress address = ((InetSocketTransportAddress) publishAddress).address(); + hosts.add(new HttpHost(NetworkAddress.format(address.getAddress()), address.getPort(), protocol)); + } + } + RestClient.Builder builder = RestClient.builder().setHosts(hosts.toArray(new HttpHost[hosts.size()])); + if (httpClient != null) { + builder.setHttpClient(httpClient); + } + return builder.build(); + } /** * This method is executed iff the test is annotated with {@link SuiteScopeTestCase} diff --git a/test/framework/src/main/java/org/elasticsearch/test/hamcrest/ElasticsearchAssertions.java b/test/framework/src/main/java/org/elasticsearch/test/hamcrest/ElasticsearchAssertions.java index d10c113b59..0fe65ccf75 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/hamcrest/ElasticsearchAssertions.java +++ b/test/framework/src/main/java/org/elasticsearch/test/hamcrest/ElasticsearchAssertions.java @@ -42,6 +42,7 @@ import org.elasticsearch.action.search.ShardSearchFailure; import org.elasticsearch.action.support.broadcast.BroadcastResponse; import org.elasticsearch.action.support.master.AcknowledgedRequestBuilder; import org.elasticsearch.action.support.master.AcknowledgedResponse; +import org.elasticsearch.client.ElasticsearchResponse; import org.elasticsearch.cluster.block.ClusterBlock; import org.elasticsearch.cluster.block.ClusterBlockException; import org.elasticsearch.cluster.metadata.IndexTemplateMetaData; @@ -60,7 +61,6 @@ import org.elasticsearch.search.SearchModule; import org.elasticsearch.search.suggest.Suggest; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.VersionUtils; -import org.elasticsearch.test.rest.client.http.HttpResponse; import org.hamcrest.CoreMatchers; import org.hamcrest.Matcher; import org.hamcrest.Matchers; @@ -82,7 +82,6 @@ import static org.elasticsearch.test.VersionUtils.randomVersion; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.hasItem; @@ -90,7 +89,6 @@ import static org.hamcrest.Matchers.hasKey; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -488,8 +486,8 @@ public class ElasticsearchAssertions { return new ElasticsearchMatchers.SearchHitHasScoreMatcher(score); } - public static Matcher<HttpResponse> hasStatus(RestStatus restStatus) { - return new ElasticsearchMatchers.HttpResponseHasStatusMatcher(restStatus); + public static Matcher<ElasticsearchResponse> hasStatus(RestStatus restStatus) { + return new ElasticsearchMatchers.ElasticsearchResponseHasStatusMatcher(restStatus); } public static <T extends Query> T assertBooleanSubQuery(Query query, Class<T> subqueryType, int i) { diff --git a/test/framework/src/main/java/org/elasticsearch/test/hamcrest/ElasticsearchMatchers.java b/test/framework/src/main/java/org/elasticsearch/test/hamcrest/ElasticsearchMatchers.java index d86791fa6b..c40e434a5a 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/hamcrest/ElasticsearchMatchers.java +++ b/test/framework/src/main/java/org/elasticsearch/test/hamcrest/ElasticsearchMatchers.java @@ -18,9 +18,9 @@ */ package org.elasticsearch.test.hamcrest; +import org.elasticsearch.client.ElasticsearchResponse; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.search.SearchHit; -import org.elasticsearch.test.rest.client.http.HttpResponse; import org.hamcrest.Description; import org.hamcrest.TypeSafeMatcher; @@ -118,27 +118,27 @@ public class ElasticsearchMatchers { } } - public static class HttpResponseHasStatusMatcher extends TypeSafeMatcher<HttpResponse> { + public static class ElasticsearchResponseHasStatusMatcher extends TypeSafeMatcher<ElasticsearchResponse> { private RestStatus restStatus; - public HttpResponseHasStatusMatcher(RestStatus restStatus) { + public ElasticsearchResponseHasStatusMatcher(RestStatus restStatus) { this.restStatus = restStatus; } @Override - protected boolean matchesSafely(HttpResponse response) { - return response.getStatusCode() == restStatus.getStatus(); + protected boolean matchesSafely(ElasticsearchResponse response) { + return response.getStatusLine().getStatusCode() == restStatus.getStatus(); } @Override - public void describeMismatchSafely(final HttpResponse response, final Description mismatchDescription) { - mismatchDescription.appendText(" was ").appendValue(response.getStatusCode()); + public void describeMismatchSafely(final ElasticsearchResponse response, final Description mismatchDescription) { + mismatchDescription.appendText(" was ").appendValue(response.getStatusLine().getStatusCode()); } @Override public void describeTo(final Description description) { - description.appendText("HTTP response status code should be ").appendValue(restStatus.getStatus()); + description.appendText("Elasticsearch response status code should be ").appendValue(restStatus.getStatus()); } } } |