Data insertion to CouchDB using Lightcouch lib in Java (Sample)

Introduction

Hello, a small sample on how to insert JSON data to couchDB.

First off there are MANY java libraries for accessing couchdb. For information on which one to choose for you the 2 links below may help:
1) http://stackoverflow.com/questions/1105807/which-java-library-libraries-for-couchdb
2) http://wiki.apache.org/couchdb/Getting_started_with_Java

In this post we made use of LightCouch as we wanted something relatively simple without object mappings and other such features.

Aside: an also interesting tutorial utilizing couchdb4j with description of sessions is: http://www.drdobbs.com/jvm/223100116

Getting Started

We followed the instructions at: http://www.lightcouch.org/getstarted.html related to lightcouch 0.04 .

However, we included the actual lightcouch sources within our project in order to be able to see the actual implementation underneath. We did this by downloading the souce code utilizing Git Bash for windows.

Small modification for .properties file

As I had access to the actual couchDB source code I changed the readConfigFile method in order to fallback loading with properties.load:

properties.load(new FileInputStream(file));

This is a personal decision, using the default is fine as well:

Thread.currentThread().getContextClassLoader().getResource(resource)

If you are getting the error below a quick hack would be to edit your readConfigFile method to look similar to the following code.

"Could not read configuration file from the classpath:couchdb.properties"

Modified Load Method:

private void readConfigFile(String configFile) {
	try {
		InputStream inStream = getURL(configFile).openStream();
		properties.load(inStream);
	} catch (Exception e) {
		boolean alternative_not_worked = true;

		try {
			//try to load from file
			log.info("Attempting to read config file directly from directory instead of classpath.");
			properties.load(new FileInputStream(configFile));
			alternative_not_worked = false;
		} catch (FileNotFoundException e1) {
			log.error("Attempted to read config file directly from directory instead of classpath: File not Found");
		} catch (IOException e1) {
			log.error("Attempted to read config file directly from directory instead of classpath: IO Exception");
		}

		if(alternative_not_worked)
		{
			String msg = "Could not read configuration file from the classpath or directory: " + configFile;
			log.error(msg);
			throw new IllegalStateException(msg, e);
		}
	}


Actual Java Code

You need to add the following .jar to your project as libraries:

The code below shows the basic functionality of adding JSON documents to couchDB. (Editing to follow – eclipse project can be downloaded from here).

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.lightcouch.CouchDbClient;
import org.lightcouch.Response;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSerializer;

//Based on http://www.lightcouch.org/lightcouch-guide.html#dependencies

public class TestConnection {

	/**
* @param args
*/
	public static void main(String[] args) {
		CouchDbClient dbClient = new CouchDbClient("couchdb.properties");
		Response resp;

		//How to insert JSON already formatted

		JsonParser parser = new JsonParser();
		String json_text = "{"_id": "a"+(int)(Math.random()*100)+"","a": "A"}";
		System.out.println(json_text );
		JsonObject o = (JsonObject)parser.parse(json_text );

		try
		{
			resp = dbClient.save(o);
		}
		catch(org.lightcouch.DocumentConflictException e)
		{
			//if we insert something that already exists
			//we get Exception in thread "main" org.lightcouch.DocumentConflictException: << Status: 409 (Conflict)
		}

		//Inserting some Json documents
		for(int i=0; i<100; i++)
		{
			JsonObject  object=new JsonObject ();
			object.addProperty("name","Amit Kumar");
			object.addProperty("Max.Marks",new Integer(100));
			object.addProperty("Min.Marks",new Double(40));
			object.addProperty("Scored",new Double(66.67));
			object.addProperty("nickname","Amit");
			object.addProperty("_id", "whatever"+(int)(Math.random()*100000));
			object.addProperty("rev", "3");

			try
			{
				resp = dbClient.save(object);
			}
			catch(org.lightcouch.DocumentConflictException e)
			{
				//if we insert something that already exists
				//we get Exception in thread "main" org.lightcouch.DocumentConflictException: << Status: 409 (Conflict)
			}

		}

		dbClient.shutdown();

	}





Menelaos Bakopoulos

Mr. Menelaos Bakopoulos is currently pursuing his PhD both at Center for TeleInFrastruktur (CTiF) at Aalborg University (AAU) in Denmark and Athens Information Technology (AIT) in Athens, Greece. He received a Master in Information Technology and Telecommunications Systems from Athens Information Technology and a B.Sc. in Computer Science & Management Information Systems from the American College of Thessaloniki. Since April 2008 he has been a member of the Multimedia, Knowledge, and Web Technologies Group.

More Posts