com.cloudant.client.api.CloudantClient Java Examples

The following examples show how to use com.cloudant.client.api.CloudantClient. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DatabaseTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
@Test
public void permissionsParsing() throws Exception {
    CloudantClient client = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer)
            .build();
    Database db = client.database("notarealdb", false);

    // Mock up a request of all permissions
    mockWebServer.enqueue(MockWebServerResources.PERMISSIONS); // for GET _security
    mockWebServer.enqueue(MockWebServerResources.JSON_OK); // for PUT _security
    db.setPermissions("testUsername", EnumSet.allOf(Permissions.class));

    // Mock up a failing request
    String testError = "test error";
    String testReason = "test reason";
    mockWebServer.enqueue(MockWebServerResources.PERMISSIONS); // for GET _security
    mockWebServer.enqueue(new MockResponse().setResponseCode(400).setBody("{\"reason\":\"" +
            testReason + "\", \"error\":\"" + testError + "\"}"));
    try {
        db.setPermissions("testUsername", EnumSet.allOf(Permissions.class));
    } catch (CouchDbException e) {
        assertEquals(testError, e.getError());
        assertEquals(testReason, e.getReason());
    }
}
 
Example #2
Source File: DesignDocumentsTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
/**
 * Test that a CouchDbException is thrown if an IOException is encountered when trying to get
 * revision information for a design document removal.
 *
 * @throws Exception
 */
@Test
public void couchDbExceptionIfIOExceptionDuringDDocRemove() throws Exception {
    assertThrows(CouchDbException.class, new Executable() {
        @Override
        public void execute() throws Throwable {
            CloudantClient mockClient = CloudantClientHelper.newMockWebServerClientBuilder
                    (mockWebServer).readTimeout(50, TimeUnit.MILLISECONDS).build();
            // Cause a read timeout to generate an IOException
            mockWebServer.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE));
            Database database = mockClient.database(dbResource.getDatabaseName(), false);
            // Try to remove a design document by id only, generates a HEAD request for
            // revision info
            database.getDesignDocumentManager().remove("example");
        }
    });
}
 
Example #3
Source File: TestUtility.java    From chatbot with Apache License 2.0 6 votes vote down vote up
public static Application.Helper getHelper() throws Exception {
    if(systemProperties.containsKey("PROP_FILE")) {
        properties.load(new FileInputStream(systemProperties.get("PROP_FILE")));
    }

    CloudantClient cloudantClient = ClientBuilder
            .url(new URL(getProperty("cloudant.url")))
            .username(getProperty("cloudant.username"))
            .password(getProperty("cloudant.password"))
            .build();
    WolframRepository wolframRepository = new WolframRepository(getProperty("wolfram.apiKey"));
    return new Application.Helper(
            cloudantClient,
            wolframRepository,
            getProperty("cloudant.chatDB"),
            getProperty("cloudant.feedbackDB"),
            getProperty("cloudant.explorerDB"),
            getProperty("tmdb.apiKey")
    );
}
 
Example #4
Source File: HttpIamTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
/**
 * Test IAM token and cookie flow:
 * - GET a resource on the cloudant server
 * - Cookie jar empty, so get IAM token followed by session cookie
 * - GET now proceeds as normal, expected cookie value is sent in header
 *
 * @throws Exception
 */
@Test
public void iamTokenAndCookieSuccessful() throws Exception {

    // Request sequence
    // _iam_session request to get Cookie
    // GET request -> 200 with a Set-Cookie
    mockWebServer.enqueue(OK_IAM_COOKIE);
    mockWebServer.enqueue(new MockResponse().setResponseCode(200)
            .setBody(hello));

    mockIamServer.enqueue(new MockResponse().setResponseCode(200).setBody(IAM_TOKEN));

    CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer)
            .iamApiKey(IAM_API_KEY)
            .build();

    String response = c.executeRequest(Http.GET(c.getBaseUri())).responseAsString();
    assertEquals(hello, response, "The expected response should be received");

    MockWebServerResources.assertMockIamRequests(mockWebServer, mockIamServer);
}
 
Example #5
Source File: DbInfoMockTests.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
/**
 * Make sure disk_size using sizes works
 */
