Skip to content

Commit dabea4a

Browse files
committed
Switch more LLREST usage to new style Requests (#33171)
In #29623 we added `Request` object flavored requests to the low level REST client and in #30315 we deprecated the old `performRequest`s. In a long series of PRs I've changed all of the old style requests that I could find with `grep`. In this PR I change all requests that I could find by *removing* the deprecated methods from master. Note: I'm not actually removing all calls to the deprecated methods in ths commit. I'm just backporting the commit from master that removes all of the deprecated calls so future backports from master will be clean. There is *probably* still calls to the deprecated methods in the 6.x branch which is just fine because we'll only be dropping this methods from master.
1 parent ebbfddc commit dabea4a

File tree

7 files changed

+74
-75
lines changed

7 files changed

+74
-75
lines changed

modules/lang-mustache/src/test/java/org/elasticsearch/script/mustache/SearchTemplateWithoutContentIT.java

+3-2
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919

2020
package org.elasticsearch.script.mustache;
2121

22+
import org.elasticsearch.client.Request;
2223
import org.elasticsearch.client.ResponseException;
2324
import org.elasticsearch.test.rest.ESRestTestCase;
2425

@@ -30,14 +31,14 @@ public class SearchTemplateWithoutContentIT extends ESRestTestCase {
3031

3132
public void testSearchTemplateMissingBody() throws IOException {
3233
ResponseException responseException = expectThrows(ResponseException.class, () -> client().performRequest(
33-
randomBoolean() ? "POST" : "GET", "/_search/template"));
34+
new Request(randomBoolean() ? "POST" : "GET", "/_search/template")));
3435
assertEquals(400, responseException.getResponse().getStatusLine().getStatusCode());
3536
assertThat(responseException.getMessage(), containsString("request body or source parameter is required"));
3637
}
3738

3839
public void testMultiSearchTemplateMissingBody() throws IOException {
3940
ResponseException responseException = expectThrows(ResponseException.class, () -> client().performRequest(
40-
randomBoolean() ? "POST" : "GET", "/_msearch/template"));
41+
new Request(randomBoolean() ? "POST" : "GET", "/_msearch/template")));
4142
assertEquals(400, responseException.getResponse().getStatusLine().getStatusCode());
4243
assertThat(responseException.getMessage(), containsString("request body or source parameter is required"));
4344
}

modules/reindex/src/test/java/org/elasticsearch/index/reindex/ReindexWithoutContentIT.java

+2-1
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919

2020
package org.elasticsearch.index.reindex;
2121

22+
import org.elasticsearch.client.Request;
2223
import org.elasticsearch.client.ResponseException;
2324
import org.elasticsearch.test.rest.ESRestTestCase;
2425

@@ -30,7 +31,7 @@ public class ReindexWithoutContentIT extends ESRestTestCase {
3031

3132
public void testReindexMissingBody() throws IOException {
3233
ResponseException responseException = expectThrows(ResponseException.class, () -> client().performRequest(
33-
"POST", "/_reindex"));
34+
new Request("POST", "/_reindex")));
3435
assertEquals(400, responseException.getResponse().getStatusLine().getStatusCode());
3536
assertThat(responseException.getMessage(), containsString("request body is required"));
3637
}

modules/transport-netty4/src/test/java/org/elasticsearch/rest/Netty4BadRequestIT.java

+1-2
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,6 @@
3232

3333
import java.io.IOException;
3434
import java.nio.charset.Charset;
35-
import java.util.Collections;
3635
import java.util.Map;
3736

3837
import static org.elasticsearch.rest.RestStatus.BAD_REQUEST;
@@ -71,7 +70,7 @@ public void testBadRequest() throws IOException {
7170
final ResponseException e =
7271
expectThrows(
7372
ResponseException.class,
74-
() -> client().performRequest(randomFrom("GET", "POST", "PUT"), path, Collections.emptyMap()));
73+
() -> client().performRequest(new Request(randomFrom("GET", "POST", "PUT"), path)));
7574
assertThat(e.getResponse().getStatusLine().getStatusCode(), equalTo(BAD_REQUEST.getStatus()));
7675
assertThat(e, hasToString(containsString("too_long_frame_exception")));
7776
assertThat(e, hasToString(matches("An HTTP line is larger than \\d+ bytes")));

