Search in sources :

Example 46 with BasicHttpResponse

use of org.apache.http.message.BasicHttpResponse in project elasticsearch by elastic.

the class RestHighLevelClientTests method testWrapResponseListenerOnResponseExceptionWithIgnoresErrorNoBody.

public void testWrapResponseListenerOnResponseExceptionWithIgnoresErrorNoBody() throws IOException {
    TrackingActionListener trackingActionListener = new TrackingActionListener();
    //response parsing throws exception while handling ignores. same as when GetResponse#fromXContent throws error when trying
    //to parse a 404 response which contains an error rather than a valid document not found response.
    ResponseListener responseListener = restHighLevelClient.wrapResponseListener(response -> {
        throw new IllegalStateException();
    }, trackingActionListener, Collections.singleton(404));
    HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(RestStatus.NOT_FOUND));
    Response response = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse);
    ResponseException responseException = new ResponseException(response);
    responseListener.onFailure(responseException);
    assertThat(trackingActionListener.exception.get(), instanceOf(ElasticsearchException.class));
    ElasticsearchException elasticsearchException = (ElasticsearchException) trackingActionListener.exception.get();
    assertEquals(RestStatus.NOT_FOUND, elasticsearchException.status());
    assertSame(responseException, elasticsearchException.getCause());
    assertEquals(responseException.getMessage(), elasticsearchException.getMessage());
}
Also used : MainResponse(org.elasticsearch.action.main.MainResponse) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpHost(org.apache.http.HttpHost) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) ElasticsearchException(org.elasticsearch.ElasticsearchException)

Example 47 with BasicHttpResponse

use of org.apache.http.message.BasicHttpResponse in project elasticsearch by elastic.

the class RestHighLevelClientTests method testPerformRequestOnResponseExceptionWithEntity.