@Test
public void getDbInfoSizes() {
    CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(server).build();
    Database db = c.database("animaldb", false);

    MockResponse response = new MockResponse()
            .setResponseCode(200)
            .setBody("{\"sizes\": {\"active\": 21, \"external\":22, \"file\": 23}}");
    server.enqueue(response);

    DbInfo info = db.info();
    assertEquals(21L, info.getSizes().getActive(), "The mock active disk size should be 21");
    assertEquals(22L, info.getSizes().getExternal(), "The mock external disk size should be 22");
    assertEquals(23L, info.getSizes().getFile(), "The mock file disk size should be 23");
}
 
Example #6
Source File: HttpTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
/**
 * Test that the default maximum number of retries is reached and the backoff is of at least the
 * expected duration.
 *
 * @throws Exception
 */
@TestTemplate
public void test429BackoffMaxDefault() throws Exception {

    // Always respond 429 for this test
    mockWebServer.setDispatcher(MockWebServerResources.ALL_429);

    TestTimer t = TestTimer.startTimer();
    try {
        CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer)
                .interceptors(Replay429Interceptor.WITH_DEFAULTS)
                .build();
        String response = c.executeRequest(Http.GET(c.getBaseUri())).responseAsString();
        fail("There should be a TooManyRequestsException instead had response " + response);
    } catch (TooManyRequestsException e) {
        long duration = t.stopTimer(TimeUnit.MILLISECONDS);
        // 3 backoff periods for 4 attempts: 250 + 500 + 1000 = 1750 ms
        assertTrue(duration >=
                1750, "The duration should be at least 1750 ms, but was " + duration);
        assertEquals(4, mockWebServer
                .getRequestCount(), "There should be 4 request attempts");
    }
}
 
Example #7
Source File: ReplicatorMockTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
@Test
public void createAndSaveReplicatorDocumentWithSourceIamAuth() throws Exception {
    server.enqueue(JSON_OK);

    CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(server)
            .build();

    c.replicator()
            .replicatorDocId(replicatorDocId)
            .source(sourceDbUrl)
            .sourceIamApiKey(IAM_API_KEY)
            .target(targetDbUrl)
            .save();

    RecordedRequest[] requests = takeN(server, 1);

    assertEquals(requests[0].getPath(), "/_replicator/" + replicatorDocId);

    String body = requests[0].getBody().readUtf8();

    assertThat("The replication document should contain the source IAM API key",
            body, containsString(authJson + IAM_API_KEY));

    assertThat("The replication document should contain the correct target",
            body, containsString("\"target\":\"" + targetDbUrl + "\""));
}
 
Example #8
Source File: HttpTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
@TestTemplate
public void testCookieRenewOnPost() throws Exception {

    mockWebServer.enqueue(OK_COOKIE);
    mockWebServer.enqueue(new MockResponse().setResponseCode(403).setBody
            ("{\"error\":\"credentials_expired\", \"reason\":\"Session expired\"}\r\n"));
    mockWebServer.enqueue(OK_COOKIE);
    mockWebServer.enqueue(new MockResponse());

    CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer)
            .username("a")
            .password("b")
            .build();

    HttpConnection request = Http.POST(mockWebServer.url("/").url(), "application/json");
    request.setRequestBody("{\"some\": \"json\"}");
    HttpConnection response = c.executeRequest(request);
    String responseStr = response.responseAsString();
    assertTrue(responseStr.isEmpty(), "There should be no response body on the mock response");
    response.getConnection().getResponseCode();
}
 
Example #9
Source File: ReplicatorMockTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
@Test
public void createAndSaveReplicatorDocumentWithSimpleSelector() throws Exception {
    server.enqueue(JSON_OK);

    CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(server)
            .build();

    c.replicator()
            .replicatorDocId(replicatorDocId)
            .source(sourceDbUrl)
            .target(targetDbUrl)
            .selector(eq("_id", "Schwarzenegger"))
            .save();

    RecordedRequest[] requests = takeN(server, 1);

    assertEquals(requests[0].getPath(), "/_replicator/" + replicatorDocId);

    String body = requests[0].getBody().readUtf8();

    assertThat("The replication document should contain the selector", body,
            containsString(",\"selector\":{\"_id\":{\"$eq\":\"Schwarzenegger\"}},"));
}
 
