Example usage for org.apache.http.message BasicStatusLine BasicStatusLine

List of usage examples for org.apache.http.message BasicStatusLine BasicStatusLine

Introduction

In this page you can find the example usage for org.apache.http.message BasicStatusLine BasicStatusLine.

Prototype

public BasicStatusLine(ProtocolVersion protocolVersion, int i, String str) 

Source Link

Usage

From source file:org.esigate.http.HttpClientRequestExecutorTest.java

private HttpResponse createMockGzippedResponse(String content) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gzos = new GZIPOutputStream(baos);
    byte[] uncompressedBytes = content.getBytes();
    gzos.write(uncompressedBytes, 0, uncompressedBytes.length);
    gzos.close();//from w ww . j  av  a2 s .co  m
    byte[] compressedBytes = baos.toByteArray();
    ByteArrayEntity httpEntity = new ByteArrayEntity(compressedBytes);
    httpEntity.setContentType("text/html; charset=ISO-8859-1");
    httpEntity.setContentEncoding("gzip");
    StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("p", 1, 2), HttpStatus.SC_OK, "OK");
    BasicHttpResponse httpResponse = new BasicHttpResponse(statusLine);
    httpResponse.addHeader("Content-type", "text/html; charset=ISO-8859-1");
    httpResponse.addHeader("Content-encoding", "gzip");
    httpResponse.setEntity(httpEntity);
    return httpResponse;
}

From source file:com.android.volley.toolbox.AuthenticationChallengesProofHurlStack.java

@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());//from  www . j  av a 2 s. c o  m
    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);

    /************************/
    /****** WORKAROUND ******/
    int responseCode;

    try {
        // Will throw IOException if server responds with 401.
        responseCode = connection.getResponseCode();
    } catch (IOException e) {
        // You can get the response code after an exception if you call .getResponseCode()
        // a second time on the connection object. This is because the first time you
        // call .getResponseCode() an internal state is set that enables .getResponseCode()
        // to return without throwing an exception.
        responseCode = connection.getResponseCode();
    }
    /************************/

    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // 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);
    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;
}

From source file:org.finra.herd.tools.common.databridge.DataBridgeWebClientTest.java

@Test
public void testGetBusinessObjectDataStorageFilesCreateResponse200BadContentReturnsNull() throws Exception {
    CloseableHttpResponse httpResponse = new MockCloseableHttpResponse(
            new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "testReasonPhrase"), false);
    httpResponse.setEntity(new StringEntity("invalid xml"));

    executeWithoutLogging(DataBridgeWebClient.class, () -> {
        BusinessObjectDataStorageFilesCreateResponse businessObjectDataStorageFilesCreateResponse = dataBridgeWebClient
                .getBusinessObjectDataStorageFilesCreateResponse(httpResponse);
        assertNull("businessObjectDataStorageFilesCreateResponse",
                businessObjectDataStorageFilesCreateResponse);
    });/*w  w  w.  j av  a 2s. com*/
}

From source file:org.eluder.coveralls.maven.plugin.httpclient.CoverallsClientTest.java

@Test(expected = ProcessingException.class)
public void testParseErrorousResponse() throws Exception {
    StatusLine statusLine = new BasicStatusLine(HttpVersion.HTTP_1_1, 400, "Bad Request");
    when(httpClientMock.execute(any(HttpUriRequest.class))).thenReturn(httpResponseMock);
    when(httpResponseMock.getStatusLine()).thenReturn(statusLine);
    when(httpResponseMock.getEntity()).thenReturn(httpEntityMock);
    when(httpEntityMock.getContent())/*from w ww. ja va 2 s.c  om*/
            .thenReturn(coverallsResponse(new CoverallsResponse("failure", true, "submission failed")));
    CoverallsClient client = new CoverallsClient("http://test.com/coveralls", httpClientMock,
            new ObjectMapper());
    client.submit(file);
}

From source file:org.apache.camel.component.hipchat.HipchatComponentConsumerTest.java