public void testPerformRequestOnResponseExceptionWithEntity() throws IOException {
    MainRequest mainRequest = new MainRequest();
    CheckedFunction<MainRequest, Request, IOException> requestConverter = request -> new Request("GET", "/", Collections.emptyMap(), null);
    RestStatus restStatus = randomFrom(RestStatus.values());
    HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus));
    httpResponse.setEntity(new StringEntity("{\"error\":\"test error message\",\"status\":" + restStatus.getStatus() + "}", ContentType.APPLICATION_JSON));
    Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse);
    ResponseException responseException = new ResponseException(mockResponse);
    when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class), anyObject(), anyVararg())).thenThrow(responseException);
    ElasticsearchException elasticsearchException = expectThrows(ElasticsearchException.class, () -> restHighLevelClient.performRequest(mainRequest, requestConverter, response -> response.getStatusLine().getStatusCode(), Collections.emptySet()));
    assertEquals("Elasticsearch exception [type=exception, reason=test error message]", elasticsearchException.getMessage());
    assertEquals(restStatus, elasticsearchException.status());
    assertSame(responseException, elasticsearchException.getSuppressed()[0]);
}
Also used : ElasticsearchException(org.elasticsearch.ElasticsearchException) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) Header(org.apache.http.Header) StatusLine(org.apache.http.StatusLine) CoreMatchers.instanceOf(org.hamcrest.CoreMatchers.instanceOf) ArgumentMatcher(org.mockito.ArgumentMatcher) RequestLine(org.apache.http.RequestLine) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Matchers.eq(org.mockito.Matchers.eq) ClusterName(org.elasticsearch.cluster.ClusterName) JsonParseException(com.fasterxml.jackson.core.JsonParseException) NamedXContentRegistry(org.elasticsearch.common.xcontent.NamedXContentRegistry) Matchers.anyVararg(org.mockito.Matchers.anyVararg) ActionRequest(org.elasticsearch.action.ActionRequest) HttpEntity(org.apache.http.HttpEntity) ContentType(org.apache.http.entity.ContentType) StringEntity(org.apache.http.entity.StringEntity) XContentHelper.toXContent(org.elasticsearch.common.xcontent.XContentHelper.toXContent) MainResponse(org.elasticsearch.action.main.MainResponse) CheckedFunction(org.elasticsearch.common.CheckedFunction) List(java.util.List) Version(org.elasticsearch.Version) ArrayEquals(org.mockito.internal.matchers.ArrayEquals) ActionRequestValidationException(org.elasticsearch.action.ActionRequestValidationException) Matchers.argThat(org.mockito.Matchers.argThat) RestStatus(org.elasticsearch.rest.RestStatus) Mockito.mock(org.mockito.Mockito.mock) XContentType(org.elasticsearch.common.xcontent.XContentType) BasicStatusLine(org.apache.http.message.BasicStatusLine) Matchers(org.mockito.Matchers) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) AtomicReference(java.util.concurrent.atomic.AtomicReference) Matchers.anyString(org.mockito.Matchers.anyString) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) Matchers.anyMapOf(org.mockito.Matchers.anyMapOf) SocketTimeoutException(java.net.SocketTimeoutException) Matchers.anyObject(org.mockito.Matchers.anyObject) ESTestCase(org.elasticsearch.test.ESTestCase) MainRequest(org.elasticsearch.action.main.MainRequest) Before(org.junit.Before) CborXContent(org.elasticsearch.common.xcontent.cbor.CborXContent) BasicRequestLine(org.apache.http.message.BasicRequestLine) SmileXContent(org.elasticsearch.common.xcontent.smile.SmileXContent) IOException(java.io.IOException) Mockito.when(org.mockito.Mockito.when) Mockito.verify(org.mockito.Mockito.verify) XContentParser(org.elasticsearch.common.xcontent.XContentParser) ProtocolVersion(org.apache.http.ProtocolVersion) HttpResponse(org.apache.http.HttpResponse) HttpHost(org.apache.http.HttpHost) Build(org.elasticsearch.Build) VarargMatcher(org.mockito.internal.matchers.VarargMatcher) Collections(java.util.Collections) ActionListener(org.elasticsearch.action.ActionListener) MainRequest(org.elasticsearch.action.main.MainRequest) ActionRequest(org.elasticsearch.action.ActionRequest) MainRequest(org.elasticsearch.action.main.MainRequest) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) Matchers.anyString(org.mockito.Matchers.anyString) ElasticsearchException(org.elasticsearch.ElasticsearchException) MainResponse(org.elasticsearch.action.main.MainResponse) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) StringEntity(org.apache.http.entity.StringEntity) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) RestStatus(org.elasticsearch.rest.RestStatus) HttpHost(org.apache.http.HttpHost)

Example 48 with BasicHttpResponse

use of org.apache.http.message.BasicHttpResponse in project h2o-2 by h2oai.

the class GoogleAnalyticsThreadFactory method post.

@SuppressWarnings({ "rawtypes" })
public GoogleAnalyticsResponse post(GoogleAnalyticsRequest request) {
    GoogleAnalyticsResponse response = new GoogleAnalyticsResponse();
    if (!config.isEnabled()) {
        return response;
    }
    BasicHttpResponse httpResponse = null;
    try {
        List<NameValuePair> postParms = new ArrayList<NameValuePair>();
        //Log.debug("GA Processing " + request);
        //Process the parameters
        processParameters(request, postParms);
        //Process custom dimensions
        processCustomDimensionParameters(request, postParms);
        //Process custom metrics
        processCustomMetricParameters(request, postParms);
        //Log.debug("GA Processed all parameters and sending the request " + postParms);
        HttpPost httpPost = new HttpPost(config.getUrl());
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(postParms, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            Log.warn("This systems doesn't support UTF-8!");
        }
        try {
            httpResponse = (BasicHttpResponse) httpClient.execute(httpPost);
        } catch (ClientProtocolException e) {
        //Log.trace("GA connectivity had a problem or the connectivity was aborted.  "+e.toString());
        } catch (IOException e) {
        //Log.trace("GA connectivity suffered a protocol error.  "+e.toString());
        }
        //Log.debug("GA response: " +httpResponse.toString());
        response.setStatusCode(httpResponse.getStatusLine().getStatusCode());
        response.setPostedParms(postParms);
        try {
            EntityUtils.consume(httpResponse.getEntity());
        } catch (IOException e) {
        /*consume quietly*/
        }
        if (config.isGatherStats()) {
            gatherStats(request);
        }
    } catch (Exception e) {
        if (e instanceof UnknownHostException) {
        //Log.trace("Coudln't connect to GA. Internet may not be available. " + e.toString());
        } else {
        //Log.trace("Exception while sending the GA tracker request: " + request +".  "+ e.toString());
        }
    }
    return response;
}
Also used : BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) HttpPost(org.apache.http.client.methods.HttpPost) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) UnknownHostException(java.net.UnknownHostException) ArrayList(java.util.ArrayList) UnsupportedEncodingException(java.io.UnsupportedEncodingException) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Example 49 with BasicHttpResponse

