Search in sources :

Example 16 with HttpConnection

use of com.cloudant.http.HttpConnection in project java-cloudant by cloudant.

the class HttpTest method testInputStreamRetry.

private void testInputStreamRetry(HttpConnection request, byte[] expectedContent) throws Exception {
    final MockResponse retry = new MockResponse().setResponseCode(444);
    mockWebServer.enqueue(retry);
    mockWebServer.enqueue(new MockResponse());
    HttpConnection response = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer).interceptors(new HttpConnectionResponseInterceptor() {

        // This interceptor responds to our 444 request with a retry
        @Override
        public HttpConnectionInterceptorContext interceptResponse(HttpConnectionInterceptorContext context) {
            try {
                if (444 == context.connection.getConnection().getResponseCode()) {
                    context.replayRequest = true;
                    // Close the error stream
                    InputStream errors = context.connection.getConnection().getErrorStream();
                    if (errors != null) {
                        IOUtils.closeQuietly(errors);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                fail("IOException getting response code in test interceptor");
            }
            return context;
        }
    }).build().executeRequest(request);
    String responseStr = response.responseAsString();
    assertTrue(responseStr.isEmpty(), "There should be no response body on the mock response");
    assertEquals(200, response.getConnection().getResponseCode(), "The final response code should be 200");
    // We want the second request
    assertEquals(2, mockWebServer.getRequestCount(), "There should have been two requests");
    MockWebServerResources.takeRequestWithTimeout(mockWebServer);
    RecordedRequest rr = MockWebServerResources.takeRequestWithTimeout(mockWebServer);
    assertNotNull(rr, "The request should have been recorded");
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream((int) rr.getBodySize());
    rr.getBody().copyTo(byteArrayOutputStream);
    assertArrayEquals(expectedContent, byteArrayOutputStream.toByteArray(), "The body bytes should have matched after a " + "retry");
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) HttpConnection(com.cloudant.http.HttpConnection) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) HttpConnectionResponseInterceptor(com.cloudant.http.HttpConnectionResponseInterceptor) IOException(java.io.IOException) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HttpConnectionInterceptorContext(com.cloudant.http.HttpConnectionInterceptorContext)

Example 17 with HttpConnection

use of com.cloudant.http.HttpConnection in project java-cloudant by cloudant.

the class HttpTest method testWriteToServerOk.

/*
     * Basic test that we can write a document body by POSTing to a known database
     */
@TestTemplate
public void testWriteToServerOk() throws Exception {
    HttpConnection conn = new HttpConnection("POST", new URL(dbResource.getDbURIWithUserInfo()), "application/json");
    ByteArrayInputStream bis = new ByteArrayInputStream(data.getBytes());
    // nothing read from stream
    assertEquals(data.getBytes().length, bis.available());
    conn.setRequestBody(bis);
    HttpConnection response = conn.execute();
    // Consume response stream
    String responseStr = response.responseAsString();
    String okPattern = ".*\"ok\"\\s*:\\s*true.*";
    assertTrue(Pattern.compile(okPattern, Pattern.DOTALL).matcher(responseStr).matches(), "There should be an ok response: " + "" + responseStr);
    // stream was read to end
    assertEquals(0, bis.available());
    assertEquals(2, response.getConnection().getResponseCode() / 100, "Should be a 2XX response code");
}
Also used : HttpConnection(com.cloudant.http.HttpConnection) ByteArrayInputStream(java.io.ByteArrayInputStream) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) URL(java.net.URL) TestTemplate(org.junit.jupiter.api.TestTemplate)

Example 18 with HttpConnection

use of com.cloudant.http.HttpConnection in project java-cloudant by cloudant.

the class HttpTest method inputStreamRetryGeneratorWithLength.

@TestTemplate
public void inputStreamRetryGeneratorWithLength() throws Exception {
    HttpConnection request = Http.POST(mockWebServer.url("/").url(), "application/json");
    byte[] content = "abcde".getBytes("UTF-8");
    request.setRequestBody(new TestInputStreamGenerator(content), content.length);
    testInputStreamRetry(request, content);
}
Also used : HttpConnection(com.cloudant.http.HttpConnection) TestTemplate(org.junit.jupiter.api.TestTemplate)