@Test
public void sendInOnlyMultipleUsers() throws Exception {
    result.expectedMessageCount(1);//from w w  w . j  a va  2s. c om
    String expectedResponse = "{\n" + "  \"items\" : [\n" + "    {\n"
            + "      \"date\" : \"2015-01-19T22:07:11.030740+00:00\",\n" + "      \"from\" : {\n"
            + "        \"id\" : 1647095,\n" + "        \"links\" : {\n"
            + "          \"self\" : \"https://api.hipchat.com/v2/user/1647095\"\n" + "        },\n"
            + "        \"mention_name\" : \"notifier\",\n" + "        \"name\" : \"Message Notifier\"\n"
            + "      },\n" + "      \"id\" : \"6567c6f7-7c1b-43cf-bed0-792b1d092919\",\n"
            + "      \"mentions\" : [ ],\n" + "      \"message\" : \"Unit test Alert\",\n"
            + "      \"type\" : \"message\"\n" + "    }\n" + "  ],\n" + "  \"links\" : {\n"
            + "    \"self\" : \"https://api.hipchat.com/v2/user/%40ShreyasPurohit/history/latest\"\n" + "  },\n"
            + "  \"maxResults\" : 1,\n" + "  \"startIndex\" : 0\n" + "}";
    HttpEntity mockHttpEntity = mock(HttpEntity.class);
    when(mockHttpEntity.getContent())
            .thenReturn(new ByteArrayInputStream(expectedResponse.getBytes(StandardCharsets.UTF_8)));
    when(closeableHttpResponse.getEntity()).thenReturn(mockHttpEntity);
    when(closeableHttpResponse.getStatusLine())
            .thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, ""));

    assertMockEndpointsSatisfied();

    assertCommonResultExchange(result.getExchanges().get(0));
}

From source file:co.cask.cdap.client.rest.RestClientTest.java

@Test
public void testInternalServerErrorResponseCodeAnalysis() {

    StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1),
            HttpStatus.SC_INTERNAL_SERVER_ERROR, "Internal Server Error");
    when(response.getStatusLine()).thenReturn(statusLine);
    TestUtils.verifyResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, response);
    verify(response).getStatusLine();// ww  w.  j  a v  a  2s .  c  o  m
}

From source file:com.betfair.cougar.client.HttpClientExecutableTest.java

private void mockHttpResponse(final HttpUriRequest request, final String response, final int responseCode) {
    final HttpResponse httpResponse = mock(HttpResponse.class);
    final HttpEntity entity = mock(HttpEntity.class);
    final StatusLine statusLine = new BasicStatusLine(HttpVersion.HTTP_1_1, responseCode, "");
    when(httpResponse.getEntity()).thenReturn(entity);
    when(httpResponse.getStatusLine()).thenReturn(statusLine);

    final Header cougarHeader = mock(Header.class);
    when(cougarHeader.getValue()).thenReturn("Cougar 2");
    when(httpResponse.containsHeader("Server")).thenReturn(true);
    when(httpResponse.getFirstHeader("Server")).thenReturn(cougarHeader);

    try {/*ww  w .ja  v  a  2  s . c  om*/
        final byte[] responseBytes = response.getBytes("UTF-8");
        when(entity.getContent()).thenReturn(new ByteArrayInputStream(responseBytes));
        when(entity.getContentLength()).thenReturn((long) responseBytes.length);
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }

    try {
        when(mockHttpClient.execute(request)).thenReturn(httpResponse);
    } catch (final Exception e1) {
        fail();
    }
}

From source file:common.net.volley.toolbox.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();

    stethoManager = new StethoURLConnectionManager(url);

    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());/*w w  w  .  j a v  a  2s . c  o  m*/
    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);
    requestDecompression(connection);

    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) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // 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());

    stethoManager.postConnect();

    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    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;
}

From source file:com.baseproject.volley.toolbox.HurlStack.java

@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());/*from   ww  w . j a v  a  2  s  . co  m*/
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException(Util.buildHttpErrorMsg("failed", -1, "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) {
    // // -1 is returned by getResponseCode() if the response code could not be retrieved.
    // // Signal to the caller that something was wrong with the connection.
    // throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    // }
    if (responseCode != HttpStatus.SC_NOT_MODIFIED && responseCode != HttpURLConnection.HTTP_OK) {
        InputStream in = null;
        try {
            in = connection.getErrorStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (in == null) {
            throw new IOException(Util.buildHttpErrorMsg("failed", responseCode, "unknown"));
        } else {
            throw new IOException(Util.convertStreamToString(in));
        }
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            if (header.getKey().equals("Set-Cookie")) {
                List<String> cookieValue = header.getValue();
                for (String c : cookieValue) {
                    Header h = new BasicHeader(header.getKey(), c);
                    response.addHeader(h);
                }
            } else {
                Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
                response.addHeader(h);
            }
        }
    }
    return response;
}

From source file:org.elasticsearch.client.RequestLoggerTests.java

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";
    }//from   w  w  w  .j a va2  s.co  m
    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));
    }
}