Tuesday 30 September 2014

Begin with Couchbase Lite on Android

This blog post provides the basic steps to create a simple android app based on Couchbase Lite database. This app will demonstrate how to configure couchbase for your android app, create a database , create a document and modify it.

Note : This sample app demonstrated through blog post has been created using ADT 23.0.0 and Eclipse Kepler 4.3

1. Set up a simple android app using File->New->Project->Android Application Project . Fill the necessary information and choose minimum sdk version to be 2.3 as recommended for using couchbase database.

2. Open manifest and add the following permission as

<uses-permission android:name="android.permission.INTERNET" />  
Save the AndroidManifest.xml file.


3. Next step is to add the prerequisites for the couchbase lite's smooth implementation for android.
  • Download the latest version of Couchbase Lite from http://www.couchbase.com/download#cb-mobile.
  • Decompress the zip file.
  • Copy all the files into the libs folder in the your project.
  • Download http://cl.ly/Pr1r/td_collator_so.jar.
  • Rename the downloaded td_collator_so.jar file to td_collator_so.zip.
  • Decompress the td_collator_so.zip file.
  • The zip file decompresses into a lib directory that contains several folders:
  • Copy all of the files into the libs folder in the project

4. Now before getting into the coding lets first understand the basic classes that we are going to deal with in this sample.

    Manager : Class which provide a shared instance that acts as controller or collection of multiple couchbase lite databases.

    Database : Class representing the couchbase database for android.
   
    Document : Class representing  the documents which stores the actual data. The data in the form of Map is set as properties to the document.
    Map objects provide JSON-compatible representations of data that are suitable for creating documents that you can store in the database.
   
    One most important thing is to provide a valid name to the method that creates the database.
    A database name can consist of only lowercase alphabetic characters (a-z), digits (0-9) and a few special characters (_$()+-/), so it’s important to validate the name.
   
    When the document is saved to the database, Couchbase Lite generates a document identifier property named _id and a revision identifier property named _rev, and adds them to the document. The generated _id for the newly created document is available via the getId() method of the Document class
.
   
   
   
5. Now we will explain the major steps for creating a database , creating a document and then deleting a document.

 Creating Manager
        
try
{
  Manager mCouchbaseManager =  
   new Manager(getApplicationContext().getFilesDir(), Manager.DEFAULT_OPTIONS);
}
catch (IOException e)
{
  e.printStackTrace();
}

       
Checking validity for name and Creating Database  

if (Manager.isValidDatabaseName(iDatabaseName))
{
  try
  {
    Database mCouchbaseDatabase = mCouchbaseManager.getDatabase(iDatabaseName);
  }
  catch (CouchbaseLiteException e)
  {
    e.printStackTrace();
  }
}


Creating a document and adding data to it.
   
         // Creating map that will hold the actual data to be set into the document          
 Map<String, Object> docContent = new HashMap<String, Object>();
 docContent.put("content","Sample data content for the document");
 docContent.put("time", "2014-01-01");

   
        // Create a document and add the following content to it.         
Document document = mCouchbaseDatabase.createDocument();
document.putProperties(docContent);

           
        // Save id for the document          
String docId = document.getId();

   
       
 Deleting a document
          
 boolean deleteDocSuccess = mCouchbaseDatabase.getDocument(docId).delete();


Please find the complete source code here SourceCode

       

Monday 29 September 2014

Couchbase Mobile : A Brief Architectural Overview



Couchbase Mobile Solution :
In one statement it could be called as the first NoSQL JSON database solutions for the mobiles.
But before we go describing its architectural components we should understand the major reasons for the mark of this very promising migration.


Migration from Sqlite to CouchDB(Now Couchbase Mobile)
In developing countries where infrastructure support is never a guarantee is one of the main reason for the above migration. In other words it means that an always on network connection cannot be assumed and a local copy of the data should be present on the phone. At the same time it is also important to maximize battery life because the interval between phone charging could be large. Reduced battery life on modern smart phones is already a big issue in low resource environments and requiring the phone to do even more by running a NoSQL or SQL database could reduce it more. We want to make sure we pick the technology that the best performance.





