Switch many QA projects to use new style requests (#30574)

In #29623 we added `Request` object flavored requests to the low level
REST client and in #30315 we deprecated the the old requests. This
changes many calls in the `qa` projects to use the new version.
This commit is contained in:
Nik Everett 2018-05-15 17:48:47 -04:00 committed by GitHub
parent abc06d5b79
commit 6695d11a97
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 144 additions and 117 deletions

View File

@ -35,6 +35,7 @@ import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchScrollRequest; import org.elasticsearch.action.search.SearchScrollRequest;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response; import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseException; import org.elasticsearch.client.ResponseException;
import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClient;
@ -134,7 +135,7 @@ public class CrossClusterSearchUnavailableClusterIT extends ESRestTestCase {
for (int i = 0; i < 10; i++) { for (int i = 0; i < 10; i++) {
restHighLevelClient.index(new IndexRequest("index", "doc", String.valueOf(i)).source("field", "value")); restHighLevelClient.index(new IndexRequest("index", "doc", String.valueOf(i)).source("field", "value"));
} }
Response refreshResponse = client().performRequest("POST", "/index/_refresh"); Response refreshResponse = client().performRequest(new Request("POST", "/index/_refresh"));
assertEquals(200, refreshResponse.getStatusLine().getStatusCode()); assertEquals(200, refreshResponse.getStatusLine().getStatusCode());
{ {
@ -223,10 +224,11 @@ public class CrossClusterSearchUnavailableClusterIT extends ESRestTestCase {
{ {
//check that skip_unavailable alone cannot be set //check that skip_unavailable alone cannot be set
HttpEntity clusterSettingsEntity = buildUpdateSettingsRequestBody( Request request = new Request("PUT", "/_cluster/settings");
Collections.singletonMap("skip_unavailable", randomBoolean())); request.setEntity(buildUpdateSettingsRequestBody(
Collections.singletonMap("skip_unavailable", randomBoolean())));
ResponseException responseException = expectThrows(ResponseException.class, ResponseException responseException = expectThrows(ResponseException.class,
() -> client().performRequest("PUT", "/_cluster/settings", Collections.emptyMap(), clusterSettingsEntity)); () -> client().performRequest(request));
assertEquals(400, responseException.getResponse().getStatusLine().getStatusCode()); assertEquals(400, responseException.getResponse().getStatusLine().getStatusCode());
assertThat(responseException.getMessage(), assertThat(responseException.getMessage(),
containsString("Missing required setting [search.remote.remote1.seeds] " + containsString("Missing required setting [search.remote.remote1.seeds] " +
@ -240,9 +242,10 @@ public class CrossClusterSearchUnavailableClusterIT extends ESRestTestCase {
{ {
//check that seeds cannot be reset alone if skip_unavailable is set //check that seeds cannot be reset alone if skip_unavailable is set
HttpEntity clusterSettingsEntity = buildUpdateSettingsRequestBody(Collections.singletonMap("seeds", null)); Request request = new Request("PUT", "/_cluster/settings");
request.setEntity(buildUpdateSettingsRequestBody(Collections.singletonMap("seeds", null)));
ResponseException responseException = expectThrows(ResponseException.class, ResponseException responseException = expectThrows(ResponseException.class,
() -> client().performRequest("PUT", "/_cluster/settings", Collections.emptyMap(), clusterSettingsEntity)); () -> client().performRequest(request));
assertEquals(400, responseException.getResponse().getStatusLine().getStatusCode()); assertEquals(400, responseException.getResponse().getStatusLine().getStatusCode());
assertThat(responseException.getMessage(), containsString("Missing required setting [search.remote.remote1.seeds] " + assertThat(responseException.getMessage(), containsString("Missing required setting [search.remote.remote1.seeds] " +
"for setting [search.remote.remote1.skip_unavailable]")); "for setting [search.remote.remote1.skip_unavailable]"));
@ -284,8 +287,9 @@ public class CrossClusterSearchUnavailableClusterIT extends ESRestTestCase {
private static void updateRemoteClusterSettings(Map<String, Object> settings) throws IOException { private static void updateRemoteClusterSettings(Map<String, Object> settings) throws IOException {
HttpEntity clusterSettingsEntity = buildUpdateSettingsRequestBody(settings); Request request = new Request("PUT", "/_cluster/settings");
Response response = client().performRequest("PUT", "/_cluster/settings", Collections.emptyMap(), clusterSettingsEntity); request.setEntity(buildUpdateSettingsRequestBody(settings));
Response response = client().performRequest(request);
assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals(200, response.getStatusLine().getStatusCode());
} }

View File

@ -21,6 +21,7 @@ package org.elasticsearch.qa.die_with_dignity;
import org.apache.http.ConnectionClosedException; import org.apache.http.ConnectionClosedException;
import org.apache.lucene.util.Constants; import org.apache.lucene.util.Constants;
import org.elasticsearch.client.Request;
import org.elasticsearch.common.io.PathUtils; import org.elasticsearch.common.io.PathUtils;
import org.elasticsearch.test.rest.ESRestTestCase; import org.elasticsearch.test.rest.ESRestTestCase;
import org.hamcrest.Matcher; import org.hamcrest.Matcher;
@ -51,7 +52,8 @@ public class DieWithDignityIT extends ESRestTestCase {
assertThat(pidFileLines, hasSize(1)); assertThat(pidFileLines, hasSize(1));
final int pid = Integer.parseInt(pidFileLines.get(0)); final int pid = Integer.parseInt(pidFileLines.get(0));
Files.delete(pidFile); Files.delete(pidFile);
IOException e = expectThrows(IOException.class, () -> client().performRequest("GET", "/_die_with_dignity")); IOException e = expectThrows(IOException.class,
() -> client().performRequest(new Request("GET", "/_die_with_dignity")));
Matcher<IOException> failureMatcher = instanceOf(ConnectionClosedException.class); Matcher<IOException> failureMatcher = instanceOf(ConnectionClosedException.class);
if (Constants.WINDOWS) { if (Constants.WINDOWS) {
/* /*

View File

@ -19,9 +19,8 @@
package org.elasticsearch.backwards; package org.elasticsearch.backwards;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.elasticsearch.Version; import org.elasticsearch.Version;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response; import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClient;
import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.metadata.IndexMetaData;
@ -34,25 +33,21 @@ import org.elasticsearch.test.rest.yaml.ObjectPath;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static com.carrotsearch.randomizedtesting.RandomizedTest.randomAsciiOfLength;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonMap;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
public class IndexingIT extends ESRestTestCase { public class IndexingIT extends ESRestTestCase {
private int indexDocs(String index, final int idStart, final int numDocs) throws IOException { private int indexDocs(String index, final int idStart, final int numDocs) throws IOException {
for (int i = 0; i < numDocs; i++) { for (int i = 0; i < numDocs; i++) {
final int id = idStart + i; final int id = idStart + i;
assertOK(client().performRequest("PUT", index + "/test/" + id, emptyMap(), Request request = new Request("PUT", index + "/test/" + id);
new StringEntity("{\"test\": \"test_" + randomAsciiOfLength(2) + "\"}", ContentType.APPLICATION_JSON))); request.setJsonEntity("{\"test\": \"test_" + randomAlphaOfLength(2) + "\"}");
assertOK(client().performRequest(request));
} }
return numDocs; return numDocs;
} }
@ -105,7 +100,7 @@ public class IndexingIT extends ESRestTestCase {
logger.info("allowing shards on all nodes"); logger.info("allowing shards on all nodes");
updateIndexSettings(index, Settings.builder().putNull("index.routing.allocation.include._name")); updateIndexSettings(index, Settings.builder().putNull("index.routing.allocation.include._name"));
ensureGreen(index); ensureGreen(index);
assertOK(client().performRequest("POST", index + "/_refresh")); assertOK(client().performRequest(new Request("POST", index + "/_refresh")));
List<Shard> shards = buildShards(index, nodes, newNodeClient); List<Shard> shards = buildShards(index, nodes, newNodeClient);
Shard primary = buildShards(index, nodes, newNodeClient).stream().filter(Shard::isPrimary).findFirst().get(); Shard primary = buildShards(index, nodes, newNodeClient).stream().filter(Shard::isPrimary).findFirst().get();
logger.info("primary resolved to: " + primary.getNode().getNodeName()); logger.info("primary resolved to: " + primary.getNode().getNodeName());
@ -117,7 +112,7 @@ public class IndexingIT extends ESRestTestCase {
nUpdates = randomIntBetween(minUpdates, maxUpdates); nUpdates = randomIntBetween(minUpdates, maxUpdates);
logger.info("indexing docs with [{}] concurrent updates after allowing shards on all nodes", nUpdates); logger.info("indexing docs with [{}] concurrent updates after allowing shards on all nodes", nUpdates);
final int finalVersionForDoc2 = indexDocWithConcurrentUpdates(index, 2, nUpdates); final int finalVersionForDoc2 = indexDocWithConcurrentUpdates(index, 2, nUpdates);
assertOK(client().performRequest("POST", index + "/_refresh")); assertOK(client().performRequest(new Request("POST", index + "/_refresh")));
shards = buildShards(index, nodes, newNodeClient); shards = buildShards(index, nodes, newNodeClient);
primary = shards.stream().filter(Shard::isPrimary).findFirst().get(); primary = shards.stream().filter(Shard::isPrimary).findFirst().get();
logger.info("primary resolved to: " + primary.getNode().getNodeName()); logger.info("primary resolved to: " + primary.getNode().getNodeName());
@ -133,7 +128,7 @@ public class IndexingIT extends ESRestTestCase {
nUpdates = randomIntBetween(minUpdates, maxUpdates); nUpdates = randomIntBetween(minUpdates, maxUpdates);
logger.info("indexing docs with [{}] concurrent updates after moving primary", nUpdates); logger.info("indexing docs with [{}] concurrent updates after moving primary", nUpdates);
final int finalVersionForDoc3 = indexDocWithConcurrentUpdates(index, 3, nUpdates); final int finalVersionForDoc3 = indexDocWithConcurrentUpdates(index, 3, nUpdates);
assertOK(client().performRequest("POST", index + "/_refresh")); assertOK(client().performRequest(new Request("POST", index + "/_refresh")));
shards = buildShards(index, nodes, newNodeClient); shards = buildShards(index, nodes, newNodeClient);
for (Shard shard : shards) { for (Shard shard : shards) {
assertVersion(index, 3, "_only_nodes:" + shard.getNode().getNodeName(), finalVersionForDoc3); assertVersion(index, 3, "_only_nodes:" + shard.getNode().getNodeName(), finalVersionForDoc3);
@ -146,7 +141,7 @@ public class IndexingIT extends ESRestTestCase {
nUpdates = randomIntBetween(minUpdates, maxUpdates); nUpdates = randomIntBetween(minUpdates, maxUpdates);
logger.info("indexing doc with [{}] concurrent updates after setting number of replicas to 0", nUpdates); logger.info("indexing doc with [{}] concurrent updates after setting number of replicas to 0", nUpdates);
final int finalVersionForDoc4 = indexDocWithConcurrentUpdates(index, 4, nUpdates); final int finalVersionForDoc4 = indexDocWithConcurrentUpdates(index, 4, nUpdates);
assertOK(client().performRequest("POST", index + "/_refresh")); assertOK(client().performRequest(new Request("POST", index + "/_refresh")));
shards = buildShards(index, nodes, newNodeClient); shards = buildShards(index, nodes, newNodeClient);
for (Shard shard : shards) { for (Shard shard : shards) {
assertVersion(index, 4, "_only_nodes:" + shard.getNode().getNodeName(), finalVersionForDoc4); assertVersion(index, 4, "_only_nodes:" + shard.getNode().getNodeName(), finalVersionForDoc4);
@ -159,7 +154,7 @@ public class IndexingIT extends ESRestTestCase {
nUpdates = randomIntBetween(minUpdates, maxUpdates); nUpdates = randomIntBetween(minUpdates, maxUpdates);
logger.info("indexing doc with [{}] concurrent updates after setting number of replicas to 1", nUpdates); logger.info("indexing doc with [{}] concurrent updates after setting number of replicas to 1", nUpdates);
final int finalVersionForDoc5 = indexDocWithConcurrentUpdates(index, 5, nUpdates); final int finalVersionForDoc5 = indexDocWithConcurrentUpdates(index, 5, nUpdates);
assertOK(client().performRequest("POST", index + "/_refresh")); assertOK(client().performRequest(new Request("POST", index + "/_refresh")));
shards = buildShards(index, nodes, newNodeClient); shards = buildShards(index, nodes, newNodeClient);
for (Shard shard : shards) { for (Shard shard : shards) {
assertVersion(index, 5, "_only_nodes:" + shard.getNode().getNodeName(), finalVersionForDoc5); assertVersion(index, 5, "_only_nodes:" + shard.getNode().getNodeName(), finalVersionForDoc5);
@ -191,7 +186,7 @@ public class IndexingIT extends ESRestTestCase {
logger.info("allowing shards on all nodes"); logger.info("allowing shards on all nodes");
updateIndexSettings(index, Settings.builder().putNull("index.routing.allocation.include._name")); updateIndexSettings(index, Settings.builder().putNull("index.routing.allocation.include._name"));
ensureGreen(index); ensureGreen(index);
assertOK(client().performRequest("POST", index + "/_refresh")); assertOK(client().performRequest(new Request("POST", index + "/_refresh")));
for (final String bwcName : bwcNamesList) { for (final String bwcName : bwcNamesList) {
assertCount(index, "_only_nodes:" + bwcName, numDocs); assertCount(index, "_only_nodes:" + bwcName, numDocs);
} }
@ -222,7 +217,7 @@ public class IndexingIT extends ESRestTestCase {
logger.info("setting number of replicas to 1"); logger.info("setting number of replicas to 1");
updateIndexSettings(index, Settings.builder().put("index.number_of_replicas", 1)); updateIndexSettings(index, Settings.builder().put("index.number_of_replicas", 1));
ensureGreen(index); ensureGreen(index);
assertOK(client().performRequest("POST", index + "/_refresh")); assertOK(client().performRequest(new Request("POST", index + "/_refresh")));
for (Shard shard : buildShards(index, nodes, newNodeClient)) { for (Shard shard : buildShards(index, nodes, newNodeClient)) {
assertCount(index, "_only_nodes:" + shard.node.nodeName, numDocs); assertCount(index, "_only_nodes:" + shard.node.nodeName, numDocs);
@ -237,7 +232,8 @@ public class IndexingIT extends ESRestTestCase {
logger.info("cluster discovered: {}", nodes.toString()); logger.info("cluster discovered: {}", nodes.toString());
// Create the repository before taking the snapshot. // Create the repository before taking the snapshot.
String repoConfig = Strings Request request = new Request("PUT", "/_snapshot/repo");
request.setJsonEntity(Strings
.toString(JsonXContent.contentBuilder() .toString(JsonXContent.contentBuilder()
.startObject() .startObject()
.field("type", "fs") .field("type", "fs")
@ -245,12 +241,9 @@ public class IndexingIT extends ESRestTestCase {
.field("compress", randomBoolean()) .field("compress", randomBoolean())
.field("location", System.getProperty("tests.path.repo")) .field("location", System.getProperty("tests.path.repo"))
.endObject() .endObject()
.endObject()); .endObject()));
assertOK( assertOK(client().performRequest(request));
client().performRequest("PUT", "/_snapshot/repo", emptyMap(),
new StringEntity(repoConfig, ContentType.APPLICATION_JSON))
);
String bwcNames = nodes.getBWCNodes().stream().map(Node::getNodeName).collect(Collectors.joining(",")); String bwcNames = nodes.getBWCNodes().stream().map(Node::getNodeName).collect(Collectors.joining(","));
@ -264,34 +257,36 @@ public class IndexingIT extends ESRestTestCase {
createIndex(index, settings.build()); createIndex(index, settings.build());
indexDocs(index, 0, between(50, 100)); indexDocs(index, 0, between(50, 100));
ensureGreen(index); ensureGreen(index);
assertOK(client().performRequest("POST", index + "/_refresh")); assertOK(client().performRequest(new Request("POST", index + "/_refresh")));
assertOK( request = new Request("PUT", "/_snapshot/repo/bwc-snapshot");
client().performRequest("PUT", "/_snapshot/repo/bwc-snapshot", singletonMap("wait_for_completion", "true"), request.addParameter("wait_for_completion", "true");
new StringEntity("{\"indices\": \"" + index + "\"}", ContentType.APPLICATION_JSON)) request.setJsonEntity("{\"indices\": \"" + index + "\"}");
); assertOK(client().performRequest(request));
// Allocating shards on all nodes, taking snapshots should happen on all nodes. // Allocating shards on all nodes, taking snapshots should happen on all nodes.
updateIndexSettings(index, Settings.builder().putNull("index.routing.allocation.include._name")); updateIndexSettings(index, Settings.builder().putNull("index.routing.allocation.include._name"));
ensureGreen(index); ensureGreen(index);
assertOK(client().performRequest("POST", index + "/_refresh")); assertOK(client().performRequest(new Request("POST", index + "/_refresh")));
assertOK( request = new Request("PUT", "/_snapshot/repo/mixed-snapshot");
client().performRequest("PUT", "/_snapshot/repo/mixed-snapshot", singletonMap("wait_for_completion", "true"), request.addParameter("wait_for_completion", "true");
new StringEntity("{\"indices\": \"" + index + "\"}", ContentType.APPLICATION_JSON)) request.setJsonEntity("{\"indices\": \"" + index + "\"}");
);
} }
private void assertCount(final String index, final String preference, final int expectedCount) throws IOException { private void assertCount(final String index, final String preference, final int expectedCount) throws IOException {
final Response response = client().performRequest("GET", index + "/_count", Collections.singletonMap("preference", preference)); Request request = new Request("GET", index + "/_count");
request.addParameter("preference", preference);
final Response response = client().performRequest(request);
assertOK(response); assertOK(response);
final int actualCount = Integer.parseInt(ObjectPath.createFromResponse(response).evaluate("count").toString()); final int actualCount = Integer.parseInt(ObjectPath.createFromResponse(response).evaluate("count").toString());
assertThat(actualCount, equalTo(expectedCount)); assertThat(actualCount, equalTo(expectedCount));
} }
private void assertVersion(final String index, final int docId, final String preference, final int expectedVersion) throws IOException { private void assertVersion(final String index, final int docId, final String preference, final int expectedVersion) throws IOException {
final Response response = client().performRequest("GET", index + "/test/" + docId, Request request = new Request("GET", index + "/test/" + docId);
Collections.singletonMap("preference", preference)); request.addParameter("preference", preference);
final Response response = client().performRequest(request);
assertOK(response); assertOK(response);
final int actualVersion = Integer.parseInt(ObjectPath.createFromResponse(response).evaluate("_version").toString()); final int actualVersion = Integer.parseInt(ObjectPath.createFromResponse(response).evaluate("_version").toString());
assertThat("version mismatch for doc [" + docId + "] preference [" + preference + "]", actualVersion, equalTo(expectedVersion)); assertThat("version mismatch for doc [" + docId + "] preference [" + preference + "]", actualVersion, equalTo(expectedVersion));
@ -323,7 +318,9 @@ public class IndexingIT extends ESRestTestCase {
} }
private List<Shard> buildShards(String index, Nodes nodes, RestClient client) throws IOException { private List<Shard> buildShards(String index, Nodes nodes, RestClient client) throws IOException {
Response response = client.performRequest("GET", index + "/_stats", singletonMap("level", "shards")); Request request = new Request("GET", index + "/_stats");
request.addParameter("level", "shards");
Response response = client.performRequest(request);
List<Object> shardStats = ObjectPath.createFromResponse(response).evaluate("indices." + index + ".shards.0"); List<Object> shardStats = ObjectPath.createFromResponse(response).evaluate("indices." + index + ".shards.0");
ArrayList<Shard> shards = new ArrayList<>(); ArrayList<Shard> shards = new ArrayList<>();
for (Object shard : shardStats) { for (Object shard : shardStats) {
@ -341,7 +338,7 @@ public class IndexingIT extends ESRestTestCase {
} }
private Nodes buildNodeAndVersions() throws IOException { private Nodes buildNodeAndVersions() throws IOException {
Response response = client().performRequest("GET", "_nodes"); Response response = client().performRequest(new Request("GET", "_nodes"));
ObjectPath objectPath = ObjectPath.createFromResponse(response); ObjectPath objectPath = ObjectPath.createFromResponse(response);
Map<String, Object> nodesAsMap = objectPath.evaluate("nodes"); Map<String, Object> nodesAsMap = objectPath.evaluate("nodes");
Nodes nodes = new Nodes(); Nodes nodes = new Nodes();
@ -352,7 +349,7 @@ public class IndexingIT extends ESRestTestCase {
Version.fromString(objectPath.evaluate("nodes." + id + ".version")), Version.fromString(objectPath.evaluate("nodes." + id + ".version")),
HttpHost.create(objectPath.evaluate("nodes." + id + ".http.publish_address")))); HttpHost.create(objectPath.evaluate("nodes." + id + ".http.publish_address"))));
} }
response = client().performRequest("GET", "_cluster/state"); response = client().performRequest(new Request("GET", "_cluster/state"));
nodes.setMasterNodeId(ObjectPath.createFromResponse(response).evaluate("master_node")); nodes.setMasterNodeId(ObjectPath.createFromResponse(response).evaluate("master_node"));
return nodes; return nodes;
} }

View File

@ -19,10 +19,9 @@
package org.elasticsearch.bwc; package org.elasticsearch.bwc;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
import org.elasticsearch.Version; import org.elasticsearch.Version;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response; import org.elasticsearch.client.Response;
import org.elasticsearch.common.Booleans; import org.elasticsearch.common.Booleans;
import org.elasticsearch.common.Strings; import org.elasticsearch.common.Strings;
@ -189,13 +188,15 @@ public class QueryBuilderBWCIT extends ESRestTestCase {
mappingsAndSettings.endObject(); mappingsAndSettings.endObject();
} }
mappingsAndSettings.endObject(); mappingsAndSettings.endObject();
Response rsp = client().performRequest("PUT", "/" + index, Collections.emptyMap(), Request request = new Request("PUT", "/" + index);
new StringEntity(Strings.toString(mappingsAndSettings), ContentType.APPLICATION_JSON)); request.setJsonEntity(Strings.toString(mappingsAndSettings));
Response rsp = client().performRequest(request);
assertEquals(200, rsp.getStatusLine().getStatusCode()); assertEquals(200, rsp.getStatusLine().getStatusCode());
for (int i = 0; i < CANDIDATES.size(); i++) { for (int i = 0; i < CANDIDATES.size(); i++) {
rsp = client().performRequest("PUT", "/" + index + "/doc/" + Integer.toString(i), Collections.emptyMap(), request = new Request("PUT", "/" + index + "/doc/" + Integer.toString(i));
new StringEntity((String) CANDIDATES.get(i)[0], ContentType.APPLICATION_JSON)); request.setJsonEntity((String) CANDIDATES.get(i)[0]);
rsp = client().performRequest(request);
assertEquals(201, rsp.getStatusLine().getStatusCode()); assertEquals(201, rsp.getStatusLine().getStatusCode());
} }
} else { } else {
@ -204,9 +205,10 @@ public class QueryBuilderBWCIT extends ESRestTestCase {
for (int i = 0; i < CANDIDATES.size(); i++) { for (int i = 0; i < CANDIDATES.size(); i++) {
QueryBuilder expectedQueryBuilder = (QueryBuilder) CANDIDATES.get(i)[1]; QueryBuilder expectedQueryBuilder = (QueryBuilder) CANDIDATES.get(i)[1];
Response rsp = client().performRequest("GET", "/" + index + "/_search", Collections.emptyMap(), Request request = new Request("GET", "/" + index + "/_search");
new StringEntity("{\"query\": {\"ids\": {\"values\": [\"" + Integer.toString(i) + "\"]}}, " + request.setJsonEntity("{\"query\": {\"ids\": {\"values\": [\"" + Integer.toString(i) + "\"]}}, " +
"\"docvalue_fields\" : [\"query.query_builder_field\"]}", ContentType.APPLICATION_JSON)); "\"docvalue_fields\" : [\"query.query_builder_field\"]}");
Response rsp = client().performRequest(request);
assertEquals(200, rsp.getStatusLine().getStatusCode()); assertEquals(200, rsp.getStatusLine().getStatusCode());
Map<?, ?> hitRsp = (Map<?, ?>) ((List<?>) ((Map<?, ?>)toMap(rsp).get("hits")).get("hits")).get(0); Map<?, ?> hitRsp = (Map<?, ?>) ((List<?>) ((Map<?, ?>)toMap(rsp).get("hits")).get("hits")).get(0);
String queryBuilderStr = (String) ((List<?>) ((Map<?, ?>) hitRsp.get("fields")).get("query.query_builder_field")).get(0); String queryBuilderStr = (String) ((List<?>) ((Map<?, ?>) hitRsp.get("fields")).get("query.query_builder_field")).get(0);

View File

@ -31,11 +31,11 @@ import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.ActionFilter; import org.elasticsearch.action.support.ActionFilter;
import org.elasticsearch.action.termvectors.MultiTermVectorsRequest; import org.elasticsearch.action.termvectors.MultiTermVectorsRequest;
import org.elasticsearch.client.Client; import org.elasticsearch.client.Client;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response; import org.elasticsearch.client.Response;
import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.Strings; import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
import org.elasticsearch.common.network.NetworkModule;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.NamedXContentRegistry; import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.common.xcontent.XContentType;
@ -221,8 +221,10 @@ public class ContextAndHeaderTransportIT extends HttpSmokeTestCase {
public void testThatRelevantHttpHeadersBecomeRequestHeaders() throws IOException { public void testThatRelevantHttpHeadersBecomeRequestHeaders() throws IOException {
final String IRRELEVANT_HEADER = "SomeIrrelevantHeader"; final String IRRELEVANT_HEADER = "SomeIrrelevantHeader";
Response response = getRestClient().performRequest("GET", "/" + queryIndex + "/_search", Request request = new Request("GET", "/" + queryIndex + "/_search");
new BasicHeader(CUSTOM_HEADER, randomHeaderValue), new BasicHeader(IRRELEVANT_HEADER, randomHeaderValue)); request.setHeaders(new BasicHeader(CUSTOM_HEADER, randomHeaderValue),
new BasicHeader(IRRELEVANT_HEADER, randomHeaderValue));
Response response = getRestClient().performRequest(request);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
List<RequestAndHeaders> searchRequests = getRequests(SearchRequest.class); List<RequestAndHeaders> searchRequests = getRequests(SearchRequest.class);
assertThat(searchRequests, hasSize(greaterThan(0))); assertThat(searchRequests, hasSize(greaterThan(0)));

View File

@ -20,8 +20,8 @@
package org.elasticsearch.http; package org.elasticsearch.http;
import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicHeader;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response; import org.elasticsearch.client.Response;
import org.elasticsearch.test.ESIntegTestCase;
import java.io.IOException; import java.io.IOException;
@ -32,15 +32,16 @@ public class CorsNotSetIT extends HttpSmokeTestCase {
public void testCorsSettingDefaultBehaviourDoesNotReturnAnything() throws IOException { public void testCorsSettingDefaultBehaviourDoesNotReturnAnything() throws IOException {
String corsValue = "http://localhost:9200"; String corsValue = "http://localhost:9200";
Response response = getRestClient().performRequest("GET", "/", Request request = new Request("GET", "/");
new BasicHeader("User-Agent", "Mozilla Bar"), new BasicHeader("Origin", corsValue)); request.setHeaders(new BasicHeader("User-Agent", "Mozilla Bar"), new BasicHeader("Origin", corsValue));
Response response = getRestClient().performRequest(request);
assertThat(response.getStatusLine().getStatusCode(), is(200)); assertThat(response.getStatusLine().getStatusCode(), is(200));
assertThat(response.getHeader("Access-Control-Allow-Origin"), nullValue()); assertThat(response.getHeader("Access-Control-Allow-Origin"), nullValue());
assertThat(response.getHeader("Access-Control-Allow-Credentials"), nullValue()); assertThat(response.getHeader("Access-Control-Allow-Credentials"), nullValue());
} }
public void testThatOmittingCorsHeaderDoesNotReturnAnything() throws IOException { public void testThatOmittingCorsHeaderDoesNotReturnAnything() throws IOException {
Response response = getRestClient().performRequest("GET", "/"); Response response = getRestClient().performRequest(new Request("GET", "/"));
assertThat(response.getStatusLine().getStatusCode(), is(200)); assertThat(response.getStatusLine().getStatusCode(), is(200));
assertThat(response.getHeader("Access-Control-Allow-Origin"), nullValue()); assertThat(response.getHeader("Access-Control-Allow-Origin"), nullValue());
assertThat(response.getHeader("Access-Control-Allow-Credentials"), nullValue()); assertThat(response.getHeader("Access-Control-Allow-Credentials"), nullValue());

View File

@ -19,9 +19,9 @@
package org.elasticsearch.http; package org.elasticsearch.http;
import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicHeader;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response; import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseException; import org.elasticsearch.client.ResponseException;
import org.elasticsearch.common.network.NetworkModule;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.test.ESIntegTestCase.ClusterScope;
import org.elasticsearch.test.ESIntegTestCase.Scope; import org.elasticsearch.test.ESIntegTestCase.Scope;
@ -54,21 +54,26 @@ public class CorsRegexIT extends HttpSmokeTestCase {
public void testThatRegularExpressionWorksOnMatch() throws IOException { public void testThatRegularExpressionWorksOnMatch() throws IOException {
String corsValue = "http://localhost:9200"; String corsValue = "http://localhost:9200";
Response response = getRestClient().performRequest("GET", "/", Request request = new Request("GET", "/");
new BasicHeader("User-Agent", "Mozilla Bar"), new BasicHeader("Origin", corsValue)); request.setHeaders(new BasicHeader("User-Agent", "Mozilla Bar"),
new BasicHeader("Origin", corsValue));
Response response = getRestClient().performRequest(request);
assertResponseWithOriginheader(response, corsValue); assertResponseWithOriginheader(response, corsValue);
corsValue = "https://localhost:9200"; corsValue = "https://localhost:9201";
response = getRestClient().performRequest("GET", "/", request.setHeaders(new BasicHeader("User-Agent", "Mozilla Bar"),
new BasicHeader("User-Agent", "Mozilla Bar"), new BasicHeader("Origin", corsValue)); new BasicHeader("Origin", corsValue));
response = getRestClient().performRequest(request);
assertResponseWithOriginheader(response, corsValue); assertResponseWithOriginheader(response, corsValue);
assertThat(response.getHeader("Access-Control-Allow-Credentials"), is("true")); assertThat(response.getHeader("Access-Control-Allow-Credentials"), is("true"));
} }
public void testThatRegularExpressionReturnsForbiddenOnNonMatch() throws IOException { public void testThatRegularExpressionReturnsForbiddenOnNonMatch() throws IOException {
try { Request request = new Request("GET", "/");
getRestClient().performRequest("GET", "/", new BasicHeader("User-Agent", "Mozilla Bar"), request.setHeaders(new BasicHeader("User-Agent", "Mozilla Bar"),
new BasicHeader("Origin", "http://evil-host:9200")); new BasicHeader("Origin", "http://evil-host:9200"));
try {
getRestClient().performRequest(request);
fail("request should have failed"); fail("request should have failed");
} catch(ResponseException e) { } catch(ResponseException e) {
Response response = e.getResponse(); Response response = e.getResponse();
@ -79,31 +84,38 @@ public class CorsRegexIT extends HttpSmokeTestCase {
} }
public void testThatSendingNoOriginHeaderReturnsNoAccessControlHeader() throws IOException { public void testThatSendingNoOriginHeaderReturnsNoAccessControlHeader() throws IOException {
Response response = getRestClient().performRequest("GET", "/", new BasicHeader("User-Agent", "Mozilla Bar")); Request request = new Request("GET", "/");
request.setHeaders(new BasicHeader("User-Agent", "Mozilla Bar"));
Response response = getRestClient().performRequest(request);
assertThat(response.getStatusLine().getStatusCode(), is(200)); assertThat(response.getStatusLine().getStatusCode(), is(200));
assertThat(response.getHeader("Access-Control-Allow-Origin"), nullValue()); assertThat(response.getHeader("Access-Control-Allow-Origin"), nullValue());
} }
public void testThatRegularExpressionIsNotAppliedWithoutCorrectBrowserOnMatch() throws IOException { public void testThatRegularExpressionIsNotAppliedWithoutCorrectBrowserOnMatch() throws IOException {
Response response = getRestClient().performRequest("GET", "/"); Response response = getRestClient().performRequest(new Request("GET", "/"));
assertThat(response.getStatusLine().getStatusCode(), is(200)); assertThat(response.getStatusLine().getStatusCode(), is(200));
assertThat(response.getHeader("Access-Control-Allow-Origin"), nullValue()); assertThat(response.getHeader("Access-Control-Allow-Origin"), nullValue());
} }
public void testThatPreFlightRequestWorksOnMatch() throws IOException { public void testThatPreFlightRequestWorksOnMatch() throws IOException {
String corsValue = "http://localhost:9200"; String corsValue = "http://localhost:9200";
Response response = getRestClient().performRequest("OPTIONS", "/", Request request = new Request("OPTIONS", "/");
new BasicHeader("User-Agent", "Mozilla Bar"), new BasicHeader("Origin", corsValue), request.setHeaders(new BasicHeader("User-Agent", "Mozilla Bar"),
new BasicHeader("Origin", corsValue),
new BasicHeader("Access-Control-Request-Method", "GET")); new BasicHeader("Access-Control-Request-Method", "GET"));
Response response = getRestClient().performRequest(request);
assertResponseWithOriginheader(response, corsValue); assertResponseWithOriginheader(response, corsValue);
assertNotNull(response.getHeader("Access-Control-Allow-Methods")); assertNotNull(response.getHeader("Access-Control-Allow-Methods"));
} }
public void testThatPreFlightRequestReturnsNullOnNonMatch() throws IOException { public void testThatPreFlightRequestReturnsNullOnNonMatch() throws IOException {
try { String corsValue = "http://evil-host:9200";
getRestClient().performRequest("OPTIONS", "/", new BasicHeader("User-Agent", "Mozilla Bar"), Request request = new Request("OPTIONS", "/");
new BasicHeader("Origin", "http://evil-host:9200"), request.setHeaders(new BasicHeader("User-Agent", "Mozilla Bar"),
new BasicHeader("Origin", corsValue),
new BasicHeader("Access-Control-Request-Method", "GET")); new BasicHeader("Access-Control-Request-Method", "GET"));
try {
getRestClient().performRequest(request);
fail("request should have failed"); fail("request should have failed");
} catch(ResponseException e) { } catch(ResponseException e) {
Response response = e.getResponse(); Response response = e.getResponse();

View File

@ -22,6 +22,7 @@ import org.apache.http.Header;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType; import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity; import org.apache.http.entity.StringEntity;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response; import org.elasticsearch.client.Response;
import org.elasticsearch.common.Strings; import org.elasticsearch.common.Strings;
import org.elasticsearch.common.logging.DeprecationLogger; import org.elasticsearch.common.logging.DeprecationLogger;
@ -106,11 +107,10 @@ public class DeprecationHttpIT extends HttpSmokeTestCase {
final String commaSeparatedIndices = Stream.of(indices).collect(Collectors.joining(",")); final String commaSeparatedIndices = Stream.of(indices).collect(Collectors.joining(","));
final String body = "{\"query\":{\"bool\":{\"filter\":[{\"" + TestDeprecatedQueryBuilder.NAME + "\":{}}]}}}";
// trigger all index deprecations // trigger all index deprecations
Response response = getRestClient().performRequest("GET", "/" + commaSeparatedIndices + "/_search", Request request = new Request("GET", "/" + commaSeparatedIndices + "/_search");
Collections.emptyMap(), new StringEntity(body, ContentType.APPLICATION_JSON)); request.setJsonEntity("{\"query\":{\"bool\":{\"filter\":[{\"" + TestDeprecatedQueryBuilder.NAME + "\":{}}]}}}");
Response response = getRestClient().performRequest(request);
assertThat(response.getStatusLine().getStatusCode(), equalTo(OK.getStatus())); assertThat(response.getStatusLine().getStatusCode(), equalTo(OK.getStatus()));
final List<String> deprecatedWarnings = getWarningHeaders(response.getHeaders()); final List<String> deprecatedWarnings = getWarningHeaders(response.getHeaders());
@ -162,8 +162,9 @@ public class DeprecationHttpIT extends HttpSmokeTestCase {
Collections.shuffle(settings, random()); Collections.shuffle(settings, random());
// trigger all deprecations // trigger all deprecations
Response response = getRestClient().performRequest("GET", "/_test_cluster/deprecated_settings", Request request = new Request("GET", "/_test_cluster/deprecated_settings");
Collections.emptyMap(), buildSettingsRequest(settings, useDeprecatedField)); request.setEntity(buildSettingsRequest(settings, useDeprecatedField));
Response response = getRestClient().performRequest(request);
assertThat(response.getStatusLine().getStatusCode(), equalTo(OK.getStatus())); assertThat(response.getStatusLine().getStatusCode(), equalTo(OK.getStatus()));
final List<String> deprecatedWarnings = getWarningHeaders(response.getHeaders()); final List<String> deprecatedWarnings = getWarningHeaders(response.getHeaders());

View File

@ -20,12 +20,11 @@
package org.elasticsearch.http; package org.elasticsearch.http;
import java.io.IOException; import java.io.IOException;
import java.util.Collections;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response; import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseException; import org.elasticsearch.client.ResponseException;
import org.elasticsearch.common.network.NetworkModule;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.test.ESIntegTestCase.ClusterScope;
import org.elasticsearch.test.ESIntegTestCase.Scope; import org.elasticsearch.test.ESIntegTestCase.Scope;
@ -49,8 +48,10 @@ public class DetailedErrorsDisabledIT extends HttpSmokeTestCase {
} }
public void testThatErrorTraceParamReturns400() throws IOException { public void testThatErrorTraceParamReturns400() throws IOException {
Request request = new Request("DELETE", "/");
request.addParameter("error_trace", "true");
ResponseException e = expectThrows(ResponseException.class, () -> ResponseException e = expectThrows(ResponseException.class, () ->
getRestClient().performRequest("DELETE", "/", Collections.singletonMap("error_trace", "true"))); getRestClient().performRequest(request));
Response response = e.getResponse(); Response response = e.getResponse();
assertThat(response.getHeader("Content-Type"), is("application/json; charset=UTF-8")); assertThat(response.getHeader("Content-Type"), is("application/json; charset=UTF-8"));

View File

@ -20,11 +20,11 @@
package org.elasticsearch.http; package org.elasticsearch.http;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response; import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseException; import org.elasticsearch.client.ResponseException;
import java.io.IOException; import java.io.IOException;
import java.util.Collections;
import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.not;
@ -36,7 +36,9 @@ public class DetailedErrorsEnabledIT extends HttpSmokeTestCase {
public void testThatErrorTraceWorksByDefault() throws IOException { public void testThatErrorTraceWorksByDefault() throws IOException {
try { try {
getRestClient().performRequest("DELETE", "/", Collections.singletonMap("error_trace", "true")); Request request = new Request("DELETE", "/");
request.addParameter("error_trace", "true");
getRestClient().performRequest(request);
fail("request should have failed"); fail("request should have failed");
} catch(ResponseException e) { } catch(ResponseException e) {
Response response = e.getResponse(); Response response = e.getResponse();
@ -47,7 +49,7 @@ public class DetailedErrorsEnabledIT extends HttpSmokeTestCase {
} }
try { try {
getRestClient().performRequest("DELETE", "/"); getRestClient().performRequest(new Request("DELETE", "/"));
fail("request should have failed"); fail("request should have failed");
} catch(ResponseException e) { } catch(ResponseException e) {
Response response = e.getResponse(); Response response = e.getResponse();

View File

@ -19,41 +19,40 @@
package org.elasticsearch.http; package org.elasticsearch.http;
import org.apache.http.HttpHeaders; import org.apache.http.HttpHeaders;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicHeader;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response; import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.test.rest.ESRestTestCase; import org.elasticsearch.test.rest.ESRestTestCase;
import java.io.IOException; import java.io.IOException;
import java.util.Collections;
public class HttpCompressionIT extends ESRestTestCase { public class HttpCompressionIT extends ESRestTestCase {
private static final String GZIP_ENCODING = "gzip"; private static final String GZIP_ENCODING = "gzip";
private static final StringEntity SAMPLE_DOCUMENT = new StringEntity("{\n" + private static final String SAMPLE_DOCUMENT = "{\n" +
" \"name\": {\n" + " \"name\": {\n" +
" \"first name\": \"Steve\",\n" + " \"first name\": \"Steve\",\n" +
" \"last name\": \"Jobs\"\n" + " \"last name\": \"Jobs\"\n" +
" }\n" + " }\n" +
"}", ContentType.APPLICATION_JSON); "}";
public void testCompressesResponseIfRequested() throws IOException { public void testCompressesResponseIfRequested() throws IOException {
RestClient client = client(); Request request = new Request("GET", "/");
Response response = client.performRequest("GET", "/", new BasicHeader(HttpHeaders.ACCEPT_ENCODING, GZIP_ENCODING)); request.setHeaders(new BasicHeader(HttpHeaders.ACCEPT_ENCODING, GZIP_ENCODING));
Response response = client().performRequest(request);
assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals(200, response.getStatusLine().getStatusCode());
assertEquals(GZIP_ENCODING, response.getHeader(HttpHeaders.CONTENT_ENCODING)); assertEquals(GZIP_ENCODING, response.getHeader(HttpHeaders.CONTENT_ENCODING));
} }
public void testUncompressedResponseByDefault() throws IOException { public void testUncompressedResponseByDefault() throws IOException {
RestClient client = client(); Response response = client().performRequest(new Request("GET", "/"));
Response response = client.performRequest("GET", "/");
assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals(200, response.getStatusLine().getStatusCode());
assertNull(response.getHeader(HttpHeaders.CONTENT_ENCODING)); assertNull(response.getHeader(HttpHeaders.CONTENT_ENCODING));
response = client.performRequest("POST", "/company/employees/1", Collections.emptyMap(), SAMPLE_DOCUMENT); Request request = new Request("POST", "/company/employees/1");
request.setJsonEntity(SAMPLE_DOCUMENT);
response = client().performRequest(request);
assertEquals(201, response.getStatusLine().getStatusCode()); assertEquals(201, response.getStatusLine().getStatusCode());
assertNull(response.getHeader(HttpHeaders.CONTENT_ENCODING)); assertNull(response.getHeader(HttpHeaders.CONTENT_ENCODING));
} }

View File

@ -21,6 +21,7 @@ package org.elasticsearch.http;
import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response; import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseException; import org.elasticsearch.client.ResponseException;
@ -45,10 +46,10 @@ public class NoHandlerIT extends HttpSmokeTestCase {
private void runTestNoHandlerRespectsAcceptHeader( private void runTestNoHandlerRespectsAcceptHeader(
final String accept, final String contentType, final String expect) throws IOException { final String accept, final String contentType, final String expect) throws IOException {
final ResponseException e = Request request = new Request("GET", "/foo/bar/baz/qux/quux");
expectThrows( request.setHeaders(new BasicHeader("Accept", accept));
ResponseException.class, final ResponseException e = expectThrows(ResponseException.class,
() -> getRestClient().performRequest("GET", "/foo/bar/baz/qux/quux", new BasicHeader("Accept", accept))); () -> getRestClient().performRequest(request));
final Response response = e.getResponse(); final Response response = e.getResponse();
assertThat(response.getHeader("Content-Type"), equalTo(contentType)); assertThat(response.getHeader("Content-Type"), equalTo(contentType));

View File

@ -19,9 +19,9 @@
package org.elasticsearch.http; package org.elasticsearch.http;
import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicHeader;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response; import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseException; import org.elasticsearch.client.ResponseException;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.plugins.Plugin; import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.test.ESIntegTestCase.ClusterScope;
import org.elasticsearch.test.ESIntegTestCase.Scope; import org.elasticsearch.test.ESIntegTestCase.Scope;
@ -53,7 +53,7 @@ public class ResponseHeaderPluginIT extends HttpSmokeTestCase {
public void testThatSettingHeadersWorks() throws IOException { public void testThatSettingHeadersWorks() throws IOException {
ensureGreen(); ensureGreen();
try { try {
getRestClient().performRequest("GET", "/_protected"); getRestClient().performRequest(new Request("GET", "/_protected"));
fail("request should have failed"); fail("request should have failed");
} catch(ResponseException e) { } catch(ResponseException e) {
Response response = e.getResponse(); Response response = e.getResponse();
@ -61,7 +61,9 @@ public class ResponseHeaderPluginIT extends HttpSmokeTestCase {
assertThat(response.getHeader("Secret"), equalTo("required")); assertThat(response.getHeader("Secret"), equalTo("required"));
} }
Response authResponse = getRestClient().performRequest("GET", "/_protected", new BasicHeader("Secret", "password")); Request request = new Request("GET", "/_protected");
request.setHeaders(new BasicHeader("Secret", "password"));
Response authResponse = getRestClient().performRequest(request);
assertThat(authResponse.getStatusLine().getStatusCode(), equalTo(200)); assertThat(authResponse.getStatusLine().getStatusCode(), equalTo(200));
assertThat(authResponse.getHeader("Secret"), equalTo("granted")); assertThat(authResponse.getHeader("Secret"), equalTo("granted"));
} }

View File

@ -18,6 +18,7 @@
package org.elasticsearch.http; package org.elasticsearch.http;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response; import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseException; import org.elasticsearch.client.ResponseException;
import org.elasticsearch.test.rest.ESRestTestCase; import org.elasticsearch.test.rest.ESRestTestCase;
@ -46,7 +47,7 @@ public class RestHttpResponseHeadersIT extends ESRestTestCase {
* - Options</a>). * - Options</a>).
*/ */
public void testValidEndpointOptionsResponseHttpHeader() throws Exception { public void testValidEndpointOptionsResponseHttpHeader() throws Exception {
Response response = client().performRequest("OPTIONS", "/_tasks"); Response response = client().performRequest(new Request("OPTIONS", "/_tasks"));
assertThat(response.getStatusLine().getStatusCode(), is(200)); assertThat(response.getStatusLine().getStatusCode(), is(200));
assertThat(response.getHeader("Allow"), notNullValue()); assertThat(response.getHeader("Allow"), notNullValue());
List<String> responseAllowHeaderStringArray = List<String> responseAllowHeaderStringArray =
@ -64,7 +65,7 @@ public class RestHttpResponseHeadersIT extends ESRestTestCase {
*/ */
public void testUnsupportedMethodResponseHttpHeader() throws Exception { public void testUnsupportedMethodResponseHttpHeader() throws Exception {
try { try {
client().performRequest("DELETE", "/_tasks"); client().performRequest(new Request("DELETE", "/_tasks"));
fail("Request should have failed with 405 error"); fail("Request should have failed with 405 error");
} catch (ResponseException e) { } catch (ResponseException e) {
Response response = e.getResponse(); Response response = e.getResponse();
@ -85,9 +86,9 @@ public class RestHttpResponseHeadersIT extends ESRestTestCase {
* 17853</a> for more information). * 17853</a> for more information).
*/ */
public void testIndexSettingsPostRequest() throws Exception { public void testIndexSettingsPostRequest() throws Exception {
client().performRequest("PUT", "/testindex"); client().performRequest(new Request("PUT", "/testindex"));
try { try {
client().performRequest("POST", "/testindex/_settings"); client().performRequest(new Request("POST", "/testindex/_settings"));
fail("Request should have failed with 405 error"); fail("Request should have failed with 405 error");
} catch (ResponseException e) { } catch (ResponseException e) {
Response response = e.getResponse(); Response response = e.getResponse();