Search in sources :

Example 66 with ProtocolVersion

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

the class RequestLoggerTests method testTraceResponse.

public void testTraceResponse() throws IOException {
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int statusCode = randomIntBetween(200, 599);
    String reasonPhrase = "REASON";
    BasicStatusLine statusLine = new BasicStatusLine(protocolVersion, statusCode, reasonPhrase);
    String expected = "# " + statusLine.toString();
    BasicHttpResponse httpResponse = new BasicHttpResponse(statusLine);
    int numHeaders = randomIntBetween(0, 3);
    for (int i = 0; i < numHeaders; i++) {
        httpResponse.setHeader("header" + i, "value");
        expected += "\n# header" + i + ": value";
    }
    expected += "\n#";
    boolean hasBody = getRandom().nextBoolean();
    String responseBody = "{\n  \"field\": \"value\"\n}";
    if (hasBody) {
        expected += "\n# {";
        expected += "\n#   \"field\": \"value\"";
        expected += "\n# }";
        HttpEntity entity;
        switch(randomIntBetween(0, 2)) {
            case 0:
                entity = new StringEntity(responseBody, ContentType.APPLICATION_JSON);
                break;
            case 1:
                //test a non repeatable entity
                entity = new InputStreamEntity(new ByteArrayInputStream(responseBody.getBytes(StandardCharsets.UTF_8)), ContentType.APPLICATION_JSON);
                break;
            case 2:
                // Evil entity without a charset
                entity = new StringEntity(responseBody, ContentType.create("application/json", (Charset) null));
                break;
            default:
                throw new UnsupportedOperationException();
        }
        httpResponse.setEntity(entity);
    }
    String traceResponse = RequestLogger.buildTraceResponse(httpResponse);
    assertThat(traceResponse, equalTo(expected));
    if (hasBody) {
        //check that the body is still readable as most entities are not repeatable
        String body = EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
        assertThat(body, equalTo(responseBody));
    }
}
Also used : NStringEntity(org.apache.http.nio.entity.NStringEntity) StringEntity(org.apache.http.entity.StringEntity) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpEntity(org.apache.http.HttpEntity) ByteArrayInputStream(java.io.ByteArrayInputStream) ProtocolVersion(org.apache.http.ProtocolVersion) BasicStatusLine(org.apache.http.message.BasicStatusLine) InputStreamEntity(org.apache.http.entity.InputStreamEntity)

Example 67 with ProtocolVersion

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

the class RemoteScrollableHitSourceTests method sourceWithMockedRemoteCall.

/**
     * Creates a hit source that doesn't make the remote request and instead returns data from some files. Also requests are always returned
     * synchronously rather than asynchronously.
     */
@SuppressWarnings("unchecked")
private RemoteScrollableHitSource sourceWithMockedRemoteCall(boolean mockRemoteVersion, ContentType contentType, String... paths) throws Exception {
    URL[] resources = new URL[paths.length];
    for (int i = 0; i < paths.length; i++) {
        resources[i] = Thread.currentThread().getContextClassLoader().getResource("responses/" + paths[i].replace("fail:", ""));
        if (resources[i] == null) {
            throw new IllegalArgumentException("Couldn't find [" + paths[i] + "]");
        }
    }
    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>>() {

        int responseCount = 0;

        @Override
        public Future<HttpResponse> answer(InvocationOnMock invocationOnMock) throws Throwable {
            // Throw away the current thread context to simulate running async httpclient's thread pool
            threadPool.getThreadContext().stashContext();
            HttpAsyncRequestProducer requestProducer = (HttpAsyncRequestProducer) invocationOnMock.getArguments()[0];
            FutureCallback<HttpResponse> futureCallback = (FutureCallback<HttpResponse>) invocationOnMock.getArguments()[3];
            HttpEntityEnclosingRequest request = (HttpEntityEnclosingRequest) requestProducer.generateRequest();
            URL resource = resources[responseCount];
            String path = paths[responseCount++];
            ProtocolVersion protocolVersion = new ProtocolVersion("http", 1, 1);
            if (path.startsWith("fail:")) {
                String body = Streams.copyToString(new InputStreamReader(request.getEntity().getContent(), StandardCharsets.UTF_8));
                if (path.equals("fail:rejection.json")) {
                    StatusLine statusLine = new BasicStatusLine(protocolVersion, RestStatus.TOO_MANY_REQUESTS.getStatus(), "");
                    BasicHttpResponse httpResponse = new BasicHttpResponse(statusLine);
                    futureCallback.completed(httpResponse);
                } else {
                    futureCallback.failed(new RuntimeException(body));
                }
            } else {
                StatusLine statusLine = new BasicStatusLine(protocolVersion, 200, "");
                HttpResponse httpResponse = new BasicHttpResponse(statusLine);
                httpResponse.setEntity(new InputStreamEntity(FileSystemUtils.openFileURLStream(resource), contentType));
                futureCallback.completed(httpResponse);
            }
            return null;
        }
    });
    return sourceWithMockedClient(mockRemoteVersion, httpClient);
}
Also used : InputStreamReader(java.io.InputStreamReader) 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) Matchers.containsString(org.hamcrest.Matchers.containsString) ProtocolVersion(org.apache.http.ProtocolVersion) URL(java.net.URL) BasicStatusLine(org.apache.http.message.BasicStatusLine) InputStreamEntity(org.apache.http.entity.InputStreamEntity) StatusLine(org.apache.http.StatusLine) BasicStatusLine(org.apache.http.message.BasicStatusLine) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpAsyncRequestProducer(org.apache.http.nio.protocol.HttpAsyncRequestProducer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest) CloseableHttpAsyncClient(org.apache.http.impl.nio.client.CloseableHttpAsyncClient) ScheduledFuture(java.util.concurrent.ScheduledFuture) Future(java.util.concurrent.Future) FutureCallback(org.apache.http.concurrent.FutureCallback)

Example 68 with ProtocolVersion

use of org.apache.http.ProtocolVersion 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 69 with ProtocolVersion

use of org.apache.http.ProtocolVersion 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)

Example 70 with ProtocolVersion

use of org.apache.http.ProtocolVersion in project iosched by google.

the class BasicNetworkTest method testHeadersAndPostParams.

public void testHeadersAndPostParams() 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)

Aggregations

ProtocolVersion (org.apache.http.ProtocolVersion)113 BasicStatusLine (org.apache.http.message.BasicStatusLine)54 BasicHttpResponse (org.apache.http.message.BasicHttpResponse)43 StatusLine (org.apache.http.StatusLine)42 Test (org.junit.Test)33 Header (org.apache.http.Header)26 HttpEntity (org.apache.http.HttpEntity)26 HttpResponse (org.apache.http.HttpResponse)22 StringEntity (org.apache.http.entity.StringEntity)20 URL (java.net.URL)16 BasicHeader (org.apache.http.message.BasicHeader)16 IOException (java.io.IOException)15 HttpURLConnection (java.net.HttpURLConnection)15 List (java.util.List)15 HashMap (java.util.HashMap)14 HttpHost (org.apache.http.HttpHost)12 ParseException (org.apache.http.ParseException)12 HttpEntityEnclosingRequest (org.apache.http.HttpEntityEnclosingRequest)11 MockHttpStack (com.android.volley.mock.MockHttpStack)10 HttpRequest (org.apache.http.HttpRequest)10