use of org.apache.http.message.BasicHttpResponse in project android-volley by mcxiaoke.

the class BasicNetworkTest method headersAndPostParams.

@Test
public void headersAndPostParams() throws Exception {
    MockHttpStack mockHttpStack = new MockHttpStack();
    BasicHttpResponse fakeResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 200, "OK");
    fakeResponse.setEntity(new StringEntity("foobar"));
    mockHttpStack.setResponseToReturn(fakeResponse);
    BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
    Request<String> request = new Request<String>(Request.Method.GET, "http://foo", null) {

        @Override
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
            return null;
        }

        @Override
        protected void deliverResponse(String response) {
        }

        @Override
        public Map<String, String> getHeaders() {
            Map<String, String> result = new HashMap<String, String>();
            result.put("requestheader", "foo");
            return result;
        }

        @Override
        public Map<String, String> getParams() {
            Map<String, String> result = new HashMap<String, String>();
            result.put("requestpost", "foo");
            return result;
        }
    };
    httpNetwork.performRequest(request);
    assertEquals("foo", mockHttpStack.getLastHeaders().get("requestheader"));
    assertEquals("requestpost=foo&", new String(mockHttpStack.getLastPostBody()));
}
Also used : StringEntity(org.apache.http.entity.StringEntity) MockHttpStack(com.android.volley.mock.MockHttpStack) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HashMap(java.util.HashMap) Request(com.android.volley.Request) NetworkResponse(com.android.volley.NetworkResponse) ProtocolVersion(org.apache.http.ProtocolVersion) Test(org.junit.Test)

Example 50 with BasicHttpResponse

use of org.apache.http.message.BasicHttpResponse in project android-volley by mcxiaoke.

the class HurlStack method performRequest.

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);
    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) {
        response.setEntity(entityFromConnection(connection));
    }
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }
    return response;
}
Also used : HashMap(java.util.HashMap) IOException(java.io.IOException) ProtocolVersion(org.apache.http.ProtocolVersion) URL(java.net.URL) BasicStatusLine(org.apache.http.message.BasicStatusLine) BasicStatusLine(org.apache.http.message.BasicStatusLine) StatusLine(org.apache.http.StatusLine) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpURLConnection(java.net.HttpURLConnection) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) List(java.util.List) BasicHeader(org.apache.http.message.BasicHeader)

Aggregations

BasicHttpResponse (org.apache.http.message.BasicHttpResponse)72 ProtocolVersion (org.apache.http.ProtocolVersion)51 BasicStatusLine (org.apache.http.message.BasicStatusLine)47 StatusLine (org.apache.http.StatusLine)41 HttpResponse (org.apache.http.HttpResponse)33 StringEntity (org.apache.http.entity.StringEntity)25 Header (org.apache.http.Header)24 List (java.util.List)23 IOException (java.io.IOException)20 HttpHost (org.apache.http.HttpHost)19 URL (java.net.URL)16 BasicHeader (org.apache.http.message.BasicHeader)16 HttpURLConnection (java.net.HttpURLConnection)15 HashMap (java.util.HashMap)15 HttpEntity (org.apache.http.HttpEntity)14 MainResponse (org.elasticsearch.action.main.MainResponse)14 ElasticsearchException (org.elasticsearch.ElasticsearchException)12 RequestLine (org.apache.http.RequestLine)11 BasicRequestLine (org.apache.http.message.BasicRequestLine)11 RestStatus (org.elasticsearch.rest.RestStatus)11