Merge pull request #19340 from javanna/enhancement/perform_request_variants

Rest Client: add short performRequest method variants without params and/or body
This commit is contained in:
Luca Cavanna 2016-07-11 10:37:01 +02:00 committed by GitHub
commit db111174ec
12 changed files with 97 additions and 54 deletions

View File

@ -117,6 +117,39 @@ public final class RestClient implements Closeable {
this.blacklist.clear();
}
/**
* Sends a request to the elasticsearch cluster that the current client points to.
* Shortcut to {@link #performRequest(String, String, Map, HttpEntity, Header...)} but without parameters and request body.
*
* @param method the http method
* @param endpoint the path of the request (without host and port)
* @param headers the optional request headers
* @return the response returned by elasticsearch
* @throws IOException in case of a problem or the connection was aborted
* @throws ClientProtocolException in case of an http protocol error
* @throws ResponseException in case elasticsearch responded with a status code that indicated an error
*/
public Response performRequest(String method, String endpoint, Header... headers) throws IOException {
return performRequest(method, endpoint, Collections.<String, String>emptyMap(), null, headers);
}
/**
* Sends a request to the elasticsearch cluster that the current client points to.
* Shortcut to {@link #performRequest(String, String, Map, HttpEntity, Header...)} but without request body.
*
* @param method the http method
* @param endpoint the path of the request (without host and port)
* @param params the query_string parameters
* @param headers the optional request headers
* @return the response returned by elasticsearch
* @throws IOException in case of a problem or the connection was aborted
* @throws ClientProtocolException in case of an http protocol error
* @throws ResponseException in case elasticsearch responded with a status code that indicated an error
*/
public Response performRequest(String method, String endpoint, Map<String, String> params, Header... headers) throws IOException {
return performRequest(method, endpoint, params, null, headers);
}
/**
* Sends a request to the elasticsearch cluster that the current client points to.
* Selects a host out of the provided ones in a round-robin fashion. Failing hosts are marked dead and retried after a certain

View File

@ -19,7 +19,6 @@
package org.elasticsearch.client;
import com.carrotsearch.randomizedtesting.RandomizedTest;
import com.carrotsearch.randomizedtesting.generators.RandomInts;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
@ -102,8 +101,7 @@ public class RestClientMultipleHostsTests extends RestClientTestCase {
Collections.addAll(hostsSet, httpHosts);
for (int j = 0; j < httpHosts.length; j++) {
int statusCode = randomOkStatusCode(getRandom());
try (Response response = restClient.performRequest(randomHttpMethod(getRandom()), "/" + statusCode,
Collections.<String, String>emptyMap(), null)) {
try (Response response = restClient.performRequest(randomHttpMethod(getRandom()), "/" + statusCode)) {
assertThat(response.getStatusLine().getStatusCode(), equalTo(statusCode));
assertTrue("host not found: " + response.getHost(), hostsSet.remove(response.getHost()));
}
@ -121,8 +119,7 @@ public class RestClientMultipleHostsTests extends RestClientTestCase {
for (int j = 0; j < httpHosts.length; j++) {
String method = randomHttpMethod(getRandom());
int statusCode = randomErrorNoRetryStatusCode(getRandom());
try (Response response = restClient.performRequest(method, "/" + statusCode,
Collections.<String, String>emptyMap(), null)) {
try (Response response = restClient.performRequest(method, "/" + statusCode)) {
if (method.equals("HEAD") && statusCode == 404) {
//no exception gets thrown although we got a 404
assertThat(response.getStatusLine().getStatusCode(), equalTo(404));
@ -149,7 +146,7 @@ public class RestClientMultipleHostsTests extends RestClientTestCase {
public void testRoundRobinRetryErrors() throws Exception {
String retryEndpoint = randomErrorRetryEndpoint();
try {
restClient.performRequest(randomHttpMethod(getRandom()), retryEndpoint, Collections.<String, String>emptyMap(), null);
restClient.performRequest(randomHttpMethod(getRandom()), retryEndpoint);
fail("request should have failed");
} catch(ResponseException e) {
Set<HttpHost> hostsSet = new HashSet<>();
@ -199,7 +196,7 @@ public class RestClientMultipleHostsTests extends RestClientTestCase {
for (int j = 0; j < httpHosts.length; j++) {
retryEndpoint = randomErrorRetryEndpoint();
try {
restClient.performRequest(randomHttpMethod(getRandom()), retryEndpoint, Collections.<String, String>emptyMap(), null);
restClient.performRequest(randomHttpMethod(getRandom()), retryEndpoint);
fail("request should have failed");
} catch(ResponseException e) {
Response response = e.getResponse();
@ -225,8 +222,7 @@ public class RestClientMultipleHostsTests extends RestClientTestCase {
for (int y = 0; y < iters; y++) {
int statusCode = randomErrorNoRetryStatusCode(getRandom());
Response response;
try (Response esResponse = restClient.performRequest(randomHttpMethod(getRandom()), "/" + statusCode,
Collections.<String, String>emptyMap(), null)) {
try (Response esResponse = restClient.performRequest(randomHttpMethod(getRandom()), "/" + statusCode)) {
response = esResponse;
}
catch(ResponseException e) {
@ -245,8 +241,7 @@ public class RestClientMultipleHostsTests extends RestClientTestCase {
for (int y = 0; y < i + 1; y++) {
retryEndpoint = randomErrorRetryEndpoint();
try {
restClient.performRequest(randomHttpMethod(getRandom()), retryEndpoint,
Collections.<String, String>emptyMap(), null);
restClient.performRequest(randomHttpMethod(getRandom()), retryEndpoint);
fail("request should have failed");
} catch(ResponseException e) {
Response response = e.getResponse();

View File

@ -19,7 +19,6 @@
package org.elasticsearch.client;
import com.carrotsearch.randomizedtesting.RandomizedTest;
import com.carrotsearch.randomizedtesting.generators.RandomInts;
import com.carrotsearch.randomizedtesting.generators.RandomStrings;
import org.apache.http.Header;
@ -156,7 +155,7 @@ public class RestClientSingleHostTests extends RestClientTestCase {
}
}
public void testSetNodes() throws IOException {
public void testSetHosts() throws IOException {
try {
restClient.setHosts((HttpHost[]) null);
fail("setHosts should have failed");
@ -189,8 +188,7 @@ public class RestClientSingleHostTests extends RestClientTestCase {
public void testOkStatusCodes() throws Exception {
for (String method : getHttpMethods()) {
for (int okStatusCode : getOkStatusCodes()) {
Response response = restClient.performRequest(method, "/" + okStatusCode,
Collections.<String, String>emptyMap(), null);
Response response = performRequest(method, "/" + okStatusCode);
assertThat(response.getStatusLine().getStatusCode(), equalTo(okStatusCode));
}
}
@ -204,8 +202,7 @@ public class RestClientSingleHostTests extends RestClientTestCase {
for (String method : getHttpMethods()) {
//error status codes should cause an exception to be thrown
for (int errorStatusCode : getAllErrorStatusCodes()) {
try (Response response = restClient.performRequest(method, "/" + errorStatusCode,
Collections.<String, String>emptyMap(), null)) {
try (Response response = performRequest(method, "/" + errorStatusCode)) {
if (method.equals("HEAD") && errorStatusCode == 404) {
//no exception gets thrown although we got a 404
assertThat(response.getStatusLine().getStatusCode(), equalTo(errorStatusCode));
@ -231,14 +228,14 @@ public class RestClientSingleHostTests extends RestClientTestCase {
for (String method : getHttpMethods()) {
//IOExceptions should be let bubble up
try {
restClient.performRequest(method, "/coe", Collections.<String, String>emptyMap(), null);
performRequest(method, "/coe");
fail("request should have failed");
} catch(IOException e) {
assertThat(e, instanceOf(ConnectTimeoutException.class));
}
failureListener.assertCalled(httpHost);
try {
restClient.performRequest(method, "/soe", Collections.<String, String>emptyMap(), null);
performRequest(method, "/soe");
fail("request should have failed");
} catch(IOException e) {
assertThat(e, instanceOf(SocketTimeoutException.class));
@ -275,8 +272,7 @@ public class RestClientSingleHostTests extends RestClientTestCase {
}
for (String method : Arrays.asList("HEAD", "OPTIONS", "TRACE")) {
try {
restClient.performRequest(method, "/" + randomStatusCode(getRandom()),
Collections.<String, String>emptyMap(), entity);
restClient.performRequest(method, "/" + randomStatusCode(getRandom()), Collections.<String, String>emptyMap(), entity);
fail("request should have failed");
} catch(UnsupportedOperationException e) {
assertThat(e.getMessage(), equalTo(method + " with body is not supported"));
@ -288,13 +284,13 @@ public class RestClientSingleHostTests extends RestClientTestCase {
String method = randomHttpMethod(getRandom());
int statusCode = randomStatusCode(getRandom());
try {
restClient.performRequest(method, "/" + statusCode, Collections.<String, String>emptyMap(), null, (Header[])null);
performRequest(method, "/" + statusCode, (Header[])null);
fail("request should have failed");
} catch(NullPointerException e) {
assertEquals("request headers must not be null", e.getMessage());
}
try {
restClient.performRequest(method, "/" + statusCode, Collections.<String, String>emptyMap(), null, (Header)null);
performRequest(method, "/" + statusCode, (Header)null);
fail("request should have failed");
} catch(NullPointerException e) {
assertEquals("request header must not be null", e.getMessage());
@ -305,7 +301,13 @@ public class RestClientSingleHostTests extends RestClientTestCase {
String method = randomHttpMethod(getRandom());
int statusCode = randomStatusCode(getRandom());
try {
restClient.performRequest(method, "/" + statusCode, null, null);
restClient.performRequest(method, "/" + statusCode, (Map<String, String>)null);
fail("request should have failed");
} catch(NullPointerException e) {
assertEquals("params must not be null", e.getMessage());
}
try {
restClient.performRequest(method, "/" + statusCode, null, (HttpEntity)null);
fail("request should have failed");
} catch(NullPointerException e) {
assertEquals("params must not be null", e.getMessage());
@ -352,7 +354,8 @@ public class RestClientSingleHostTests extends RestClientTestCase {
String uriAsString = "/" + randomStatusCode(getRandom());
URIBuilder uriBuilder = new URIBuilder(uriAsString);
Map<String, String> params = Collections.emptyMap();
if (getRandom().nextBoolean()) {
boolean hasParams = randomBoolean();
if (hasParams) {
int numParams = RandomInts.randomIntBetween(getRandom(), 1, 3);
params = new HashMap<>(numParams);
for (int i = 0; i < numParams; i++) {
@ -395,7 +398,8 @@ public class RestClientSingleHostTests extends RestClientTestCase {
}
HttpEntity entity = null;
if (request instanceof HttpEntityEnclosingRequest && getRandom().nextBoolean()) {
boolean hasBody = request instanceof HttpEntityEnclosingRequest && getRandom().nextBoolean();
if (hasBody) {
entity = new StringEntity(RandomStrings.randomAsciiOfLengthBetween(getRandom(), 10, 100));
((HttpEntityEnclosingRequest) request).setEntity(entity);
}
@ -418,10 +422,29 @@ public class RestClientSingleHostTests extends RestClientTestCase {
}
try {
restClient.performRequest(method, uriAsString, params, entity, headers);
if (hasParams == false && hasBody == false && randomBoolean()) {
restClient.performRequest(method, uriAsString, headers);
} else if (hasBody == false && randomBoolean()) {
restClient.performRequest(method, uriAsString, params, headers);
} else {
restClient.performRequest(method, uriAsString, params, entity, headers);
}
} catch(ResponseException e) {
//all good
}
return request;
}
private Response performRequest(String method, String endpoint, Header... headers) throws IOException {
switch(randomIntBetween(0, 2)) {
case 0:
return restClient.performRequest(method, endpoint, headers);
case 1:
return restClient.performRequest(method, endpoint, Collections.<String, String>emptyMap(), headers);
case 2:
return restClient.performRequest(method, endpoint, Collections.<String, String>emptyMap(), null, headers);
default:
throw new UnsupportedOperationException();
}
}
}

View File

@ -62,7 +62,7 @@ public class HostsSniffer {
* Calls the elasticsearch nodes info api, parses the response and returns all the found http hosts
*/
public List<HttpHost> sniffHosts() throws IOException {
try (Response response = restClient.performRequest("get", "/_nodes/http", sniffRequestParams, null)) {
try (Response response = restClient.performRequest("get", "/_nodes/http", sniffRequestParams)) {
return readHosts(response.getEntity());
}
}

View File

@ -62,8 +62,7 @@ public class NettyHttpCompressionIT extends ESIntegTestCase {
// we need to intercept early, otherwise internal logic in HttpClient will just remove the header and we cannot verify it
ContentEncodingHeaderExtractor headerExtractor = new ContentEncodingHeaderExtractor();
try (RestClient client = createRestClient(HttpClients.custom().addInterceptorFirst(headerExtractor).build())) {
try (Response response = client.performRequest("GET", "/", Collections.emptyMap(), null,
new BasicHeader(HttpHeaders.ACCEPT_ENCODING, GZIP_ENCODING))) {
try (Response response = client.performRequest("GET", "/", new BasicHeader(HttpHeaders.ACCEPT_ENCODING, GZIP_ENCODING))) {
assertEquals(200, response.getStatusLine().getStatusCode());
assertTrue(headerExtractor.hasContentEncodingHeader());
assertEquals(GZIP_ENCODING, headerExtractor.getContentEncodingHeader().getValue());
@ -76,7 +75,7 @@ public class NettyHttpCompressionIT extends ESIntegTestCase {
ContentEncodingHeaderExtractor headerExtractor = new ContentEncodingHeaderExtractor();
CloseableHttpClient httpClient = HttpClients.custom().disableContentCompression().addInterceptorFirst(headerExtractor).build();
try (RestClient client = createRestClient(httpClient)) {
try (Response response = client.performRequest("GET", "/", Collections.emptyMap(), null)) {
try (Response response = client.performRequest("GET", "/")) {
assertEquals(200, response.getStatusLine().getStatusCode());
assertFalse(headerExtractor.hasContentEncodingHeader());
}

View File

@ -49,7 +49,7 @@ public class DetailedErrorsDisabledIT extends ESIntegTestCase {
public void testThatErrorTraceParamReturns400() throws Exception {
try {
getRestClient().performRequest("DELETE", "/", Collections.singletonMap("error_trace", "true"), null);
getRestClient().performRequest("DELETE", "/", Collections.singletonMap("error_trace", "true"));
fail("request should have failed");
} catch(ResponseException e) {
Response response = e.getResponse();

View File

@ -47,7 +47,7 @@ public class DetailedErrorsEnabledIT extends ESIntegTestCase {
public void testThatErrorTraceWorksByDefault() throws Exception {
try {
getRestClient().performRequest("DELETE", "/", Collections.singletonMap("error_trace", "true"), null);
getRestClient().performRequest("DELETE", "/", Collections.singletonMap("error_trace", "true"));
fail("request should have failed");
} catch(ResponseException e) {
Response response = e.getResponse();
@ -57,7 +57,7 @@ public class DetailedErrorsEnabledIT extends ESIntegTestCase {
}
try {
getRestClient().performRequest("DELETE", "/", Collections.emptyMap(), null);
getRestClient().performRequest("DELETE", "/");
fail("request should have failed");
} catch(ResponseException e) {
Response response = e.getResponse();

View File

@ -28,7 +28,6 @@ import org.elasticsearch.test.ESIntegTestCase.ClusterScope;
import org.elasticsearch.test.ESIntegTestCase.Scope;
import java.util.Collection;
import java.util.Collections;
import static org.hamcrest.Matchers.equalTo;
@ -53,7 +52,7 @@ public class ResponseHeaderPluginIT extends ESIntegTestCase {
public void testThatSettingHeadersWorks() throws Exception {
ensureGreen();
try {
getRestClient().performRequest("GET", "/_protected", Collections.emptyMap(), null);
getRestClient().performRequest("GET", "/_protected");
fail("request should have failed");
} catch(ResponseException e) {
Response response = e.getResponse();
@ -61,8 +60,7 @@ public class ResponseHeaderPluginIT extends ESIntegTestCase {
assertThat(response.getHeader("Secret"), equalTo("required"));
}
try (Response authResponse = getRestClient().performRequest("GET", "/_protected", Collections.emptyMap(), null,
new BasicHeader("Secret", "password"))) {
try (Response authResponse = getRestClient().performRequest("GET", "/_protected", new BasicHeader("Secret", "password"))) {
assertThat(authResponse.getStatusLine().getStatusCode(), equalTo(200));
assertThat(authResponse.getHeader("Secret"), equalTo("granted"));
}

View File

@ -26,8 +26,6 @@ import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.ESIntegTestCase.ClusterScope;
import java.util.Collections;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
@ -46,7 +44,7 @@ public class CorsNotSetIT extends ESIntegTestCase {
public void testCorsSettingDefaultBehaviourDoesNotReturnAnything() throws Exception {
String corsValue = "http://localhost:9200";
try (Response response = getRestClient().performRequest("GET", "/", Collections.emptyMap(), null,
try (Response response = getRestClient().performRequest("GET", "/",
new BasicHeader("User-Agent", "Mozilla Bar"), new BasicHeader("Origin", corsValue))) {
assertThat(response.getStatusLine().getStatusCode(), is(200));
assertThat(response.getHeader("Access-Control-Allow-Origin"), nullValue());
@ -55,7 +53,7 @@ public class CorsNotSetIT extends ESIntegTestCase {
}
public void testThatOmittingCorsHeaderDoesNotReturnAnything() throws Exception {
try (Response response = getRestClient().performRequest("GET", "/", Collections.emptyMap(), null)) {
try (Response response = getRestClient().performRequest("GET", "/")) {
assertThat(response.getStatusLine().getStatusCode(), is(200));
assertThat(response.getHeader("Access-Control-Allow-Origin"), nullValue());
assertThat(response.getHeader("Access-Control-Allow-Credentials"), nullValue());

View File

@ -30,8 +30,6 @@ import org.elasticsearch.test.ESIntegTestCase.ClusterScope;
import org.elasticsearch.test.ESIntegTestCase.Scope;
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;
@ -61,12 +59,12 @@ public class CorsRegexIT extends ESIntegTestCase {
public void testThatRegularExpressionWorksOnMatch() throws Exception {
String corsValue = "http://localhost:9200";
try (Response response = getRestClient().performRequest("GET", "/", Collections.emptyMap(), null,
try (Response response = getRestClient().performRequest("GET", "/",
new BasicHeader("User-Agent", "Mozilla Bar"), new BasicHeader("Origin", corsValue))) {
assertResponseWithOriginheader(response, corsValue);
}
corsValue = "https://localhost:9200";
try (Response response = getRestClient().performRequest("GET", "/", Collections.emptyMap(), null,
try (Response response = getRestClient().performRequest("GET", "/",
new BasicHeader("User-Agent", "Mozilla Bar"), new BasicHeader("Origin", corsValue));) {
assertResponseWithOriginheader(response, corsValue);
assertThat(response.getHeader("Access-Control-Allow-Credentials"), is("true"));
@ -75,7 +73,7 @@ public class CorsRegexIT extends ESIntegTestCase {
public void testThatRegularExpressionReturnsForbiddenOnNonMatch() throws Exception {
try {
getRestClient().performRequest("GET", "/", Collections.emptyMap(), null, new BasicHeader("User-Agent", "Mozilla Bar"),
getRestClient().performRequest("GET", "/", new BasicHeader("User-Agent", "Mozilla Bar"),
new BasicHeader("Origin", "http://evil-host:9200"));
fail("request should have failed");
} catch(ResponseException e) {
@ -87,15 +85,14 @@ public class CorsRegexIT extends ESIntegTestCase {
}
public void testThatSendingNoOriginHeaderReturnsNoAccessControlHeader() throws Exception {
try (Response response = getRestClient().performRequest("GET", "/", Collections.emptyMap(), null,
new BasicHeader("User-Agent", "Mozilla Bar"))) {
try (Response response = getRestClient().performRequest("GET", "/", new BasicHeader("User-Agent", "Mozilla Bar"))) {
assertThat(response.getStatusLine().getStatusCode(), is(200));
assertThat(response.getHeader("Access-Control-Allow-Origin"), nullValue());
}
}
public void testThatRegularExpressionIsNotAppliedWithoutCorrectBrowserOnMatch() throws Exception {
try (Response response = getRestClient().performRequest("GET", "/", Collections.emptyMap(), null)) {
try (Response response = getRestClient().performRequest("GET", "/")) {
assertThat(response.getStatusLine().getStatusCode(), is(200));
assertThat(response.getHeader("Access-Control-Allow-Origin"), nullValue());
}
@ -103,7 +100,7 @@ public class CorsRegexIT extends ESIntegTestCase {
public void testThatPreFlightRequestWorksOnMatch() throws Exception {
String corsValue = "http://localhost:9200";
try (Response response = getRestClient().performRequest("OPTIONS", "/", Collections.emptyMap(), null,
try (Response response = getRestClient().performRequest("OPTIONS", "/",
new BasicHeader("User-Agent", "Mozilla Bar"), new BasicHeader("Origin", corsValue),
new BasicHeader(HttpHeaders.Names.ACCESS_CONTROL_REQUEST_METHOD, "GET"));) {
assertResponseWithOriginheader(response, corsValue);
@ -113,7 +110,7 @@ public class CorsRegexIT extends ESIntegTestCase {
public void testThatPreFlightRequestReturnsNullOnNonMatch() throws Exception {
try {
getRestClient().performRequest("OPTIONS", "/", Collections.emptyMap(), null, new BasicHeader("User-Agent", "Mozilla Bar"),
getRestClient().performRequest("OPTIONS", "/", 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");

View File

@ -220,7 +220,7 @@ public class ContextAndHeaderTransportIT extends ESIntegTestCase {
}
try (Response response = getRestClient().performRequest(
"GET", "/" + queryIndex + "/_search", Collections.emptyMap(), null,
"GET", "/" + queryIndex + "/_search",
new BasicHeader(randomHeaderKey, randomHeaderValue), new BasicHeader(relevantHeaderName, randomHeaderValue))) {
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
List<RequestAndHeaders> searchRequests = getRequests(SearchRequest.class);

View File

@ -113,7 +113,7 @@ public class RestTestClient implements Closeable {
//we don't really use the urls here, we rely on the client doing round-robin to touch all the nodes in the cluster
String method = restApi.getMethods().get(0);
String endpoint = restApi.getPaths().get(0);
Response response = restClient.performRequest(method, endpoint, Collections.emptyMap(), null);
Response response = restClient.performRequest(method, endpoint);
RestTestResponse restTestResponse = new RestTestResponse(response);
Object latestVersion = restTestResponse.evaluate("version.number");
if (latestVersion == null) {