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

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

Introduction

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

Prototype

public String toString() 

Source Link

Usage

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 v  a 2s.  c  o 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));
    }
}