Search in sources :

Example 6 with HttpConnection

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

the class SessionInterceptorExpiryTests method executeTest.

private void executeTest(boolean okUsable, String sessionPath, Long expiryTime, String cookieValue) throws Exception {
    queueResponses(okUsable, sessionPath, expiryTime, cookieValue);
    HttpConnection conn = Http.GET(mockWebServer.url("/").url());
    conn.connectionFactory = (isOkUsable) ? new OkHttpClientHttpUrlConnectionFactory() : new DefaultHttpUrlConnectionFactory();
    conn.requestInterceptors.add(rqInterceptor);
    conn.responseInterceptors.add(rpInterceptor);
    conn = conn.execute();
    // Consume response stream and assert ok: true
    String responseStr = conn.responseAsString();
    String okPattern = ".*\"ok\"\\s*:\\s*true.*";
    assertTrue(Pattern.compile(okPattern, Pattern.DOTALL).matcher(responseStr).matches(), "There should be an ok response: " + responseStr);
    // Assert the _session request
    RecordedRequest sessionRequest = mockWebServer.takeRequest(MockWebServerResources.TIMEOUT, MockWebServerResources.TIMEOUT_UNIT);
    assertEquals(sessionPath, sessionRequest.getPath(), "The interceptor should make a " + "session request");
    assertNull(sessionRequest.getHeader("Cookie"), "There should be no existing cookie on the" + " session request");
    // Assert the GET request
    RecordedRequest getRequest = mockWebServer.takeRequest(MockWebServerResources.TIMEOUT, MockWebServerResources.TIMEOUT_UNIT);
    assertEquals("/", getRequest.getPath(), "The request path should be correct");
    assertNotNull(getRequest.getHeader("Cookie"), "There should be a cookie on the request");
    String expectedCookie = ((sessionPath.equals("/_session")) ? MockWebServerResources.AUTH_COOKIE_NAME : MockWebServerResources.IAM_COOKIE_NAME) + "=" + cookieValue;
    assertEquals(expectedCookie, getRequest.getHeader("Cookie"), "The cookie should be the " + "correct session type");
}
Also used : OkHttpClientHttpUrlConnectionFactory(com.cloudant.http.internal.ok.OkHttpClientHttpUrlConnectionFactory) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) HttpConnection(com.cloudant.http.HttpConnection) DefaultHttpUrlConnectionFactory(com.cloudant.http.internal.DefaultHttpUrlConnectionFactory)

Example 7 with HttpConnection

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

the class CouchDatabaseBase method getAttachment.

/**
 * Reads an attachment from the database.
 *
 * The stream must be closed after usage, otherwise http connection leaks will occur.
 *
 * @param uri the attachment URI
 * @return the attachment in the form of an {@code InputStream}.
 */
private InputStream getAttachment(URI uri) {
    HttpConnection connection = Http.GET(uri);
    couchDbClient.execute(connection);
    try {
        return connection.responseAsInputStream();
    } catch (IOException e) {
        throw new CouchDbException("Error retrieving response input stream.", e);
    }
}
Also used : HttpConnection(com.cloudant.http.HttpConnection) IOException(java.io.IOException)

Example 8 with HttpConnection

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

the class CouchDatabaseBase method bulk.

/**
 * Performs a Bulk Documents insert request.
 *
 * @param objects      The {@link List} of objects.
 * @param allOrNothing Indicates whether the request has <tt>all-or-nothing</tt> semantics.
 * @return {@code List<Response>} Containing the resulted entries.
 */
public List<Response> bulk(List<?> objects, boolean allOrNothing) {
    assertNotEmpty(objects, "objects");
    InputStream responseStream = null;
    HttpConnection connection;
    try {
        final JsonObject jsonObject = new JsonObject();
        if (allOrNothing) {
            jsonObject.addProperty("all_or_nothing", true);
        }
        final URI uri = new DatabaseURIHelper(dbUri).bulkDocsUri();
        jsonObject.add("docs", getGson().toJsonTree(objects));
        connection = Http.POST(uri, "application/json");
        if (jsonObject.toString().length() != 0) {
            connection.setRequestBody(jsonObject.toString());
        }
        couchDbClient.execute(connection);
        responseStream = connection.responseAsInputStream();
        List<Response> bulkResponses = getResponseList(responseStream, getGson(), DeserializationTypes.LC_RESPONSES);
        for (Response response : bulkResponses) {
            response.setStatusCode(connection.getConnection().getResponseCode());
            response.setReason(connection.getConnection().getResponseMessage());
        }
        return bulkResponses;
    } catch (IOException e) {
        throw new CouchDbException("Error retrieving response input stream.", e);
    } finally {
        close(responseStream);
    }
}
Also used : CouchDbUtil.getResponse(com.cloudant.client.org.lightcouch.internal.CouchDbUtil.getResponse) HttpConnection(com.cloudant.http.HttpConnection) InputStream(java.io.InputStream) JsonObject(com.google.gson.JsonObject) DatabaseURIHelper(com.cloudant.client.internal.DatabaseURIHelper) IOException(java.io.IOException) URI(java.net.URI)

Example 9 with HttpConnection

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

the class CouchDbClient method put.

/**
 * Performs a HTTP PUT request, saves or updates a document.
 *
 * @param object    Object for updating request
 * @param newEntity If true, saves a new document. Else, updates an existing one.
 * @return {@link Response}
 */
public Response put(URI uri, Object object, boolean newEntity, int writeQuorum) {
    assertNotEmpty(object, "object");
    final JsonObject json = getGson().toJsonTree(object).getAsJsonObject();
    String id = getAsString(json, "_id");
    String rev = getAsString(json, "_rev");
    if (newEntity) {
        // save
        assertNull(rev, "rev");
        id = (id == null) ? generateUUID() : id;
    } else {
        // update
        assertNotEmpty(id, "id");
        assertNotEmpty(rev, "rev");
    }
    URI httpUri = null;
    if (writeQuorum > -1) {
        httpUri = new DatabaseURIHelper(uri).documentUri(id, "w", writeQuorum);
    } else {
        httpUri = new DatabaseURIHelper(uri).documentUri(id);
    }
    HttpConnection connection = Http.PUT(httpUri, "application/json");
    connection.setRequestBody(json.toString());
    return executeToResponse(connection);
}
Also used : HttpConnection(com.cloudant.http.HttpConnection) JsonObject(com.google.gson.JsonObject) DatabaseURIHelper(com.cloudant.client.internal.DatabaseURIHelper) CouchDbUtil.getAsString(com.cloudant.client.org.lightcouch.internal.CouchDbUtil.getAsString) URI(java.net.URI)

Example 10 with HttpConnection

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

the class CouchDbClient method put.

/**
 * Performs a HTTP PUT request, saves an attachment.
 *
 * @return {@link Response}
 */
Response put(URI uri, InputStream instream, String contentType) {
    HttpConnection connection = Http.PUT(uri, contentType);
    connection.setRequestBody(instream);
    return executeToResponse(connection);
}
Also used : HttpConnection(com.cloudant.http.HttpConnection)

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