Example #10
Source File: CloudFoundryServiceTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
@Test
public void vcapMultiServiceUsingIAM() throws Exception{
    VCAPGenerator vcap = new CloudFoundryServiceTest.VCAPGenerator();
    vcap.createNewLegacyService("test_bluemix_service_1", "foo1.bar", "admin1", "pass1");
    vcap.createNewLegacyService("test_bluemix_service_2", "foo2.bar", "admin2", "pass2");
    vcap.createNewLegacyService("test_bluemix_service_3",
            mockServerHostPort,
            "user", "password");
    vcap.createNewService("test_bluemix_service_4", "admin4", "api1234key");
    vcap.createNewService("test_bluemix_service_5", mockServerHostPort,
            IAM_API_KEY);
    CloudantClient client = ClientBuilder
            .bluemix(vcap.toJson(), "test_bluemix_service_5")
            .disableSSLAuthentication()
            .build();
    this.testMockInfoRequest(client, false);
    // One request to _iam_session then one to get server info
    assertEquals(2, server.getRequestCount(), "There should be two requests");
}
 
Example #11
Source File: HttpTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
/**
 * Test that an integer number of seconds delay specified by a Retry-After header is honoured.
 *
 * @throws Exception
 */
@TestTemplate
public void test429BackoffRetryAfter() throws Exception {

    mockWebServer.enqueue(MockWebServerResources.get429().addHeader("Retry-After", "1"));
    mockWebServer.enqueue(new MockResponse());

    TestTimer t = TestTimer.startTimer();
    CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer)
            .interceptors(Replay429Interceptor.WITH_DEFAULTS)
            .build();
    String response = c.executeRequest(Http.GET(c.getBaseUri())).responseAsString();
    assertTrue(response.isEmpty(), "There should be no response body on the mock response");

    long duration = t.stopTimer(TimeUnit.MILLISECONDS);
    assertTrue(duration >=
            1000, "The duration should be at least 1000 ms, but was " + duration);
    assertEquals(2, mockWebServer
            .getRequestCount(), "There should be 2 request attempts");
}
 
Example #12
Source File: HttpTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
@TestTemplate
public void test429IgnoreRetryAfter() throws Exception {
    mockWebServer.enqueue(MockWebServerResources.get429().addHeader("Retry-After", "1"));
    mockWebServer.enqueue(new MockResponse());

    TestTimer t = TestTimer.startTimer();
    CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer)
            .interceptors(new Replay429Interceptor(1, 1, false))
            .build();

    String response = c.executeRequest(Http.GET(c.getBaseUri())).responseAsString();
    assertTrue(response.isEmpty(), "There should be no response body on the mock response");

    long duration = t.stopTimer(TimeUnit.MILLISECONDS);
    assertTrue(duration <
            1000, "The duration should be less than 1000 ms, but was " + duration);
    assertEquals(2, mockWebServer
            .getRequestCount(), "There should be 2 request attempts");
}
 
Example #13
Source File: CloudantClientTests.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
/**
 * 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"));
}
 
Example #14
Source File: HttpTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
/**
 * Test that having no body and hence no error stream on a 401 response correctly results in a
 * 401 cookie renewal without a NPE.
 *
 * @throws Exception
 */
@TestTemplate
public void noErrorStream401() throws Exception {

    // Respond with a cookie init to the first request to _session
    mockWebServer.enqueue(OK_COOKIE);
    // Respond to the executeRequest GET of / with a 401 with no body
    mockWebServer.enqueue(new MockResponse().setResponseCode(401));
    // 401 triggers a renewal so respond with a new cookie for renewal request to _session
    mockWebServer.enqueue(OK_COOKIE);
    // Finally respond 200 OK with body of "TEST" to the replay of GET to /
    mockWebServer.enqueue(new MockResponse().setBody("TEST"));

    CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer)
            .username("a")
            .password("b")
            .build();

    String response = c.executeRequest(Http.GET(c.getBaseUri())).responseAsString();
    assertEquals("TEST", response, "The expected response body should be received");
}
 
Example #15
Source File: CloudFoundryServiceTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
@Test
public void vcapValidServiceNameSpecified() throws Exception {
    //server.enqueue(MockWebServerResources.OK_COOKIE);
    String serviceName = "serviceFoo";
    VCAPGenerator vcap = new CloudFoundryServiceTest.VCAPGenerator(serviceName);
    vcap.createNewLegacyService("test_bluemix_service_1",
            String.format("%s:%s/", server.getHostName(), server.getPort()),
            "user", "password");
    CloudantClient client = ClientBuilder
            .bluemix(vcap.toJson(), serviceName, "test_bluemix_service_1")
            .disableSSLAuthentication()
            .build();
    this.testMockInfoRequest(client, true);
    // One request to _session then one to get server info
    assertEquals(2, server.getRequestCount(), "There should be two requests");
}
 
