Search in sources :

Example 1 with BasicAuthInterceptor

use of com.cloudant.http.interceptors.BasicAuthInterceptor in project java-cloudant by cloudant.

the class CloudantClientTests method testBasicAuth.

/**
 * Test that adding the Basic Authentication interceptor to CloudantClient works.
 */
@Test
@RequiresCloudant
public void testBasicAuth() throws IOException {
    BasicAuthInterceptor interceptor = new BasicAuthInterceptor(CloudantClientHelper.COUCH_USERNAME + ":" + CloudantClientHelper.COUCH_PASSWORD);
    CloudantClient client = ClientBuilder.account(CloudantClientHelper.COUCH_USERNAME).interceptors(interceptor).build();
    // Test passes if there are no exceptions
    client.getAllDbs();
}
Also used : BasicAuthInterceptor(com.cloudant.http.interceptors.BasicAuthInterceptor) CloudantClient(com.cloudant.client.api.CloudantClient) Test(org.junit.jupiter.api.Test) RequiresCloudant(com.cloudant.test.main.RequiresCloudant)

Example 2 with BasicAuthInterceptor

use of com.cloudant.http.interceptors.BasicAuthInterceptor in project java-cloudant by cloudant.

the class CloudantClientTests method testBasicAuthFromCredentials.

/**
 * Test that configuring the Basic Authentication interceptor from credentials and adding to
 * the CloudantClient works.
 */
@Test
public void testBasicAuthFromCredentials() throws Exception {
    BasicAuthInterceptor interceptor = BasicAuthInterceptor.createFromCredentials("username", "password");
    // send back a mock OK 200
    server.enqueue(new MockResponse());
    CloudantClient client = CloudantClientHelper.newMockWebServerClientBuilder(server).interceptors(interceptor).build();
    client.getAllDbs();
    // expected 'username:password'
    assertEquals("Basic dXNlcm5hbWU6cGFzc3dvcmQ=", server.takeRequest().getHeader("Authorization"));
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) BasicAuthInterceptor(com.cloudant.http.interceptors.BasicAuthInterceptor) CloudantClient(com.cloudant.client.api.CloudantClient) Test(org.junit.jupiter.api.Test)

Example 3 with BasicAuthInterceptor

use of com.cloudant.http.interceptors.BasicAuthInterceptor in project java-cloudant by cloudant.

the class HttpConnection method execute.

/**
 * <p>
 * Execute request without returning data from server.
 * </p>
 * <p>
 * Call {@code responseAsString}, {@code responseAsBytes}, or {@code responseAsInputStream}
 * after {@code execute} if the response body is required.
 * </p>
 * <P>
 * Note if the URL contains user information it will be encoded in a BasicAuth header.
 * </P>
 *
 * @return An {@link HttpConnection} which can be used to obtain the response body
 * @throws IOException if there was a problem writing data to the server
 */
