Java Code Examples for com.cloudant.client.api.CloudantClient#getAllDbs()

The following examples show how to use com.cloudant.client.api.CloudantClient#getAllDbs() . 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: HttpTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
@TestTemplate
public void testCustomHeader() throws Exception {
    mockWebServer.enqueue(new MockResponse());
    final String headerName = "Test-Header";
    final String headerValue = "testHeader";
    CloudantClient client = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer)
            .interceptors(new HttpConnectionRequestInterceptor() {

                @Override
                public HttpConnectionInterceptorContext interceptRequest
                        (HttpConnectionInterceptorContext context) {
                    context.connection.requestProperties.put(headerName, headerValue);
                    return context;
                }
            }).build();
    client.getAllDbs();
    assertEquals(1, mockWebServer.getRequestCount(), "There should have been 1 request");
    RecordedRequest request = MockWebServerResources.takeRequestWithTimeout(mockWebServer);
    assertNotNull(request, "The recorded request should not be null");
    assertNotNull(request.getHeader(headerName), "The custom header should have been present");
    assertEquals(headerValue, request
            .getHeader(headerName), "The custom header should have the specified value");
}
 
Example 2
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 3
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 4
Source File: SslAuthenticationTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
/**
 * Repeat the localSSLAuthenticationDisabled, but with the cookie auth enabled.
 * This test validates that the SSL settings also get applied to the cookie interceptor.
 */
@TestTemplate
public void localSSLAuthenticationDisabledWithCookieAuth() 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")
            .disableSSLAuthentication()
            .build();

    dbClient.getAllDbs();
}
 
Example 5
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 6
Source File: HttpTest.java    From java-cloudant with Apache License 2.0 5 votes vote down vote up
/**
 * Test that a response stream from a successful _session request is consumed and closed.
 *
 * @throws Exception
 */
@TestTemplate
public void successfulSessionStreamClose() throws Exception {
    // Queue a mock response for the _session request
    mockWebServer.enqueue(OK_COOKIE);
    // Queue a mock response for an _all_dbs request
    mockWebServer.enqueue(new MockResponse().setBody("[]"));

    final AtomicReference<InputStream> responseStream = new AtomicReference<InputStream>();
    CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer)
            .interceptors(new HttpConnectionResponseInterceptor() {
                @Override
                public HttpConnectionInterceptorContext interceptResponse(HttpConnectionInterceptorContext context) {
                    try {
                        // Store the response stream from the session request
                        if (context.connection.url.toString().contains("_session")) {
                            HttpURLConnection conn = context.connection.getConnection();
                            responseStream.set(context.connection.getConnection().getInputStream());
                        }
                    } catch (IOException e) {
                        fail("IOException in test interceptor.");
                    }
                    return context;
                }
            })
            .username("a")
            .password("b")
            .build();
    // Make a request to init the session
    List<String> dbs = c.getAllDbs();
    // Get the response stream from the session request
    InputStream stream = responseStream.get();
    // Assert that the stream has been consumed
    assertEquals(0, stream.available(), "There should be no bytes available from the stream.");
    // Assert that the stream is closed
    assertThrows(IOException.class,
            () -> stream.read(),
            "Reading the stream should throw an IOException because the stream should be " +
                    "closed.");
}
 
Example 7
Source File: SslAuthenticationTest.java    From java-cloudant with Apache License 2.0 5 votes vote down vote up
/**
 * Connect to the remote Cloudant server with SSL Authentication enabled.
 * This shouldn't throw an exception as the Cloudant server has a valid
 * SSL certificate, so should be authenticated.
 */
@TestTemplate
@RequiresCloudantService
public void remoteSslAuthenticationEnabledTest() {

    CloudantClient dbClient = CloudantClientHelper.getClientBuilder().build();

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

    // Test is successful if no exception is thrown, so no explicit check is needed.
}
 
Example 8
Source File: SslAuthenticationTest.java    From java-cloudant with Apache License 2.0 5 votes vote down vote up
/**
 * Connect to the remote Cloudant server with SSL Authentication disabled.
 */
@TestTemplate
@RequiresCloudantService
public void remoteSslAuthenticationDisabledTest() {

    CloudantClient dbClient = CloudantClientHelper.getClientBuilder()
            .disableSSLAuthentication()
            .build();

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

    // Test is successful if no exception is thrown, so no explicit check is needed.
}
 