Example #16
Source File: HttpIamTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
/**
 * Assert that the IAM API key is preferred to username/password if both are supplied.
 * As above test but with different builder arguments.
 *
 * @throws Exception
 */
@Test
public void iamApiKeyPreferredToUsernamePassword() throws Exception {

    // Request sequence
    // _iam_session request to get Cookie
    // GET request -> 200 with a Set-Cookie
    mockWebServer.enqueue(OK_IAM_COOKIE);
    mockWebServer.enqueue(new MockResponse().setResponseCode(200)
            .setBody(hello));

    mockIamServer.enqueue(new MockResponse().setResponseCode(200).setBody(IAM_TOKEN));

    CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer)
            .username("username")
            .password("password")
            .iamApiKey(IAM_API_KEY)
            .build();

    String response = c.executeRequest(Http.GET(c.getBaseUri())).responseAsString();
    assertEquals(hello, response, "The expected response should be received");

    MockWebServerResources.assertMockIamRequests(mockWebServer, mockIamServer);
}
 
Example #17
Source File: DatabaseTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
@Test
public void customGsonDeserializerTest() throws MalformedURLException {
    GsonBuilder builder = new GsonBuilder();
    builder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss");

    CloudantClient account = CloudantClientHelper.getClientBuilder()
            .gsonBuilder(builder)
            .build();

    Database db = account.database(dbResource.getDatabaseName(), false);

    Map<String, Object> h = new HashMap<String, Object>();
    h.put("_id", "serializertest");
    h.put("date", "2015-01-23T18:25:43.511Z");
    db.save(h);

    db.find(Foo.class, "serializertest"); // should not throw a JsonSyntaxException

}
 
Example #18
Source File: CloudantClientTests.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
/**
 * Checks that the read timeout works. The test sets a read timeout of 0.25 s and the mock
 * server thread never sends a response. If things are working
 * correctly then the client should see a SocketTimeoutException for the read.
 */
@Test
public void readTimeout() throws Throwable {
    assertThrows(SocketTimeoutException.class, new Executable() {
        @Override
        public void execute() throws Throwable {
            // Don't respond so the read will timeout
            server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE));
            try {
                CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(server)
                        .readTimeout(25, TimeUnit.MILLISECONDS).build();

                //do a call that expects a response
                c.getAllDbs();
            } catch (CouchDbException e) {
                //unwrap the CouchDbException
                if (e.getCause() != null) {
                    throw e.getCause();
                } else {
                    throw e;
                }
            }
        }
    });
}
 
Example #19
Source File: ReplicationMockTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
@Test
public void createAndTriggerReplicationWithSourceIamAuth() throws Exception {
    server.enqueue(JSON_OK);

    CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(server)
            .build();

    c.replication()
            .source(sourceDbUrl)
            .sourceIamApiKey(IAM_API_KEY)
            .target(targetDbUrl)
            .trigger();

    RecordedRequest[] requests = takeN(server, 1);

    assertEquals(requests[0].getPath(), "/_replicate");

    String body = requests[0].getBody().readUtf8();

    assertThat("The replication document should contain the source IAM API key",
            body, containsString(authJson + IAM_API_KEY));

    assertThat("The replication document should contain the correct target",
            body, containsString("\"target\":\"" + targetDbUrl + "\""));
}
 
Example #20
Source File: ReplicationMockTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
@Test
public void createAndTriggerReplicationWithTargetIamAuth() throws Exception {
    server.enqueue(JSON_OK);

    CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(server)
            .build();

    c.replication()
            .source(sourceDbUrl)
            .target(targetDbUrl)
            .targetIamApiKey(IAM_API_KEY)
            .trigger();

    RecordedRequest[] requests = takeN(server, 1);

    assertEquals(requests[0].getPath(), "/_replicate");

    String body = requests[0].getBody().readUtf8();

    assertThat("The replication document should contain the source IAM API key",
            body, containsString("\"source\":\"" + sourceDbUrl + "\""));

    assertThat("The replication document should contain the correct target",
            body, containsString(authJson + IAM_API_KEY));
}
 
