Search in sources :

Example 21 with HttpConnection

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

the class HttpTest method testReadBeforeExecute.

/*
     * Basic test to check that an IOException is thrown when we attempt to get the response
     * without first calling execute()
     */
@TestTemplate
public void testReadBeforeExecute() 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);
    try {
        String response = conn.responseAsString();
        fail("IOException not thrown as expected instead had response " + response);
    } catch (IOException ioe) {
        // "Attempted to read response from server before calling execute()"
        ;
    }
    // stream was not read because execute() was not called
    assertEquals(data.getBytes().length, bis.available());
}
Also used : HttpConnection(com.cloudant.http.HttpConnection) ByteArrayInputStream(java.io.ByteArrayInputStream) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) IOException(java.io.IOException) URL(java.net.URL) TestTemplate(org.junit.jupiter.api.TestTemplate)

Example 22 with HttpConnection

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

the class LoggingTest method urlRegexLogging.

@Test
public void urlRegexLogging() throws Exception {
    // Set the regex filter property on the LogManager and assert it was set
    String urlFilterPropName = "com.cloudant.http.filter.url";
    String urlFilterPropValue = ".*/testdb.*";
    setAndAssertLogProperty(urlFilterPropName, urlFilterPropValue);
    // Configure HttpConnection logging and get a client
    logger = setupLogger(HttpConnection.class, Level.FINE);
    // Make a request to testdb
    client.executeRequest(Http.GET(new URL(client.getBaseUri().toString() + "/testdb"))).responseAsString();
    // Check there were two log messages one for request and one for response
    assertEquals(2, handler.logEntries.size(), "There should be 2 log messages");
    // Check the messages were the ones we expected
    assertHttpMessage("GET .*/testdb request", 0);
    assertHttpMessage("GET .*/testdb response 200 OK", 1);
    // Store the current log size
    int logsize = handler.logEntries.size();
    // Make a second request to a different URL and check that nothing else was logged
    client.executeRequest(Http.GET(client.getBaseUri())).responseAsString();
    assertEquals(logsize, handler.logEntries.size(), "There should have been no more log " + "entries");
}
Also used : HttpConnection(com.cloudant.http.HttpConnection) URL(java.net.URL) Test(org.junit.jupiter.api.Test)

Example 23 with HttpConnection

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

the class ResponseTest method testJsonErrorStreamFromLB.

/**
 * Test that an error stream is correctly assigned to a CouchDbException error field if it comes
 * directly from the lb and not the service.
 * <P>
 * This is a Cloudant service test, where a HTTP proxy may send an error.
 * We can provoke it into doing so by sending an invalid HTTP request - in this case an
 * invalid header field.
 * Originally these errors were wrapped in HTML and so exercised a different path - they are now
 * JSON body responses like most other Cloudant requests so should be on the normal exception
 * handling path, but it is worth checking that we do work with these error types.
 * </P>
 */
@RequiresCloudant
@Test
public void testJsonErrorStreamFromLB() throws Exception {
    final AtomicBoolean badHeaderEnabled = new AtomicBoolean(false);
    CloudantClient c = CloudantClientHelper.getClientBuilder().interceptors(new HttpConnectionRequestInterceptor() {

        @Override
        public HttpConnectionInterceptorContext interceptRequest(HttpConnectionInterceptorContext context) {
            if (badHeaderEnabled.get()) {
                // Note space is also a bad char, but OkHttp prohibits them
                String badHeaderCharacters = "()<>@,;\\/[]?=";
                // set a header using characters that are not permitted
                context.connection.requestProperties.put(badHeaderCharacters, badHeaderCharacters);
            }
            return context;
        }
    }).build();
    try {
        // Make a good request, which will set up the session etc
        HttpConnection d = c.executeRequest(Http.GET(c.getBaseUri()));
        d.responseAsString();
        assertTrue(d.getConnection().getResponseCode() / 100 == 2, "The first request should " + "succeed");
        // Enable the bad headers and expect the exception on the next request
        badHeaderEnabled.set(true);
        String response = c.executeRequest(Http.GET(c.getBaseUri())).responseAsString();
        fail("A CouchDbException should be thrown, but had response " + response);
    } catch (CouchDbException e) {
        // we expect a CouchDbException
        assertEquals(400, e.getStatusCode(), "The exception should be for a bad request");
        assertNotNull(e.getError(), "The exception should have an error set");
        assertEquals("bad_request", e.getError(), "The exception error should be bad request");
    } finally {
        // Disable the bad header to allow a clean shutdown
        badHeaderEnabled.set(false);
        c.shutdown();
    }
}
Also used : HttpConnectionRequestInterceptor(com.cloudant.http.HttpConnectionRequestInterceptor) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CouchDbException(com.cloudant.client.org.lightcouch.CouchDbException) CloudantClient(com.cloudant.client.api.CloudantClient) HttpConnection(com.cloudant.http.HttpConnection) HttpConnectionInterceptorContext(com.cloudant.http.HttpConnectionInterceptorContext) Test(org.junit.jupiter.api.Test) RequiresCloudant(com.cloudant.test.main.RequiresCloudant)