public HttpConnection execute() throws IOException {
    boolean retry = true;
    while (retry && numberOfRetries-- > 0) {
        connection = connectionFactory.openConnection(url);
        if (url.getUserInfo() != null) {
            // Insert at position 0 in case another interceptor wants to overwrite the BasicAuth
            requestInterceptors.add(0, new BasicAuthInterceptor(url.getUserInfo()));
        }
        // always read the result, so we can retrieve the HTTP response code
        connection.setDoInput(true);
        connection.setRequestMethod(requestMethod);
        if (contentType != null) {
            connection.setRequestProperty("Content-type", contentType);
        }
        // context.connection.getConnection().setChunkedStreamingMode(16384);
        if (input != null) {
            connection.setDoOutput(true);
            if (inputLength != -1) {
                // TODO Remove this cast to int when the minimum supported level is 1.7.
                // On 1.7 upwards this method takes a long, otherwise int.
                connection.setFixedLengthStreamingMode((int) this.inputLength);
            } else {
                // Use 0 for the default size
                connection.setChunkedStreamingMode(0);
            // Note that CouchDB does not currently work for a chunked multipart stream, see
            // https://issues.apache.org/jira/browse/COUCHDB-1403. Cases that use
            // multipart need to provide the content length until that is fixed.
            }
        }
        currentContext = (currentContext == null) ? new HttpConnectionInterceptorContext(this) : new HttpConnectionInterceptorContext(this, currentContext.interceptorStates);
        for (HttpConnectionRequestInterceptor requestInterceptor : requestInterceptors) {
            currentContext = requestInterceptor.interceptRequest(currentContext);
        }
        // to the properties map
        for (Map.Entry<String, String> property : requestProperties.entrySet()) {
            connection.setRequestProperty(property.getKey(), property.getValue());
        }
        // Log the request
        if (requestIsLoggable && logger.isLoggable(Level.FINE)) {
            logger.fine(String.format("%s request%s", getLogRequestIdentifier(), (connection.usingProxy() ? " via proxy" : "")));
        }
        // Log the request headers
        if (requestIsLoggable && logger.isLoggable(Level.FINER)) {
            logger.finer(String.format("%s request headers %s", getLogRequestIdentifier(), connection.getRequestProperties()));
        }
        if (input != null) {
            InputStream is = input.getInputStream();
            OutputStream os = connection.getOutputStream();
            try {
                // The buffer size used for writing to this output stream has an impact on the
                // HTTP chunk size, so we make it a pretty large size to avoid limiting the
                // size
                // of those chunks (although this appears in turn to set the chunk sizes).
                IOUtils.copyLarge(is, os, new byte[16 * 1024]);
                os.flush();
            } finally {
                Utils.close(is);
                Utils.close(os);
            }
        }
        // Log the response
        if (requestIsLoggable && logger.isLoggable(Level.FINE)) {
            logger.fine(String.format("%s response %s %s", getLogRequestIdentifier(), connection.getResponseCode(), connection.getResponseMessage()));
        }
        // Log the response headers
        if (requestIsLoggable && logger.isLoggable(Level.FINER)) {
            logger.finer(String.format("%s response headers %s", getLogRequestIdentifier(), connection.getHeaderFields()));
        }
        for (HttpConnectionResponseInterceptor responseInterceptor : responseInterceptors) {
            try {
                currentContext = responseInterceptor.interceptResponse(currentContext);
            } catch (HttpConnectionInterceptorException e) {
                // Sadly the current interceptor API doesn't allow an IOException to be thrown
                // so to avoid swallowing them the interceptors need to wrap them in the runtime
                // HttpConnectionInterceptorException and we can then unwrap them here.
                Throwable cause = e.getCause();
                if (cause != null && cause instanceof IOException) {
                    throw (IOException) cause;
                } else {
                    throw e;
                }
            }
        }
        // retry flag is set from the final step in the response interceptRequest pipeline
        retry = currentContext.replayRequest;
        // makes the connection eligible for re-use.
        if (retry && numberOfRetries > 0) {
            Utils.consumeAndCloseStream(connection.getErrorStream());
        }
        if (numberOfRetries == 0) {
            logger.info("Maximum number of retries reached");
        }
    }
    // return ourselves to allow method chaining
    return this;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) IOException(java.io.IOException) BasicAuthInterceptor(com.cloudant.http.interceptors.BasicAuthInterceptor) HttpConnectionInterceptorException(com.cloudant.http.internal.interceptors.HttpConnectionInterceptorException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 4 with BasicAuthInterceptor

use of com.cloudant.http.interceptors.BasicAuthInterceptor 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)

Aggregations

BasicAuthInterceptor (com.cloudant.http.interceptors.BasicAuthInterceptor)4 CloudantClient (com.cloudant.client.api.CloudantClient)2 RequiresCloudant (com.cloudant.test.main.RequiresCloudant)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 InputStream (java.io.InputStream)2 Test (org.junit.jupiter.api.Test)2 HttpConnection (com.cloudant.http.HttpConnection)1 HttpConnectionInterceptorException (com.cloudant.http.internal.interceptors.HttpConnectionInterceptorException)1 Gson (com.google.gson.Gson)1 JsonObject (com.google.gson.JsonObject)1 IOException (java.io.IOException)1 InputStreamReader (java.io.InputStreamReader)1 OutputStream (java.io.OutputStream)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 MockResponse (okhttp3.mockwebserver.MockResponse)1 TestTemplate (org.junit.jupiter.api.TestTemplate)1