x-pack/plugin/monitoring/src/main/java/org/elasticsearch/xpack/monitoring/exporter/http/HttpExportBulk.java

+8-4
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,14 @@
55
*/
66
package org.elasticsearch.xpack.monitoring.exporter.http;
77

8-
import org.apache.http.HttpEntity;
9-
import org.apache.http.entity.ByteArrayEntity;
108
import org.apache.http.entity.ContentType;
9+
import org.apache.http.nio.entity.NByteArrayEntity;
1110
import org.apache.logging.log4j.Logger;
1211
import org.apache.logging.log4j.message.ParameterizedMessage;
1312
import org.apache.logging.log4j.util.Supplier;
1413
import org.apache.lucene.util.BytesRef;
1514
import org.elasticsearch.action.ActionListener;
15+
import org.elasticsearch.client.Request;
1616
import org.elasticsearch.client.Response;
1717
import org.elasticsearch.client.ResponseListener;
1818
import org.elasticsearch.client.RestClient;
@@ -94,9 +94,13 @@ public void doFlush(ActionListener<Void> listener) throws ExportException {
9494
if (payload == null) {
9595
listener.onFailure(new ExportException("unable to send documents because none were loaded for export bulk [{}]", name));
9696
} else if (payload.length != 0) {
97-
final HttpEntity body = new ByteArrayEntity(payload, ContentType.APPLICATION_JSON);
97+
final Request request = new Request("POST", "/_bulk");
98+
for (Map.Entry<String, String> param : params.entrySet()) {
99+
request.addParameter(param.getKey(), param.getValue());
100+
}
101+
request.setEntity(new NByteArrayEntity(payload, ContentType.APPLICATION_JSON));
98102

99-
client.performRequestAsync("POST", "/_bulk", params, body, new ResponseListener() {
103+
client.performRequestAsync(request, new ResponseListener() {
100104
@Override
101105
public void onSuccess(Response response) {
102106
try {

x-pack/plugin/security/src/test/java/org/elasticsearch/integration/AbstractPrivilegeTestCase.java

+39-43
Original file line numberDiff line numberDiff line change
@@ -7,97 +7,93 @@
77

88
import org.apache.http.HttpEntity;
99
import org.apache.http.StatusLine;
10-
import org.apache.http.entity.ContentType;
11-
import org.apache.http.entity.StringEntity;
12-
import org.apache.http.message.BasicHeader;
1310
import org.apache.http.util.EntityUtils;
11+
import org.elasticsearch.client.Request;
12+
import org.elasticsearch.client.RequestOptions;
1413
import org.elasticsearch.client.Response;
1514
import org.elasticsearch.client.ResponseException;
1615
import org.elasticsearch.common.settings.SecureString;
1716
import org.elasticsearch.test.SecuritySingleNodeTestCase;
1817
import org.elasticsearch.xpack.core.security.authc.support.UsernamePasswordToken;
1918

2019
import java.io.IOException;
21-
import java.util.HashMap;
2220
import java.util.Locale;
23-
import java.util.Map;
2421

2522
import static org.hamcrest.Matchers.containsString;
2623
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
2724
import static org.hamcrest.Matchers.is;
2825
import static org.hamcrest.Matchers.not;
2926

3027
/**
31-
* a helper class that contains a couple of HTTP helper methods
28+
* A helper class that contains a couple of HTTP helper methods.
3229
*/
3330
public abstract class AbstractPrivilegeTestCase extends SecuritySingleNodeTestCase {
3431

35-
protected void assertAccessIsAllowed(String user, String method, String uri, String body,
36-
Map<String, String> params) throws IOException {
37-
Response response = getRestClient().performRequest(method, uri, params, entityOrNull(body),
38-
new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER,
39-
UsernamePasswordToken.basicAuthHeaderValue(user, new SecureString("passwd".toCharArray()))));
32+
protected void assertAccessIsAllowed(String user, Request request) throws IOException {
33+
setUser(request, user);
34+
Response response = getRestClient().performRequest(request);
4035
StatusLine statusLine = response.getStatusLine();
41-
String message = String.format(Locale.ROOT, "%s %s: Expected no error got %s %s with body %s", method, uri,
42-
statusLine.getStatusCode(), statusLine.getReasonPhrase(), EntityUtils.toString(response.getEntity()));
36+
String message = String.format(Locale.ROOT, "%s %s: Expected no error got %s %s with body %s",
37+
request.getMethod(), request.getEndpoint(), statusLine.getStatusCode(),
38+
statusLine.getReasonPhrase(), EntityUtils.toString(response.getEntity()));
4339
assertThat(message, statusLine.getStatusCode(), is(not(greaterThanOrEqualTo(400))));
4440
}
4541

4642
protected void assertAccessIsAllowed(String user, String method, String uri, String body) throws IOException {
47-
assertAccessIsAllowed(user, method, uri, body, new HashMap<>());
43+
Request request = new Request(method, uri);
44+
request.setJsonEntity(body);
45+
assertAccessIsAllowed(user, request);
4846
}
4947

5048
protected void assertAccessIsAllowed(String user, String method, String uri) throws IOException {
51-
assertAccessIsAllowed(user, method, uri, null, new HashMap<>());
49+
assertAccessIsAllowed(user, new Request(method, uri));
5250
}
5351

54-
protected void assertAccessIsDenied(String user, String method, String uri, String body) throws IOException {
55-
assertAccessIsDenied(user, method, uri, body, new HashMap<>());
56-
}
57-
58-
protected void assertAccessIsDenied(String user, String method, String uri) throws IOException {
59-
assertAccessIsDenied(user, method, uri, null, new HashMap<>());
60-
}
61-
62-
protected void assertAccessIsDenied(String user, String method, String uri, String body,
63-
Map<String, String> params) throws IOException {
64-
ResponseException responseException = expectThrows(ResponseException.class,
65-
() -> getRestClient().performRequest(method, uri, params, entityOrNull(body),
66-
new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER,
67-
UsernamePasswordToken.basicAuthHeaderValue(user, new SecureString("passwd".toCharArray())))));
52+
protected void assertAccessIsDenied(String user, Request request) throws IOException {
53+
setUser(request, user);
54+
ResponseException responseException = expectThrows(ResponseException.class, () -> getRestClient().performRequest(request));
6855
StatusLine statusLine = responseException.getResponse().getStatusLine();
69-
String message = String.format(Locale.ROOT, "%s %s body %s: Expected 403, got %s %s with body %s", method, uri, body,
56+
String requestBody = request.getEntity() == null ? "" : "with body " + EntityUtils.toString(request.getEntity());
57+
String message = String.format(Locale.ROOT, "%s %s body %s: Expected 403, got %s %s with body %s",
58+
request.getMethod(), request.getEndpoint(), requestBody,
7059
statusLine.getStatusCode(), statusLine.getReasonPhrase(),
7160
EntityUtils.toString(responseException.getResponse().getEntity()));
7261
assertThat(message, statusLine.getStatusCode(), is(403));
7362
}
7463

64+
protected void assertAccessIsDenied(String user, String method, String uri, String body) throws IOException {
65+
Request request = new Request(method, uri);
66+
request.setJsonEntity(body);
67+
assertAccessIsDenied(user, request);
68+
}
7569

76-
protected void assertBodyHasAccessIsDenied(String user, String method, String uri, String body) throws IOException {
77-
assertBodyHasAccessIsDenied(user, method, uri, body, new HashMap<>());
70+
protected void assertAccessIsDenied(String user, String method, String uri) throws IOException {
71+
assertAccessIsDenied(user, new Request(method, uri));
7872
}
7973

8074
/**
8175
* Like {@code assertAcessIsDenied}, but for _bulk requests since the entire
8276
* request will not be failed, just the individual ones
8377
*/
84-
protected void assertBodyHasAccessIsDenied(String user, String method, String uri, String body,
85-
Map<String, String> params) throws IOException {
86-
Response resp = getRestClient().performRequest(method, uri, params, entityOrNull(body),
87-
new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER,
88-
UsernamePasswordToken.basicAuthHeaderValue(user, new SecureString("passwd".toCharArray()))));
78+
protected void assertBodyHasAccessIsDenied(String user, Request request) throws IOException {
79+
setUser(request, user);
80+
Response resp = getRestClient().performRequest(request);
8981
StatusLine statusLine = resp.getStatusLine();
9082
assertThat(statusLine.getStatusCode(), is(200));
9183
HttpEntity bodyEntity = resp.getEntity();
9284
String bodyStr = EntityUtils.toString(bodyEntity);
9385
assertThat(bodyStr, containsString("unauthorized for user [" + user + "]"));
9486
}
9587

96-
private static HttpEntity entityOrNull(String body) {
97-
HttpEntity entity = null;
98-
if (body != null) {
99-
entity = new StringEntity(body, ContentType.APPLICATION_JSON);
100-
}
101-
return entity;
88+
protected void assertBodyHasAccessIsDenied(String user, String method, String uri, String body) throws IOException {
89+
Request request = new Request(method, uri);
90+
request.setJsonEntity(body);
91+
assertBodyHasAccessIsDenied(user, request);
92+
}
93+
94+
private void setUser(Request request, String user) {
95+
RequestOptions.Builder options = RequestOptions.DEFAULT.toBuilder();
96+
options.addHeader("Authorization", UsernamePasswordToken.basicAuthHeaderValue(user, new SecureString("passwd".toCharArray())));
97+
request.setOptions(options);
10298
}
10399
}

x-pack/plugin/security/src/test/java/org/elasticsearch/integration/ClusterPrivilegeTests.java

+12-10
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
package org.elasticsearch.integration;
77

88
import org.elasticsearch.action.admin.cluster.snapshots.status.SnapshotsStatusResponse;
9+
import org.elasticsearch.client.Request;
910
import org.elasticsearch.cluster.SnapshotsInProgress;
1011
import org.elasticsearch.common.Strings;
1112
import org.elasticsearch.common.network.NetworkModule;
@@ -16,9 +17,7 @@
1617
import org.junit.BeforeClass;
1718

1819
import java.nio.file.Path;
19-
import java.util.Map;
2020

21-
import static java.util.Collections.singletonMap;
2221
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
2322
import static org.hamcrest.Matchers.is;
2423

@@ -129,10 +128,12 @@ public void testThatSnapshotAndRestore() throws Exception {
129128
assertAccessIsDenied("user_c", "PUT", "/_snapshot/my-repo", repoJson);
130129
assertAccessIsAllowed("user_a", "PUT", "/_snapshot/my-repo", repoJson);
131130

132-
Map<String, String> params = singletonMap("refresh", "true");
133-
assertAccessIsDenied("user_a", "PUT", "/someindex/bar/1", "{ \"name\" : \"elasticsearch\" }", params);
134-
assertAccessIsDenied("user_b", "PUT", "/someindex/bar/1", "{ \"name\" : \"elasticsearch\" }", params);
135-
assertAccessIsAllowed("user_c", "PUT", "/someindex/bar/1", "{ \"name\" : \"elasticsearch\" }", params);
131+
Request createBar = new Request("PUT", "/someindex/bar/1");
132+
createBar.setJsonEntity("{ \"name\" : \"elasticsearch\" }");
133+
createBar.addParameter("refresh", "true");
134+
assertAccessIsDenied("user_a", createBar);
135+
assertAccessIsDenied("user_b", createBar);
136+
assertAccessIsAllowed("user_c", createBar);
136137

137138
assertAccessIsDenied("user_b", "PUT", "/_snapshot/my-repo/my-snapshot", "{ \"indices\": \"someindex\" }");
138139
assertAccessIsDenied("user_c", "PUT", "/_snapshot/my-repo/my-snapshot", "{ \"indices\": \"someindex\" }");
@@ -149,10 +150,11 @@ public void testThatSnapshotAndRestore() throws Exception {
149150
assertAccessIsDenied("user_b", "DELETE", "/someindex");
150151
assertAccessIsAllowed("user_c", "DELETE", "/someindex");
151152

152-
params = singletonMap("wait_for_completion", "true");
153-
assertAccessIsDenied("user_b", "POST", "/_snapshot/my-repo/my-snapshot/_restore", null, params);
154-
assertAccessIsDenied("user_c", "POST", "/_snapshot/my-repo/my-snapshot/_restore", null, params);
155-
assertAccessIsAllowed("user_a", "POST", "/_snapshot/my-repo/my-snapshot/_restore", null, params);
153+
Request restoreSnapshotRequest = new Request("POST", "/_snapshot/my-repo/my-snapshot/_restore");
154+
restoreSnapshotRequest.addParameter("wait_for_completion", "true");
155+
assertAccessIsDenied("user_b", restoreSnapshotRequest);
156+
assertAccessIsDenied("user_c", restoreSnapshotRequest);
157+
assertAccessIsAllowed("user_a", restoreSnapshotRequest);
156158

157159
assertAccessIsDenied("user_a", "GET", "/someindex/bar/1");
158160
assertAccessIsDenied("user_b", "GET", "/someindex/bar/1");

x-pack/plugin/security/src/test/java/org/elasticsearch/integration/IndexPrivilegeTests.java

+9-13
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,8 @@
1515
import org.elasticsearch.xpack.core.security.authc.support.UsernamePasswordToken;
1616
import org.junit.Before;
1717

18-
import java.util.Collections;
1918
import java.util.Locale;
20-
import java.util.Map;
2119

22-
import static java.util.Collections.singletonMap;
2320
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoTimeout;
2421
import static org.hamcrest.Matchers.is;
2522

@@ -147,11 +144,12 @@ protected String configUsersRoles() {
147144
@Before
148145
public void insertBaseDocumentsAsAdmin() throws Exception {
149146
// indices: a,b,c,abc
150-
Map<String, String> params = singletonMap("refresh", "true");
151-
assertAccessIsAllowed("admin", "PUT", "/a/foo/1", jsonDoc, params);
152-
assertAccessIsAllowed("admin", "PUT", "/b/foo/1", jsonDoc, params);
153-
assertAccessIsAllowed("admin", "PUT", "/c/foo/1", jsonDoc, params);
154-
assertAccessIsAllowed("admin", "PUT", "/abc/foo/1", jsonDoc, params);
147+
for (String index : new String[] {"a", "b", "c", "abc"}) {
148+
Request request = new Request("PUT", "/" + index + "/foo/1");
149+
request.setJsonEntity(jsonDoc);
150+
request.addParameter("refresh", "true");
151+
assertAccessIsAllowed("admin", request);
152+
}
155153
}
156154

157155
private static String randomIndex() {
@@ -406,8 +404,6 @@ public void testThatUnknownUserIsRejectedProperly() throws Exception {
406404
}
407405

408406
private void assertUserExecutes(String user, String action, String index, boolean userIsAllowed) throws Exception {
409-
Map<String, String> refreshParams = Collections.emptyMap();//singletonMap("refresh", "true");
410-
411407
switch (action) {
412408
case "all" :
413409
if (userIsAllowed) {
@@ -442,7 +438,7 @@ private void assertUserExecutes(String user, String action, String index, boolea
442438
assertAccessIsAllowed(user, "POST", "/" + index + "/_open");
443439
assertAccessIsAllowed(user, "POST", "/" + index + "/_cache/clear");
444440
// indexing a document to have the mapping available, and wait for green state to make sure index is created
445-
assertAccessIsAllowed("admin", "PUT", "/" + index + "/foo/1", jsonDoc, refreshParams);
441+
assertAccessIsAllowed("admin", "PUT", "/" + index + "/foo/1", jsonDoc);
446442
assertNoTimeout(client().admin().cluster().prepareHealth(index).setWaitForGreenStatus().get());
447443
assertAccessIsAllowed(user, "GET", "/" + index + "/_mapping/foo/field/name");
448444
assertAccessIsAllowed(user, "GET", "/" + index + "/_settings");
@@ -539,8 +535,8 @@ private void assertUserExecutes(String user, String action, String index, boolea
539535

540536
case "delete" :
541537
String jsonDoc = "{ \"name\" : \"docToDelete\"}";
542-
assertAccessIsAllowed("admin", "PUT", "/" + index + "/foo/docToDelete", jsonDoc, refreshParams);
543-
assertAccessIsAllowed("admin", "PUT", "/" + index + "/foo/docToDelete2", jsonDoc, refreshParams);
538+
assertAccessIsAllowed("admin", "PUT", "/" + index + "/foo/docToDelete", jsonDoc);
539+
assertAccessIsAllowed("admin", "PUT", "/" + index + "/foo/docToDelete2", jsonDoc);
544540
if (userIsAllowed) {
545541
assertAccessIsAllowed(user, "DELETE", "/" + index + "/foo/docToDelete");
546542
} else {

0 commit comments

Comments
 (0)