Example #21
Source File: ReplicationMockTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
@Test
public void createAndTriggerReplicationWithSourceAndTargetIamAuth() throws Exception {
    server.enqueue(JSON_OK);

    CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(server)
            .build();

    c.replication()
            .source(sourceDbUrl)
            .sourceIamApiKey(IAM_API_KEY)
            .target(targetDbUrl)
            .targetIamApiKey(IAM_API_KEY_2)
            .trigger();

    RecordedRequest[] requests = takeN(server, 1);

    assertEquals(requests[0].getPath(), "/_replicate");

    String body = requests[0].getBody().readUtf8();

    assertThat("The replication document should contain the source IAM API key",
            body, containsString(authJson + IAM_API_KEY));

    assertThat("The replication document should contain the target IAM API key",
            body, containsString(authJson + IAM_API_KEY_2));
}
 
Example #22
Source File: SslAuthenticationTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
/**
 * Connect to the local simple https server with SSL authentication disabled.
 */
@TestTemplate
public void localSslAuthenticationDisabled() throws Exception {

    // Build a client that connects to the mock server with SSL authentication disabled
    CloudantClient dbClient = CloudantClientHelper.newMockWebServerClientBuilder(server)
            .disableSSLAuthentication()
            .build();

    // Queue a 200 OK response
    server.enqueue(new MockResponse());

    // Make an arbitrary connection to the DB.
    dbClient.getAllDbs();

    // Test is successful if no exception is thrown, so no explicit check is needed.
}
 
Example #23
Source File: SslAuthenticationTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
/**
 * Connect to the local simple https server with SSL authentication enabled explicitly.
 * This should throw an exception because the SSL authentication fails.
 */
@TestTemplate
public void localSslAuthenticationEnabled() throws Exception {

    CouchDbException thrownException = null;
    try {
        CloudantClient dbClient = CloudantClientHelper.newMockWebServerClientBuilder(server)
                .build();

        // Queue a 200 OK response
        server.enqueue(new MockResponse());

        // Make an arbitrary connection to the DB.
        dbClient.getAllDbs();
    } catch (CouchDbException e) {
        thrownException = e;
    }
    validateClientAuthenticationException(thrownException);
}
 
Example #24
Source File: ReplicatorMockTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
@Test
public void createAndSaveReplicatorDocumentWithTargetIamAuth() throws Exception {
    server.enqueue(JSON_OK);

    CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(server)
            .build();

    c.replicator()
            .replicatorDocId(replicatorDocId)
            .source(sourceDbUrl)
            .target(targetDbUrl)
            .targetIamApiKey(IAM_API_KEY_2)
            .save();

    RecordedRequest[] requests = takeN(server, 1);

    assertEquals(requests[0].getPath(), "/_replicator/" + replicatorDocId);

    String body = requests[0].getBody().readUtf8();

    assertThat("The replication document should contain the source IAM API key",
            body, containsString("\"source\":\"" + sourceDbUrl + "\""));

    assertThat("The replication document should contain the correct target",
            body, containsString(authJson + IAM_API_KEY_2));
}
 
Example #25
Source File: ChangeNotificationsTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
/**
 * Test that a custom parameter can be added to a changes request.
 */
@Test
public void changesCustomParameter() throws Exception {
    CloudantClient client = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer)
            .build();
    Database db = client.database("notreal", false);
    // Mock up an empty set of changes
    mockWebServer.enqueue(new MockResponse().setBody("{\"results\": []}"));
    db.changes().filter("myFilter").parameter("myParam", "paramValue").getChanges();
    RecordedRequest request = mockWebServer.takeRequest(1, TimeUnit.SECONDS);
    assertNotNull(request, "There should be a changes request");
    assertTrue(request.getPath()
            .contains("filter=myFilter"), "There should be a filter parameter on the request");
    assertTrue(request.getPath()
            .contains("myParam=paramValue"), "There should be a custom parameter on the " +
            "request");
}
 
Example #26
Source File: ChangeNotificationsTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
/**
 * Test that the descending true parameter is applied and the results are returned in reverse
 * order.
 */
@Test
public void changesDescending() throws Exception {

    CloudantClient client = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer)
            .build();
    Database db = client.database("notreal", false);

    // Mock up an empty set of changes
    mockWebServer.enqueue(new MockResponse().setBody("{\"results\": []}"));
    db.changes().descending(true).getChanges();
    RecordedRequest request = mockWebServer.takeRequest(1, TimeUnit.SECONDS);
    assertNotNull(request, "There should be a changes request");
    assertTrue(request.getPath()
            .contains("descending=true"), "There should be a descending parameter on the " +
            "request");
}
 
Example #27
Source File: SslAuthenticationTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
/**
 * Repeat the localSSLAuthenticationEnabled, but with the cookie auth enabled.
 * This test validates that the SSL settings also get applied to the cookie interceptor.
 */
