use of org.apache.http.entity.StringEntity in project elasticsearch by elastic.
the class Netty4HeadBodyIsEmptyIT method testAliasExists.
public void testAliasExists() throws IOException {
createTestDoc();
try (XContentBuilder builder = jsonBuilder()) {
builder.startObject();
{
builder.startArray("actions");
{
builder.startObject();
{
builder.startObject("add");
{
builder.field("index", "test");
builder.field("alias", "test_alias");
}
builder.endObject();
}
builder.endObject();
}
builder.endArray();
}
builder.endObject();
client().performRequest("POST", "_aliases", emptyMap(), new StringEntity(builder.string(), ContentType.APPLICATION_JSON));
headTestCase("/_alias/test_alias", emptyMap(), greaterThan(0));
headTestCase("/test/_alias/test_alias", emptyMap(), greaterThan(0));
}
}
use of org.apache.http.entity.StringEntity in project elasticsearch by elastic.
the class DeprecationHttpIT method testUniqueDeprecationResponsesMergedTogether.
/**
* Attempts to do a scatter/gather request that expects unique responses per sub-request.
*/
@AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/19222")
public void testUniqueDeprecationResponsesMergedTogether() throws IOException {
final String[] indices = new String[randomIntBetween(2, 5)];
// add at least one document for each index
for (int i = 0; i < indices.length; ++i) {
indices[i] = "test" + i;
// create indices with a single shard to reduce noise; the query only deprecates uniquely by index anyway
assertTrue(prepareCreate(indices[i]).setSettings(Settings.builder().put("number_of_shards", 1)).get().isAcknowledged());
int randomDocCount = randomIntBetween(1, 2);
for (int j = 0; j < randomDocCount; ++j) {
index(indices[i], "type", Integer.toString(j), "{\"field\":" + j + "}");
}
}
refresh(indices);
final String commaSeparatedIndices = Stream.of(indices).collect(Collectors.joining(","));
final String body = "{\"query\":{\"bool\":{\"filter\":[{\"" + TestDeprecatedQueryBuilder.NAME + "\":{}}]}}}";
// trigger all index deprecations
Response response = getRestClient().performRequest("GET", "/" + commaSeparatedIndices + "/_search", Collections.emptyMap(), new StringEntity(body, ContentType.APPLICATION_JSON));
assertThat(response.getStatusLine().getStatusCode(), equalTo(OK.getStatus()));
final List<String> deprecatedWarnings = getWarningHeaders(response.getHeaders());
final List<Matcher<String>> headerMatchers = new ArrayList<>(indices.length);
for (String index : indices) {
headerMatchers.add(containsString(LoggerMessageFormat.format("[{}] index", (Object) index)));
}
assertThat(deprecatedWarnings, hasSize(headerMatchers.size()));
for (Matcher<String> headerMatcher : headerMatchers) {
assertThat(deprecatedWarnings, hasItem(headerMatcher));
}
}
use of org.apache.http.entity.StringEntity in project elasticsearch by elastic.
the class RestClientSingleHostTests method performRandomRequest.
private HttpUriRequest performRandomRequest(String method) throws Exception {
String uriAsString = "/" + randomStatusCode(getRandom());
URIBuilder uriBuilder = new URIBuilder(uriAsString);
final Map<String, String> params = new HashMap<>();
boolean hasParams = randomBoolean();
if (hasParams) {
int numParams = randomIntBetween(1, 3);
for (int i = 0; i < numParams; i++) {
String paramKey = "param-" + i;
String paramValue = randomAsciiOfLengthBetween(3, 10);
params.put(paramKey, paramValue);
uriBuilder.addParameter(paramKey, paramValue);
}
}
if (randomBoolean()) {
//randomly add some ignore parameter, which doesn't get sent as part of the request
String ignore = Integer.toString(randomFrom(RestClientTestUtil.getAllErrorStatusCodes()));
if (randomBoolean()) {
ignore += "," + Integer.toString(randomFrom(RestClientTestUtil.getAllErrorStatusCodes()));
}
params.put("ignore", ignore);
}
URI uri = uriBuilder.build();
HttpUriRequest request;
switch(method) {
case "DELETE":
request = new HttpDeleteWithEntity(uri);
break;
case "GET":
request = new HttpGetWithEntity(uri);
break;
case "HEAD":
request = new HttpHead(uri);
break;
case "OPTIONS":
request = new HttpOptions(uri);
break;
case "PATCH":
request = new HttpPatch(uri);
break;
case "POST":
request = new HttpPost(uri);
break;
case "PUT":
request = new HttpPut(uri);
break;
case "TRACE":
request = new HttpTrace(uri);
break;
default:
throw new UnsupportedOperationException("method not supported: " + method);
}
HttpEntity entity = null;
boolean hasBody = request instanceof HttpEntityEnclosingRequest && getRandom().nextBoolean();
if (hasBody) {
entity = new StringEntity(randomAsciiOfLengthBetween(10, 100), ContentType.APPLICATION_JSON);
((HttpEntityEnclosingRequest) request).setEntity(entity);
}
Header[] headers = new Header[0];
final Set<String> uniqueNames = new HashSet<>();
if (randomBoolean()) {
headers = RestClientTestUtil.randomHeaders(getRandom(), "Header");
for (Header header : headers) {
request.addHeader(header);
uniqueNames.add(header.getName());
}
}
for (Header defaultHeader : defaultHeaders) {
// request level headers override default headers
if (uniqueNames.contains(defaultHeader.getName()) == false) {
request.addHeader(defaultHeader);
}
}
try {
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;
}
use of org.apache.http.entity.StringEntity in project elasticsearch by elastic.
the class RestClientSingleHostTests method testBody.
/**
* End to end test for request and response body. Exercises the mock http client ability to send back
* whatever body it has received.
*/
public void testBody() throws IOException {
String body = "{ \"field\": \"value\" }";
StringEntity entity = new StringEntity(body, ContentType.APPLICATION_JSON);
for (String method : Arrays.asList("DELETE", "GET", "PATCH", "POST", "PUT")) {
for (int okStatusCode : getOkStatusCodes()) {
Response response = restClient.performRequest(method, "/" + okStatusCode, Collections.<String, String>emptyMap(), entity);
assertThat(response.getStatusLine().getStatusCode(), equalTo(okStatusCode));
assertThat(EntityUtils.toString(response.getEntity()), equalTo(body));
}
for (int errorStatusCode : getAllErrorStatusCodes()) {
try {
restClient.performRequest(method, "/" + errorStatusCode, Collections.<String, String>emptyMap(), entity);
fail("request should have failed");
} catch (ResponseException e) {
Response response = e.getResponse();
assertThat(response.getStatusLine().getStatusCode(), equalTo(errorStatusCode));
assertThat(EntityUtils.toString(response.getEntity()), equalTo(body));
}
}
}
for (String method : Arrays.asList("HEAD", "OPTIONS", "TRACE")) {
try {
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"));
}
}
}
use of org.apache.http.entity.StringEntity in project elasticsearch by elastic.
the class CrudIT method testGet.
public void testGet() throws IOException {
{
GetRequest getRequest = new GetRequest("index", "type", "id");
ElasticsearchException exception = expectThrows(ElasticsearchException.class, () -> execute(getRequest, highLevelClient()::get, highLevelClient()::getAsync));
assertEquals(RestStatus.NOT_FOUND, exception.status());
assertEquals("Elasticsearch exception [type=index_not_found_exception, reason=no such index]", exception.getMessage());
assertEquals("index", exception.getMetadata("es.index").get(0));
}
String document = "{\"field1\":\"value1\",\"field2\":\"value2\"}";
StringEntity stringEntity = new StringEntity(document, ContentType.APPLICATION_JSON);
Response response = client().performRequest("PUT", "/index/type/id", Collections.singletonMap("refresh", "wait_for"), stringEntity);
assertEquals(201, response.getStatusLine().getStatusCode());
{
GetRequest getRequest = new GetRequest("index", "type", "id").version(2);
ElasticsearchException exception = expectThrows(ElasticsearchException.class, () -> execute(getRequest, highLevelClient()::get, highLevelClient()::getAsync));
assertEquals(RestStatus.CONFLICT, exception.status());
assertEquals("Elasticsearch exception [type=version_conflict_engine_exception, " + "reason=[type][id]: " + "version conflict, current version [1] is different than the one provided [2]]", exception.getMessage());
assertEquals("index", exception.getMetadata("es.index").get(0));
}
{
GetRequest getRequest = new GetRequest("index", "type", "id");
if (randomBoolean()) {
getRequest.version(1L);
}
GetResponse getResponse = execute(getRequest, highLevelClient()::get, highLevelClient()::getAsync);
assertEquals("index", getResponse.getIndex());
assertEquals("type", getResponse.getType());
assertEquals("id", getResponse.getId());
assertTrue(getResponse.isExists());
assertFalse(getResponse.isSourceEmpty());
assertEquals(1L, getResponse.getVersion());
assertEquals(document, getResponse.getSourceAsString());
}
{
GetRequest getRequest = new GetRequest("index", "type", "does_not_exist");
GetResponse getResponse = execute(getRequest, highLevelClient()::get, highLevelClient()::getAsync);
assertEquals("index", getResponse.getIndex());
assertEquals("type", getResponse.getType());
assertEquals("does_not_exist", getResponse.getId());
assertFalse(getResponse.isExists());
assertEquals(-1, getResponse.getVersion());
assertTrue(getResponse.isSourceEmpty());
assertNull(getResponse.getSourceAsString());
}
{
GetRequest getRequest = new GetRequest("index", "type", "id");
getRequest.fetchSourceContext(new FetchSourceContext(false, Strings.EMPTY_ARRAY, Strings.EMPTY_ARRAY));
GetResponse getResponse = execute(getRequest, highLevelClient()::get, highLevelClient()::getAsync);
assertEquals("index", getResponse.getIndex());
assertEquals("type", getResponse.getType());
assertEquals("id", getResponse.getId());
assertTrue(getResponse.isExists());
assertTrue(getResponse.isSourceEmpty());
assertEquals(1L, getResponse.getVersion());
assertNull(getResponse.getSourceAsString());
}
{
GetRequest getRequest = new GetRequest("index", "type", "id");
if (randomBoolean()) {
getRequest.fetchSourceContext(new FetchSourceContext(true, new String[] { "field1" }, Strings.EMPTY_ARRAY));
} else {
getRequest.fetchSourceContext(new FetchSourceContext(true, Strings.EMPTY_ARRAY, new String[] { "field2" }));
}
GetResponse getResponse = execute(getRequest, highLevelClient()::get, highLevelClient()::getAsync);
assertEquals("index", getResponse.getIndex());
assertEquals("type", getResponse.getType());
assertEquals("id", getResponse.getId());
assertTrue(getResponse.isExists());
assertFalse(getResponse.isSourceEmpty());
assertEquals(1L, getResponse.getVersion());
Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();
assertEquals(1, sourceAsMap.size());
assertEquals("value1", sourceAsMap.get("field1"));
}
}
Aggregations