Couchbase Java Client Library 1.1
The Java client library provides fast access to documents in Couchbase Server 2.0. With JSON documents and Couchbase server 2.0 you have new ways to index and query data stored in the cluster through views. These view(s) can be accessed using the newly defined View and Query objects.
You can provide different perspsectives to the data. For example, on the sample beer data, you can sort by category, ABV and so on depending on your taste!
Step 0: Get a Server
Get & Install Couchbase Server. Come back here when you're done.
Step 1: Get a Client Library
The Java client libraries have been updated to be compatible with Couchbase Server 2.0 Developer Preview. It adds new features through the View and Query objects which enable to you to access your data with simple Javascript Map-Reduce based views.
See the server developer documentation for information on creating views and the getting started guide for information on how to use the client library.
Get the client library and its dependencies. It can either be downloaded as a zipfile or you could use Maven. This client depends on spymemcached-2.8.12, netty-3.5.5.Final, httpcore-4.1.1, httpcore-nio-4.1.1, jettison-1.1 and commons-codec-1.5. These dependencies have been bundled in the zipfile.
Step 2: Try it out!
-
Create an Eclipse or NetBeans project and set up the Couchbase Client Libraries as referenced libraries. You'll need to include the libraries at compile time. -
Write a simple program to demonstrate connecting to Couchbase and saving some data. Explore some of the API methods that will take you further than the simple program. - Define a view and how to access it using the View and Query objects in a Java program.
- Using the Couchbase Web Console, for information on using the Couchbase Administrative Console,
- Couchbase CLI, for the command line interface,
- Couchbase REST API, for creating and managing Couchbase resources.
Hello Couchbase
You might be curious what the simplest Java program to talk to Couchbase might look like, and how you might compile and run it.
We will create a connection and we will look at some of the operations that the library supports. The asynchronous operations return a Future object. You can wait for the operation to complete and check the status of the operation.
Listing 1: Main.java
import java.io.IOException;
import java.net.URI;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import net.spy.memcached.internal.OperationFuture;
public class App {
// the unique key of the document
public static final String KEY = "beer_Wrath";
// expiration time of the document (use 0 to persist forever)
public static final int EXP_TIME = 10;
// the JSON encoded document
public static final String VALUE =
"{\"name\":\"Wrath\",\"abv\":9.0,"
+ "\"type\":\"beer\",\"brewery_id\":\"110f1a10e7\","
+ "\"updated\":\"2010-07-22 20:00:20\","
+ "\"description\":\"WRATH Belgian-style \","
+ "\"style\":\"Other Belgian-Style Ales\","
+ "\"category\":\"Belgian and French Ale\"}";
public static void main(String args[]) {
// Set the URIs and get a client
List<URI> uris = new LinkedList<URI>();
// Connect to localhost or to the appropriate URI(s)
uris.add(URI.create("http://192.168.1.101:8091/pools"));
uris.add(URI.create("http://192.168.1.102:8091/pools"));
CouchbaseClient client = null;
try {
// Use the "default" bucket with no password
client = new CouchbaseClient(uris, "default", "");
} catch (IOException e) {
System.err.println("IOException connecting to Couchbase: " + e.getMessage());
System.exit(1);
}
// Do an asynchronous set
OperationFuture<Boolean> setOp = client.set(KEY, EXP_TIME, VALUE);
// Check to see if our set succeeded
try {
if (setOp.get().booleanValue()) {
System.out.println("Set Succeeded");
} else {
System.err.println("Set failed: " + setOp.getStatus().getMessage());
}
} catch (InterruptedException e) {
System.err.println("InterruptedException while doing set: " + e.getMessage());
} catch (ExecutionException e) {
System.err.println("ExecutionException while doing set: " + e.getMessage());
}
// Shutdown and wait a maximum of three seconds to finish up operations
client.shutdown(3, TimeUnit.SECONDS);
System.exit(0);
}
}
-
Enter the code in listing 1 into a file. -
Ensure that the main executable file, all the client libraries for Java and dependencies is included in the classpath for your IDE. -
Or you could t ype the following commands for instance:
Main.java
shell> java -cp .:couchbase-client-1.1.6.jar:spymemcached-2.8.12.jar:\
jettison-1.1.jar:netty-3.5.5.Final.jar:commons-codec-1.5.jar:\
httpcore-4.1.1.jar:httpcore-nio-4.1.1.jar Main
Of course, substitute your own Couchbase server IP address. If you are on Linux or Mac OS X replace the semi-colon in the second command-line with a colon.
If you want to make your life easier, Couchbase provides a Maven repository through which you can import the Client SDK and all its dependencies very easily. The documentation on how to do this can be found in the manual here.
The program shows how to do an asynchronous set. We persist a JSON object of type beer, with a key of beer_Wrath. It does an asynchronous set operation with the set() operation as below which returns an OperationFuture object.
OperationFuture<Boolean> setOp = client.set(KEY, EXP_TIME, VALUE);
try {
if (setOp.get().booleanValue()) {
System.out.println("Set Succeeded");
} else {
System.err.println("Set failed: " + setOp.getStatus().getMessage());
}
} catch (InterruptedException e) {
System.err.println("InterruptedException while doing set: " + e.getMessage());
} catch (ExecutionException e) {
System.err.println("ExecutionException while doing set: " + e.getMessage());
}
Persisting JSON using Java
CRUD Operations with JSON
In this section we will look at how to Create, Read, Update and Delete (CRUD) JSON-based documents.
These program snippets assume that Couchbase Server 2.0 is installed and the sample data which is contained in beer-sample is created and ready for use. The beer-sample data can be installed either during the initial wizard or loaded later through the Web-UI under "Settings/Sample Buckets".
Working with Views
if (doc.type && doc.name && doc.type == "beer") {
emit(doc.name, meta.id);
}
}
// CouchbaseClient client = new CouchbaseClient(...);
// Load the View "by_name" from the design doc "beer"
View view = client.getView("beer", "by_name");
// Create a new View Query
Query query = new Query();
query.setKey("Wrath"); // Only retreive this specific key
query.setIncludeDocs(true); // Include the full document as well
// Query the Cluster and return the View Response
ViewResponse result = client.query(view, query);
// Iterate over the results and print out some info
Iterator<ViewRow> itr = result.iterator();
Gson gson = new Gson();
while(itr.hasNext()) {
ViewRow row = itr.next();
// Print out some infos about the document
System.out.println("The Key is: " + row.getKey());
System.out.println("The full document is: " + row.getDocument());
// Convert it back to an object with gson
Beer beer = gson.fromJson( (String) row.getDocument(), Beer.class);
System.out.println("Hi, my name is " + beer.name + "!");
}
client.replace(beerId, 0, gson.toJson(beer));
Then Learn More:
The full getting started guide will cover additional getting started information. From there, move on to the tutorial, which will show how to build a full application on Couchbase Server with a JSON dataset, sample views, and modifying data.