Skip navigation links

cloudant-client 2.0.0 API

See: Description

Packages 
Package Description
com.cloudant.client.api
This package provides the objects for interacting with Cloudant
com.cloudant.client.api.model
This package provides additional objects for interacting with Cloudant
com.cloudant.client.api.views
This package provides access to the view API.
com.cloudant.http
This package provides the classes for interacting with HTTP.

This is the official Cloudant library for java.

Contents

  1. Compatibility
  2. Initialization
    1. Cloudant service example
    2. Cloudant Local example
  3. Authentication
    1. Cookie authentication
    2. Custom authentication
  4. Capabilities
    1. Server Operations
    2. Database Operations
    3. Document Operations
      1. Single document CRUD
      2. Bulk document CRU
    4. Attachments
      1. Standalone Attachments
      2. Inline Attachments
    5. Design Documents
    6. Using Views
    7. Cloudant Query
    8. Cloudant Search
  5. Advanced Configuration
    1. Connection options
    2. Resource sharing
      1. Thread safety
      2. Connection pooling
        1. Default pooling
        2. With OkHttp
    3. J2EE
  6. Project

Compatibility

This library can be used with the following databases

Note that some features are Cloudant specific.

The library is compiled with Java 1.6 compatibility, but it is recommended to run with the latest available Java version.

Initialization

Use the ClientBuilder class to build a CloudantClient instance. The CloudantClient class is the starting point for interacting with Cloudant from Java.

Cloudant service example

When using the managed service at cloudant.com, initialize your Cloudant connection by using ClientBuilder.account(String) supplying the account to connect to. Set additional options for the API key or username and passphrase.

    
    CloudantClient client = ClientBuilder.account("yourCloudantAccount")
            .setUsername("yourAPIKey")
            .setPassword("yourAPIKeyPassphrase")
            .build();
    

Cloudant Local example

When using Cloudant Local, initialize your Cloudant connection by using ClientBuilder.url(URL) supplying the URL of the Cloudant Local. Again set additional options for the user name or API key and passphase.

    
    CloudantClient client = ClientBuilder.url(new URL("https://192.0.2.0"))
            .username("yourAPIKey")
            .password("yourAPIKeyPassphrase")
            .build();
    

Authentication

Using the ClientBuilder.username(String) and ClientBuilder.password(String) options uses cookie authentication for the CloudantClient connection. The supplied credentials are used to request a session with the server and the session is renewed automatically if the cookie expires. If the credentials become invalid then a new instance of a CloudantClient needs to be created.

Custom authentication

If cookie authentication is not desired then it is possible to build the CloudantClient without credentials and use a HttpConnectionInterceptor to customize the HTTP request with the desired authentication mechanism.

An example using Basic Authentication is shown in the javadoc for ClientBuilder.interceptors(HttpConnectionInterceptor[]).

Capabilities

Server Operations

CloudantClient encapsulates the connection to the server and provides access to server operations.

Database Operations

CloudantClient.database(String, boolean) returns a Database object that provides access to database operations.

Document Operations

Single document CRUD

CRUD operations for documents in a database are achieved via the Database object.

Bulk document CRU

Database also provides a bulk documents API for fetching or modifying multiple documents in a single request.

Attachments

See the Cloudant documentation for more information about attachments.

Standalone Attachments

Standalone attachment data is provided as an InputStream. The attachment can be created and either referenced from an existing document or a new document.

Inline Attachments

Inline attachments enclose the attachment data, Base64 encoded, within the document body. The Attachment class represents an inline attachment. Classes that extend Document automatically inherit support for inline attachments.

Example usage of inline attachment, using Apache Commons Codec for Base64 encoding:

    
        Attachment attachment = new Attachment();
        attachment.setData(Base64.encodeBase64String("attachment test string".getBytes()));
        attachment.setContentType("text/plain");
        Foo foo = new Foo(); // Foo extends Document
        foo.addAttachment("attachment.txt", attachment);
        db.save(foo);
    

Note that attachment data is not included by default when reading documents. To retrieve inline attachment data use Params.attachments(). See Database.find(java.lang.Class, java.lang.String, com.cloudant.client.api.model.Params) for an example.

Design Documents