Example 24 with HttpConnection

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

the class CloudantClientTests method credentialsCheck.

private void credentialsCheck(ClientBuilder b, String encodedUser, String encodedPassword) throws Exception {
    CloudantClient c = b.build();
    server.enqueue(MockWebServerResources.OK_COOKIE);
    server.enqueue(MockWebServerResources.JSON_OK);
    HttpConnection conn = c.executeRequest(Http.GET(c.getBaseUri()));
    // Consume response stream and assert ok: true
    String responseStr = conn.responseAsString();
    assertNotNull(responseStr);
    // One request to _session then one to get info
    assertEquals(2, server.getRequestCount(), "There should be two requests");
    // Get the _session request
    RecordedRequest request = server.takeRequest();
    String body = request.getBody().readUtf8();
    // body should be of form:
    // name=YourUserName&password=YourPassword
    Matcher m = CREDENTIALS.matcher(body);
    assertTrue(m.matches(), "The _session request should match the regex");
    assertEquals(2, m.groupCount(), "There should be a username group and a password group in" + " the creds");
    assertEquals(encodedUser, m.group(1), "The username should match");
    assertEquals(encodedPassword, m.group(2), "The password should match");
    // ensure that building a URL from it does not throw any exceptions
    new URL(c.getBaseUri().toString());
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) CloudantClient(com.cloudant.client.api.CloudantClient) HttpConnection(com.cloudant.http.HttpConnection) Matcher(java.util.regex.Matcher) URL(java.net.URL)

Example 25 with HttpConnection

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

the class CookieInterceptorBase method requestCookie.

protected boolean requestCookie(HttpConnectionInterceptorContext context, URL url, byte[] payload, String mimeType, String accept, OnExecuteCallable onResponseOk) {
    try {
        HttpConnection conn = Http.POST(url, mimeType);
        conn.requestProperties.put("accept", accept);
        conn.setRequestBody(payload);
        // when we request the session we need all interceptors except this one
        conn.requestInterceptors.addAll(context.connection.requestInterceptors);
        conn.requestInterceptors.remove(this);
        conn.responseInterceptors.addAll(context.connection.responseInterceptors);
        conn.responseInterceptors.remove(this);
        HttpConnection connection = conn.execute();
        int responseCode = connection.getConnection().getResponseCode();
        if (responseCode / 100 == 2) {
            return onResponseOk.call(connection);
        } else {
            // Consume the error stream to avoid leaking connections
            String error = Utils.collectAndCloseStream(connection.getConnection().getErrorStream());
            // Log the error stream content
            logger.fine(error);
            if (responseCode == 401) {
                logger.log(Level.SEVERE, "Credentials are incorrect for server {0}, cookie " + "authentication will not be attempted again by this interceptor " + "object", url);
            } else {
                // catch any other response code
                logger.log(Level.SEVERE, "Failed to get cookie from server {0}, response code" + " {1}, cookie authentication will not be attempted again", new Object[] { url, responseCode });
            }
        }
    } catch (IOException e) {
        logger.log(Level.SEVERE, "Failed to read cookie response", e);
    }
    return false;
}
Also used : HttpConnection(com.cloudant.http.HttpConnection) IOException(java.io.IOException)

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