Example 19 with HttpConnection

use of com.cloudant.http.HttpConnection in project java-cloudant by cloudant.

the class HttpTest method testBasicAuth.

/**
 * Test that adding the Basic Authentication interceptor to HttpConnection
 * will complete with a response code of 200.  The response input stream
 * is expected to hold the newly created document's id and rev.
 */
@TestTemplate
@RequiresCloudant
public void testBasicAuth() throws IOException {
    BasicAuthInterceptor interceptor = new BasicAuthInterceptor(CloudantClientHelper.COUCH_USERNAME + ":" + CloudantClientHelper.COUCH_PASSWORD);
    HttpConnection conn = new HttpConnection("POST", dbResource.get().getDBUri().toURL(), "application/json");
    conn.requestInterceptors.add(interceptor);
    ByteArrayInputStream bis = new ByteArrayInputStream(data.getBytes());
    // nothing read from stream
    assertEquals(data.getBytes().length, bis.available());
    conn.setRequestBody(bis);
    HttpConnection responseConn = conn.execute();
    // stream was read to end
    assertEquals(0, bis.available());
    assertEquals(2, responseConn.getConnection().getResponseCode() / 100);
    // check the json
    Gson gson = new Gson();
    InputStream is = responseConn.responseAsInputStream();
    try {
        JsonObject response = gson.fromJson(new InputStreamReader(is), JsonObject.class);
        assertTrue(response.has("ok"));
        assertTrue(response.get("ok").getAsBoolean());
        assertTrue(response.has("id"));
        assertTrue(response.has("rev"));
    } finally {
        is.close();
    }
}
Also used : BasicAuthInterceptor(com.cloudant.http.interceptors.BasicAuthInterceptor) InputStreamReader(java.io.InputStreamReader) HttpConnection(com.cloudant.http.HttpConnection) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject) TestTemplate(org.junit.jupiter.api.TestTemplate) RequiresCloudant(com.cloudant.test.main.RequiresCloudant)

Example 20 with HttpConnection

use of com.cloudant.http.HttpConnection in project java-cloudant by cloudant.

the class HttpTest method inputStreamRetryGenerator.

@TestTemplate
public void inputStreamRetryGenerator() throws Exception {
    HttpConnection request = Http.POST(mockWebServer.url("/").url(), "application/json");
    byte[] content = "abcde".getBytes("UTF-8");
    request.setRequestBody(new TestInputStreamGenerator(content));
    testInputStreamRetry(request, content);
}
Also used : HttpConnection(com.cloudant.http.HttpConnection) TestTemplate(org.junit.jupiter.api.TestTemplate)

Aggregations

HttpConnection (com.cloudant.http.HttpConnection)27 TestTemplate (org.junit.jupiter.api.TestTemplate)11 JsonObject (com.google.gson.JsonObject)6 ByteArrayInputStream (java.io.ByteArrayInputStream)6 InputStream (java.io.InputStream)6 IOException (java.io.IOException)5 URI (java.net.URI)5 CoreMatchers.containsString (org.hamcrest.CoreMatchers.containsString)5 URL (java.net.URL)4 CloudantClient (com.cloudant.client.api.CloudantClient)3 DatabaseURIHelper (com.cloudant.client.internal.DatabaseURIHelper)3 HttpConnectionInterceptorContext (com.cloudant.http.HttpConnectionInterceptorContext)3 RequiresCloudant (com.cloudant.test.main.RequiresCloudant)3 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)3 HttpConnectionResponseInterceptor (com.cloudant.http.HttpConnectionResponseInterceptor)2 Gson (com.google.gson.Gson)2 JsonArray (com.google.gson.JsonArray)2 InputStreamReader (java.io.InputStreamReader)2 MockResponse (okhttp3.mockwebserver.MockResponse)2 Test (org.junit.jupiter.api.Test)2