Example 9
Source File: CloudantClientTests.java    From java-cloudant with Apache License 2.0 5 votes vote down vote up
/**
 * Test that adding the Basic Authentication interceptor to CloudantClient works.
 */
@Test
@DisabledWithIam
@RequiresCloudant
public void testBasicAuth() throws IOException {
    BasicAuthInterceptor interceptor =
            new BasicAuthInterceptor(CloudantClientHelper.SERVER_USER
                    + ":" + CloudantClientHelper.SERVER_PASSWORD);

    CloudantClient client = ClientBuilder.account(CloudantClientHelper.SERVER_USER)
            .interceptors(interceptor).build();

    // Test passes if there are no exceptions
    client.getAllDbs();
}
 
Example 10
Source File: CloudantClientTests.java    From java-cloudant with Apache License 2.0 5 votes vote down vote up
@Test
public void gatewayStyleURL() throws Exception {

    final String gatewayPath = "/gateway";

    // Set a dispatcher that returns 200 if the requests have the correct path /gateway/_all_dbs
    // Otherwise return 400.
    server.setDispatcher(new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            if (request.getPath().equals(gatewayPath + "/_all_dbs")) {
                return new MockResponse();
            } else {
                return new MockResponse().setResponseCode(400);
            }
        }
    });

    // Build a client with a URL that includes a path
    CloudantClient c = ClientBuilder.url(new URL(server.url(gatewayPath).toString())).build();
    // If the request path is wrong this call will return 400 and throw an exception failing the
    // test.
    c.getAllDbs();

    // Build a client with a URL that includes a path with a trailing /
    c = ClientBuilder.url(new URL(server.url(gatewayPath + "/").toString())).build();
    // If the request path is wrong this call will return 400 and throw an exception failing the
    // test.
    c.getAllDbs();
}
 
Example 11
Source File: HttpTest.java    From java-cloudant with Apache License 2.0 4 votes vote down vote up
/**
 * This test checks that only a single session renewal request is made on expiry.
 * Flow:
 * - First request to _all_dbs
 *   - sends a _session request and gets OK_COOKIE
 *   - _all_dbs returns ["a"]
 * - Multi-threaded requests to root endpoint
 *   - Any that occur before session renewal get a 401 unauthorized and try to renew the session
 *   - a _session request will return OK_COOKIE_2 but can only be invoked once for test purposes
 *   - any requests after session renewal will get an OK response
 *
 * @throws Exception
 */
@TestTemplate
public void singleSessionRequestOnExpiry() throws Exception {
    final AtomicInteger sessionCounter = new AtomicInteger();
    mockWebServer.setDispatcher(new Dispatcher() {

        // Use 444 response for error cases as we know this will get an exception without retries
        private final MockResponse FAIL = new MockResponse().setStatus("HTTP/1.1 444 session locking fail");

        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            if (request.getPath().endsWith("_session")) {
                int session = sessionCounter.incrementAndGet();
                switch (session) {
                    case 1:
                        return OK_COOKIE;
                    case 2:
                        return OK_COOKIE_2;
                    default:
                        return FAIL;
                }
            } else if (request.getPath().endsWith("_all_dbs")) {
                return new MockResponse().setBody("[\"a\"]");
            } else {
                String cookie = request.getHeader("COOKIE");
                if (cookie.contains(EXPECTED_OK_COOKIE)) {
                    // Request in first session
                    return new MockResponse().setResponseCode(401);
                } else if (cookie.contains(EXPECTED_OK_COOKIE_2)) {
                    // Request in second session, return OK
                    return new MockResponse();
                } else {
                    return FAIL;
                }
            }
        }
    });

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

    // Do a single request to start the first session
    c.getAllDbs();

    // Now run lots of requests simultaneously
    int threads = 25;
    int requests = 1250;

    ExecutorService executorService = Executors.newFixedThreadPool(threads);

    List<ServerInfoCallable> tasks = new ArrayList<ServerInfoCallable>(requests);
    for (int i = 0; i < requests; i++) {
        tasks.add(new ServerInfoCallable(c));
    }
    List<Future<Throwable>> results = executorService.invokeAll(tasks);
    for (Future<Throwable> result : results) {
        assertNull(result.get(), "There should be no exceptions.");
    }
    assertEquals(2, sessionCounter.get(), "There should only be 2 session requests");
}