Design documents are used to define server side operations, including querying the database using map-reduce views, Cloudant Search, and Cloudant Query. The results can be retrieved by the client. It is recommend to read the Cloudant design document documentation before working with design documents to gain an understanding of the available parameters and functions.

The DesignDocument class encapsulates a design document in a Java object.

See DesignDocumentManager.get(java.lang.String, java.lang.String) for an example of retrieving a design document from the sever.

Example of creating a view (map-reduce index) using Map to generate the JSON for the design document

    
    // Uploads the design document with view index:
    // {
    //   "_id": "_design/name",
    //   "views": {
    //     "view1": {
    //       "map":"function(doc){emit(doc.field, 1)}",
    //       "reduce": "function(key, value, rereduce){return sum(values)}"
    //     }
    //   }
    // }

    Map<String, Object> view1 = new HashMap<>();
    view1.put("map", "function(doc){emit(doc.field, 1)}");
    view1.put("reduce", "function(key, value, rereduce){return sum(values)}");

    Map<String, Object> views = new HashMap<>();
    views.put("view1", view1);

    Map<String, Object> view_ddoc = new HashMap<>();
    view_ddoc.put("_id", "_design/name");
    view_ddoc.put("views", views);

    db.save(view_ddoc);
    

Using Views

For background information about views please refer to the Cloudant views documentation . Refer to the com.cloudant.client.api.views package for information about and examples of using this library to query a view.

Cloudant Query

This feature interfaces with Cloudant's query functionality. See the Cloudant Query documentation for details.

This feature interfaces with Cloudant's full text search functionality. See the Cloudant Search documentation for details. Searches are based on index functions in design documents.

To create a search index, upload a design document containing the index:

    
    // Uploads the search index:
    // {
    //   "_id": "_design/views101",
    //   "indexes": {
    //     "animals": {
    //       "index": "function(doc){ index(\"default\", doc._id); }"
    //     }
    //   }
    // }

    Map<String, Object> animals = new HashMap<>();
    animals.put("index", "function(doc){ index(\"default\", doc._id); }");

    Map<String, Object> indexes = new HashMap<>();
    indexes.put("animals", animals);

    Map<String, Object> ddoc = new HashMap<>();
    ddoc.put("_id", "_design/searchindex");
    ddoc.put("indexes", indexes);

    db.save(ddoc);
    

To query this index, use an instance of Search by calling Database.search(java.lang.String).

Advanced Configuration

Connection options

The ClientBuilder provides access to additional advanced configuration options for the server connection. For example customized SSL, proxies and timeouts.

Custom GSON serialization

Internally the Gson library is used to serialize/deserialize JSON to/from Java objects. You can supply your own GsonBuilder instance to customize configuration, for example registering custom de-serializers.

Example setting the date/time format Gson uses:

    
    GsonBuilder builder = new GsonBuilder();
    builder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss");

    CloudantClient client = ClientBuilder.account("example").username("user").password("password)
            .gsonBuilder(builder).build();
    

Resource sharing

Thread safety

CloudantClient objects are thread-safe. All methods can be called from any thread, meaning CloudantClient objects can and should be shared across threads. The Database object is thread-safe and a single Database object may be shared across threads.

Connection pooling

Connection pooling behaviour differs depending on whether the optional OkHttp dependency is included. Note that idle connections within the pool may be terminated by the server, so will not remain open indefinitely meaning that this will not completely remove the overhead of creating new connections.

Default pooling

By default the underlying HttpUrlConnection will use the JVM wide connection pool configuration (via the http.maxConnections property). Under these circumstances the pool is shared between all applications in the VM and between all CloudantClient instances.

With OkHttp

When the OkHttp dependency is included then connection pools are managed per CloudantClient instance. The default size of the connection pool is 6. Use ClientBuilder.maxConnections(int) to configure the maximum connections in the pool.

J2EE

This library can be used in J2EE environments, but currently does not implement any J2EE standards or provide wrappers for them. As such there is no built-in support for JCA connection management or JNDI lookups of CloudantClient instances.

To get JNDI support would require a javax.naming.spi.ObjectFactory implementation and configuration of your JNDI provider to register this factory and reference this library.

Project

Please visit the java-cloudant project page for more information.

Skip navigation links