Search in sources :

Example 26 with StringEntity

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));
    }
}
Also used : StringEntity(org.apache.http.entity.StringEntity) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder)

Example 27 with StringEntity

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));
    }
}
Also used : Response(org.elasticsearch.client.Response) StringEntity(org.apache.http.entity.StringEntity) Matcher(org.hamcrest.Matcher) ArrayList(java.util.ArrayList) Matchers.containsString(org.hamcrest.Matchers.containsString)

Example 28 with StringEntity

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;
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpPost(org.apache.http.client.methods.HttpPost) HttpEntity(org.apache.http.HttpEntity) HashMap(java.util.HashMap) HttpOptions(org.apache.http.client.methods.HttpOptions) URI(java.net.URI) HttpHead(org.apache.http.client.methods.HttpHead) HttpPatch(org.apache.http.client.methods.HttpPatch) HttpPut(org.apache.http.client.methods.HttpPut) StringEntity(org.apache.http.entity.StringEntity) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest) HashSet(java.util.HashSet) URIBuilder(org.apache.http.client.utils.URIBuilder) HttpTrace(org.apache.http.client.methods.HttpTrace) Header(org.apache.http.Header)

Example 29 with StringEntity

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"));
        }
    }
}
Also used : BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) StringEntity(org.apache.http.entity.StringEntity)

Example 30 with StringEntity

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"));
    }
}
Also used : GetResponse(org.elasticsearch.action.get.GetResponse) UpdateResponse(org.elasticsearch.action.update.UpdateResponse) IndexResponse(org.elasticsearch.action.index.IndexResponse) DeleteResponse(org.elasticsearch.action.delete.DeleteResponse) BulkItemResponse(org.elasticsearch.action.bulk.BulkItemResponse) BulkResponse(org.elasticsearch.action.bulk.BulkResponse) DocWriteResponse(org.elasticsearch.action.DocWriteResponse) StringEntity(org.apache.http.entity.StringEntity) FetchSourceContext(org.elasticsearch.search.fetch.subphase.FetchSourceContext) GetRequest(org.elasticsearch.action.get.GetRequest) ElasticsearchException(org.elasticsearch.ElasticsearchException) GetResponse(org.elasticsearch.action.get.GetResponse) Map(java.util.Map) Collections.singletonMap(java.util.Collections.singletonMap)

Aggregations

StringEntity (org.apache.http.entity.StringEntity)409 HttpPost (org.apache.http.client.methods.HttpPost)223 HttpResponse (org.apache.http.HttpResponse)136 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)129 HttpPut (org.apache.http.client.methods.HttpPut)89 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)88 Test (org.junit.Test)84 IOException (java.io.IOException)78 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)60 HttpEntity (org.apache.http.HttpEntity)55 JsonNode (com.fasterxml.jackson.databind.JsonNode)54 Deployment (org.activiti.engine.test.Deployment)50 TestHttpClient (io.undertow.testutils.TestHttpClient)30 ProcessInstance (org.activiti.engine.runtime.ProcessInstance)27 StatusLine (org.apache.http.StatusLine)26 HttpGet (org.apache.http.client.methods.HttpGet)25 BasicHttpResponse (org.apache.http.message.BasicHttpResponse)23 Task (org.activiti.engine.task.Task)21 HttpRequest (org.apache.http.HttpRequest)21 ArrayNode (com.fasterxml.jackson.databind.node.ArrayNode)20