Search in sources :

Example 1 with Header

use of org.apache.http.Header in project elasticsearch by elastic.

the class RestClientMultipleHostsTests method createRestClient.

@Before
@SuppressWarnings("unchecked")
public void createRestClient() throws IOException {
    CloseableHttpAsyncClient httpClient = mock(CloseableHttpAsyncClient.class);
    when(httpClient.<HttpResponse>execute(any(HttpAsyncRequestProducer.class), any(HttpAsyncResponseConsumer.class), any(HttpClientContext.class), any(FutureCallback.class))).thenAnswer(new Answer<Future<HttpResponse>>() {

        @Override
        public Future<HttpResponse> answer(InvocationOnMock invocationOnMock) throws Throwable {
            HttpAsyncRequestProducer requestProducer = (HttpAsyncRequestProducer) invocationOnMock.getArguments()[0];
            HttpUriRequest request = (HttpUriRequest) requestProducer.generateRequest();
            HttpHost httpHost = requestProducer.getTarget();
            HttpClientContext context = (HttpClientContext) invocationOnMock.getArguments()[2];
            assertThat(context.getAuthCache().get(httpHost), instanceOf(BasicScheme.class));
            FutureCallback<HttpResponse> futureCallback = (FutureCallback<HttpResponse>) invocationOnMock.getArguments()[3];
            //return the desired status code or exception depending on the path
            if (request.getURI().getPath().equals("/soe")) {
                futureCallback.failed(new SocketTimeoutException(httpHost.toString()));
            } else if (request.getURI().getPath().equals("/coe")) {
                futureCallback.failed(new ConnectTimeoutException(httpHost.toString()));
            } else if (request.getURI().getPath().equals("/ioe")) {
                futureCallback.failed(new IOException(httpHost.toString()));
            } else {
                int statusCode = Integer.parseInt(request.getURI().getPath().substring(1));
                StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("http", 1, 1), statusCode, "");
                futureCallback.completed(new BasicHttpResponse(statusLine));
            }
            return null;
        }
    });
    int numHosts = RandomNumbers.randomIntBetween(getRandom(), 2, 5);
    httpHosts = new HttpHost[numHosts];
    for (int i = 0; i < numHosts; i++) {
        httpHosts[i] = new HttpHost("localhost", 9200 + i);
    }
    failureListener = new HostsTrackingFailureListener();
    restClient = new RestClient(httpClient, 10000, new Header[0], httpHosts, null, failureListener);
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) HttpAsyncResponseConsumer(org.apache.http.nio.protocol.HttpAsyncResponseConsumer) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) IOException(java.io.IOException) ProtocolVersion(org.apache.http.ProtocolVersion) BasicStatusLine(org.apache.http.message.BasicStatusLine) BasicStatusLine(org.apache.http.message.BasicStatusLine) StatusLine(org.apache.http.StatusLine) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) SocketTimeoutException(java.net.SocketTimeoutException) Header(org.apache.http.Header) HttpAsyncRequestProducer(org.apache.http.nio.protocol.HttpAsyncRequestProducer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) HttpHost(org.apache.http.HttpHost) CloseableHttpAsyncClient(org.apache.http.impl.nio.client.CloseableHttpAsyncClient) Future(java.util.concurrent.Future) FutureCallback(org.apache.http.concurrent.FutureCallback) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException) Before(org.junit.Before)

Example 2 with Header

use of org.apache.http.Header 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 3 with Header

use of org.apache.http.Header in project elasticsearch by elastic.

the class RestHighLevelClientTests method testPing404NotFound.

public void testPing404NotFound() throws IOException {
    Header[] headers = RestClientTestUtil.randomHeaders(random(), "Header");
    Response response = mock(Response.class);
    when(response.getStatusLine()).thenReturn(newStatusLine(RestStatus.NOT_FOUND));
    when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class), anyObject(), anyVararg())).thenReturn(response);
    assertFalse(restHighLevelClient.ping(headers));
    verify(restClient).performRequest(eq("HEAD"), eq("/"), eq(Collections.emptyMap()), Matchers.isNull(HttpEntity.class), argThat(new HeadersVarargMatcher(headers)));
}
Also used : MainResponse(org.elasticsearch.action.main.MainResponse) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) Header(org.apache.http.Header) HttpEntity(org.apache.http.HttpEntity) Matchers.anyString(org.mockito.Matchers.anyString)

Example 4 with Header

use of org.apache.http.Header in project elasticsearch by elastic.

the class RestHighLevelClientTests method testPingSocketTimeout.

public void testPingSocketTimeout() throws IOException {
    Header[] headers = RestClientTestUtil.randomHeaders(random(), "Header");
    when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class), anyObject(), anyVararg())).thenThrow(new SocketTimeoutException());
    expectThrows(SocketTimeoutException.class, () -> restHighLevelClient.ping(headers));
    verify(restClient).performRequest(eq("HEAD"), eq("/"), eq(Collections.emptyMap()), Matchers.isNull(HttpEntity.class), argThat(new HeadersVarargMatcher(headers)));
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) Header(org.apache.http.Header) HttpEntity(org.apache.http.HttpEntity) Matchers.anyString(org.mockito.Matchers.anyString)

Example 5 with Header

use of org.apache.http.Header in project elasticsearch by elastic.

the class RestHighLevelClientTests method testPingSuccessful.

public void testPingSuccessful() throws IOException {
    Header[] headers = RestClientTestUtil.randomHeaders(random(), "Header");
    Response response = mock(Response.class);
    when(response.getStatusLine()).thenReturn(newStatusLine(RestStatus.OK));
    when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class), anyObject(), anyVararg())).thenReturn(response);
    assertTrue(restHighLevelClient.ping(headers));
    verify(restClient).performRequest(eq("HEAD"), eq("/"), eq(Collections.emptyMap()), Matchers.isNull(HttpEntity.class), argThat(new HeadersVarargMatcher(headers)));
}
Also used : MainResponse(org.elasticsearch.action.main.MainResponse) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) Header(org.apache.http.Header) HttpEntity(org.apache.http.HttpEntity) Matchers.anyString(org.mockito.Matchers.anyString)

Aggregations

Header (org.apache.http.Header)923 HttpResponse (org.apache.http.HttpResponse)370 HttpGet (org.apache.http.client.methods.HttpGet)256 Test (org.junit.Test)208 IOException (java.io.IOException)207 BasicHeader (org.apache.http.message.BasicHeader)167 HttpEntity (org.apache.http.HttpEntity)139 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)99 URI (java.net.URI)98 TestHttpClient (io.undertow.testutils.TestHttpClient)94 ArrayList (java.util.ArrayList)90 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)80 HashMap (java.util.HashMap)77 InputStream (java.io.InputStream)68 URISyntaxException (java.net.URISyntaxException)66 HttpPost (org.apache.http.client.methods.HttpPost)66 StatusLine (org.apache.http.StatusLine)63 List (java.util.List)52 StringEntity (org.apache.http.entity.StringEntity)52 HttpHost (org.apache.http.HttpHost)50