Wednesday, May 27, 2015

Cloudant DB and Java on Bluemix

Dependencies


I've added this dependency to my Maven POM file:
<dependency>
 <groupId>com.cloudant</groupId>
 <artifactId>cloudant-client</artifactId>
 <version>1.0.1</version>
</dependency>



Java Client


Assuming a POJO named MyDoc with two fields
{ private String _id, private java.util.Collection lines }
this client will add and retrieve an instance of the class:
public class CloudantTest {

 public static final String DBNAME = "my-db";

 public static LogManager logger = new LogManager(CloudantTest.class);

 public static void main(String... args) throws Throwable {

  String url = ... ;
  String username = ... ;
  String password = ... ;

  CloudantClient client = new CloudantClient(url, username, password);
  logger.debug("Connected to Cloudant:\n\turl = %s\n\tserver-version = %s", url, client.serverVersion());

  List<String> databases = client.getAllDbs();

  /* drop the database if it exists */
  for (String db : databases)
   if (DBNAME.equals(db)) client.deleteDB(DBNAME, "delete database");

  /* create the db */
  client.createDB(DBNAME);
  Database db = client.database(DBNAME, true);

  /* POJO does not exist and will throw an exception */
  try {
   MyDoc doc = db.find(MyDoc.class, "100");
  } catch (NoDocumentException e) {
   logger.debug("Transcript not found (id = %s)", "100");
  }

  Response response = db.save(doc);
  logger.debug("Saved Document (id = %s)", response.getId());

  MyDoc doc = db.find(Transcript.class, "100");
  logger.debug("Found Document (id = %s)", doc.get_id());

  client.deleteDB(DBNAME, "delete database");
 }
 
 private static MyDoc getDoc() {
  List<String> lines = new ArrayList<String>();
  lines.add("transcript line 1");
  lines.add("transcript line 2");
  lines.add("transcript line 3");

  MyDoc doc = new MyDoc();
  doc.set_id("100");
  doc.setLines(lines);
  
  return doc;
 }
}



References

  1. [Github] A Java client for Cloudant

No comments:

Post a Comment