@TestTemplate
public void localSSLAuthenticationEnabledWithCookieAuth() throws Exception {

    // Mock up an OK cookie response then an OK response for the getAllDbs()
    server.enqueue(MockWebServerResources.OK_COOKIE);
    server.enqueue(new MockResponse()); //OK 200

    // Use a username and password to enable the cookie auth interceptor
    CloudantClient dbClient = CloudantClientHelper.newMockWebServerClientBuilder(server)
            .username("user")
            .password("password")
            .build();

    CouchDbException e = assertThrows(CouchDbException.class, () -> dbClient.getAllDbs(),
            "The SSL authentication failure should result in a RuntimeException.");
    validateClientAuthenticationException(e);
}
 
Example #28
Source File: ViewsMockTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
/**
 * We can't test the server behaviour of stale, but we can test the URL values are what we
 * expect. This test uses the various values and checks the stale parameter in the URL, it makes
 * a request using getSingleValue() as it is easier to mock the responses.
 *
 * @throws Exception
 */
@Test
public void staleParameterValues() throws Exception {
    CloudantClient client = CloudantClientHelper.newMockWebServerClientBuilder(server)
        .build();
    Database database = client.database("notarealdb", false);
    for (String s : new String[]{
            SettableViewParameters.STALE_NO,
            SettableViewParameters.STALE_OK,
            SettableViewParameters.STALE_UPDATE_AFTER}) {
        UnpaginatedRequestBuilder<String, Integer> viewBuilder = database.getViewRequestBuilder
                ("testDDoc", "testView").newRequest(Key.Type.STRING, Integer.class);
        MockResponse mockResponse = new MockResponse().setResponseCode(200).setBody
                ("{\"rows\":[{\"key\":null,\"value\":10}]}");
        server.enqueue(mockResponse);
        viewBuilder.stale(s).build().getSingleValue();
        HttpUrl url = server.takeRequest(1, TimeUnit.SECONDS).getRequestUrl();
        Assert.assertEquals(s, url.queryParameter("stale"));
        Assert.assertEquals("/notarealdb/_design/testDDoc/_view/testView", url.encodedPath());
    }
}
 
Example #29
Source File: ViewsMockTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
/**
 * Similar to staleParameterValues, but for `stable` parameter
 * @throws Exception
 */
@Test
public void stableParameterValues() throws Exception {
    CloudantClient client = CloudantClientHelper.newMockWebServerClientBuilder(server)
            .build();
    Database database = client.database("notarealdb", false);
    for (Boolean b : new Boolean[]{
            false,
            true}) {
        UnpaginatedRequestBuilder<String, Integer> viewBuilder = database.getViewRequestBuilder
                ("testDDoc", "testView").newRequest(Key.Type.STRING, Integer.class);
        MockResponse mockResponse = new MockResponse().setResponseCode(200).setBody
                ("{\"rows\":[{\"key\":null,\"value\":10}]}");
        server.enqueue(mockResponse);
        viewBuilder.stable(b).build().getSingleValue();
        HttpUrl url = server.takeRequest(1, TimeUnit.SECONDS).getRequestUrl();
        Assert.assertEquals(Boolean.toString(b), url.queryParameter("stable"));
        Assert.assertEquals("/notarealdb/_design/testDDoc/_view/testView", url.encodedPath());
    }
}
 
Example #30
Source File: CloudFoundryServiceTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
@Test
public void vcapMultiService() throws Exception {
    VCAPGenerator vcap = new CloudFoundryServiceTest.VCAPGenerator();
    vcap.createNewLegacyService("test_bluemix_service_1", "foo1.bar", "admin1", "pass1");
    vcap.createNewLegacyService("test_bluemix_service_2", "foo2.bar", "admin2", "pass2");
    vcap.createNewLegacyService("test_bluemix_service_3",
            mockServerHostPort,
            "user", "password");
    vcap.createNewService("test_bluemix_service_4", "admin4", "api1234key");
    vcap.createNewService("test_bluemix_service_5", mockServerHostPort,
            "api1234key");
    CloudantClient client = ClientBuilder
            .bluemix(vcap.toJson(), "test_bluemix_service_3")
            .disableSSLAuthentication()
            .build();
    this.testMockInfoRequest(client, true);
    // One request to _session then one to get server info
    assertEquals(2, server.getRequestCount(), "There should be two requests");
}