More ideas for this migration :
The new mobile version of CouchDB for Android makes it easier to get the database software onto handsets. The idea is that mobile application developers can make the local instance of CouchDB on the handset synchronize with the remove server, making data easily accessible to native mobile applications even when connectivity is down or the remote server is otherwise inaccessible.
Users expect to be able to take their data wherever they go and sometimes, if not often, that means they can't access the cloud and need a local copy. CouchOne Mobile for Android lets you build web-apps or native apps that take full advantage of CouchDB's built-in, reliable peer-to-peer sync facilities.


Couchbase Mobile Solution :
It is the first nosql json database solutions for the mobiles. 
It mainly consists of three components :
1. An embedded full featured Json database in the device called Couchbase lite.
2. A highly syncable sync tier called Couchbase Sync Gateway.
3. A highly scalable, high performance nosql database in the cloud called Couchbase server.

With couchbase mobile one can develop rich mobile applications that are always available, always responsive and unaffected due to network unavailability and latency.
Couchbase Mobile can help you get to market quickly with differentiated apps that supply “content-on-demand”, regardless of network connectivity.






1. Couchbase Lite :
       It is a lightweight document oriented schema-less highly sync-able JSON database designed from the ground up for mobile apps. It is used in conjunction with Couchbase Sync gateway and Couchbase server.

Major Features :

  • Stores record in flexible json format rather than in a predefined schema as in case of relational databases.
  • Documents can have attachments and could be multimedia content.
  • No database transformation is required as JSON is throughout Couchbase mobile. 
  • Native and REST api support for full featured database. 
  • Fast document look up using map reduce indexing without using any special query language.
  • Create views(indexes) and apply them to create ordered key-value pairs that can be queried later.
  • Supports continuous and one shot replications as well as defining filter functions to determine which document are replicated and which are not
  • Also supports peer to peer replication which means an app can receive connections requests from other devices running Couchbase Lite and sync data with them.
  • Multi version concurrency control is used to avoid document conflicts. A flexible revision tree scheme is used to manage conflicts without data loss.


2. Couchbase Sync Gateway :
      It makes the JSON document stored on Couchbase server available to mobile devices over the internet. 
It provide features for routing data to users, authentication, change validation and access control.

Major Features :

  • Configure your cloud in just one page of programmable sync code.
  • Specify all data routing required for your app.
  • It abstracts the network layer for you. No need to worry about the REST web services stack and continuous polling for data.
  • It supports multi master replication of data to and from couchbase server and client devices.
  • It also specifies the uni-directional and multi-directional data flow patterns of routing between couchbase server and client devices, as well as routing between devices for maximum flexibility.
  • It allows allows document access with fine grain filter controls, and authentication options.
  • It uses pre-built authentication features like facebook or plug-in your existing authentication methods.
  • These are stateless and developers can easily add additional ones to meet need for additional load.


Couchbase sync gateway configures data routing using the concept of channels which defines what slices of data stored on couchbase server can be visible to a given user. At any time user can be granted access to any of the several channels. For example a user can be provided access to the Sports channel of a Newsreader app where they can read all the documents related to the Sports. Similaryl other user could be provided access to the other channels like Nature, Weather etc.

If any user updates any document and tries to upload it to the couchbase server which is considered as change is decided by the Couchbase sync gateway to alllow that change or not.


3. Couchbase Server :
With the availability of JSON model, couchbase server makes it easy to modify your applications without the constraints of fixed database schema. Submillisecond, high throughput reads and write give you consistent high performance. It is easy to scale out and supports topology change with no downtime.

Major Features :

Easy Scalability: 
It is easy to scale with in a cluster or multiple clusters across multiple data centers. With one click of a button and no downtime, no changes to your app you can grow your cluster from 1 to 100's of servers while keeping the workload evenly distributed.

Always On:
With couchbase server your application is always on (24x365). Whether you are upgrading your database, system software or hardware or recovering from disaster you can count on zero app downtime with couchbase server.

Consistent High Performance:
Couchbase server's consistent submillisecond response times means an awesome experience for your app users. Consistent high throughput lets your serve more users with fewer servers.
Data and workload are equally spread across all servers.

Flexible Data model:
You shouldn't have to worry about when you change your application. With couchbase server, there is no fixed schema so records can have different structure and be changed any time without modification to any documents in the database.


Couchbase mobile use case examples:

  • Education and social interaction 
  • Point of Sales Product Catalog (E commerce) 
  • Expense Report and Other Enterprise Apps (e.g., HR / Payroll / Field Service, etc.) 
  • Real-time ‘Off-the-Grid’ Chat Applications via Bluetooth (Or on the Network with WiFi)