MongoDB Read/Write using a Java Client

Recently I’ve been working on some NoSQL projects using Cassandra and MongoDB. So I just thought of sharing some basic stuff related to those NoSQL stores which will be useful for the beginners. In this very first post I’m going to show you how to write a very simple Java code through which you can write data into a MongoDB store and read from it.

Step 1 : Install MongoDB. Depending on your environment, you can very easily install MongoDB on your machine by following the guidelines given here.

Step 2 : Create a Java project on your favorite IDE and add the MongoDB Java driver into your class path. If you are using a Maven script to build your project, you can add the following dependency into it.


Step 3 : In this simple example, first we are going to create a database called “sample” and then add a collection called “book” into it. Then we’ll add 3 pages as documents into that collection. To be used as pages in the book collection, make sure you have 3 text files “page1.txt”, “page2.txt” and “page3.txt” in your classpath. After successfully inserting data into the database, we read the first document back from the database to make sure we’ve correctly inserted data. Here’s the Java code to do this. Read comments at each line to get an idea about what each line does.

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;


public class MongoSampleClient {

    public static void main(String[] args) {
        try {
            // create a MongoClient by connecting to the MongoDB instance in localhost
            MongoClient mongoClient = new MongoClient("localhost", 27017);
            // drop database if it already exists
            // creating a db named "sample" and a collection named "book"
            DB db = mongoClient.getDB("sample");
            DBCollection bookCollection = db.getCollection("book");
            // insert the 3 pages of the book into the collection
            for (int i = 1; i < 4; i++) {
                BasicDBObject doc = new BasicDBObject("pageId", "page" + i).
                        append("content", readFile("page" + i + ".txt"));
            // read the first doc to make sure that we've inserted correctly
            DBObject firstDoc = bookCollection.findOne();
        } catch (Exception e) {

     * Reads the specified file from classpath
    private static String readFile(String fileName) throws IOException {
        // get the input stream
        InputStream fileStream = MongoSampleClient.class.getResourceAsStream("/" + fileName);
        // create a buffer with some default size
        byte[] buffer = new byte[8192 * 2];
        // read the stream into the buffer
        int size =;
        // create a string for the needed size and return
        return new String(buffer, 0, size);

You’ll see the following on your console, which is the first document on your new collection.

{ "_id" : { "$oid" : "519f6c1f44ae9aea2881672a"} , "pageId" : "page1" , "content" : "your page1 content" }

Step 4 : Finally you can see the content you inserted above through the MongoDB console by using following commands.

isuru@isuru-w520:~$ mongo

MongoDB shell version: 2.0.4
connecting to: test
> use sample
switched to db sample
{ "_id" : ObjectId("519f6c1f44ae9aea2881672a"), "pageId" : "page1", "content" : "your page1 content" }
{ "_id" : ObjectId("519f6c1f44ae9aea2881672b"), "pageId" : "page2", "content" : "your page2 content" }
{ "_id" : ObjectId("519f6c1f44ae9aea2881672c"), "pageId" : "page3", "content" : "your page3 content" }

That’s it. In the next post on MonogoDB we’ll be looking at how to use MongoDB Map-Reduce functionality on top of the “book” collection we created above.


Slow internet with Zoom 5350 Router? Here’s how to fix..

I’m using a Zoom 5350 Router and I’ve been experiencing a very slow connection specially when streaming. I thought it’s something to do with my ISP and called them. But they couldn’t find any issues with my connection. After trying many things, finally I found that the issue is with my Router. Actually what you have to do is a very simple configuration change to disable IP Flood Detection which is enabled by default. See this for more details.

Developing Secure JAX-WS Web Services with WSO2 AS

WSO2 AS supports Apache CXF as the JAX-WS framework from next release on-wards. Applying WS-Security on JAX-WS services is an important use case when developing web services. CXF supports two ways to configure WS-Security on JAX-WS services.

  1. By using custom configurations in the cxf-servlet.xml file. This is the old way and it’s documented here. When a service is secured using this method, there won’t be a Policy on the WSDL and the clients can’t get needed Policy information to invoke the service just by looking at the contract. Therefore this is not a standard way of securing a service. A useful post on using this method can be found here. On WSO2 AS trunk, you can find a this type of sample here.
  2. By using WS-SecurityPolicy language. It’s documented here. This is the standard way of securing a service. Here, the service author has to include the Policy in the WSDL and engage it with needed bindings. Only the configurations like key store locations, callback handlers etc. should be done through the cxf-servlet.xml. A nice article which this kind of samples can be found here. And on WSO2 AS trunk, there’s a UT sample of this type here.

Both these methods are still supported. But the second one is the recommended way of doing it.

4 years at WSO2

Yesterday morning, accidentally I realized that I’ve been with WSO2 for 4 years. Joined the company on the 12th of May 2008 just after completing my CSE degree. Supun, Milinda, Saliya, Kalani and Rajika were the other batch mates who joined with me and Sameera joined a week later. Looking back, it has been a wonderful period of my life. I’ve learned a lot, gathered so much experience specially at customer sites and made lots of friends.

Just after joining the company I was assigned into WSO2 WSAS team and Azeez was my very first product manager. I still remember how we worked for our very first Carbon release. It was my first release experience and we had to put in lot of effort to get the release out. However I never felt tired and it was fun. I’ve written this post on the 31st of December 2008 with all my feelings about the company and the start of my career.

In addition to the technical experiences that I’ve gathered, I’ve made lots of friends at WSO2 who contributed a lot to make these 4 years unforgettable. Specially the annual “Adyapana Charikawa” 🙂 organized by Charitha, has added loads of fun memories. In addition to that I always enjoyed playing Carrom, Table Tennis and Basket Ball with our guys whenever we get a chance.

Having spent such a wonderful time, most probably I’ll be leaving the company for my studies in August. It’s little sad to think about leaving all my WSO2 friends. But still I don’t think about that too much as I’ve got 3 more months to enjoy with them :).

Apache CXF support in WSO2 Application Server

WSO2 Application Server mainly supports hosting Web Services and Web Applications. One of the major features included in the upcoming release (version 4.5.0) of WSO2 AS is the integration of Apache CXF. So from AS 4.5.0 on-wards, CXF users also will be able to host their applications inside WSO2 AS with great ease. Once you deploy your CXF application inside WSO2 AS, it automatically inherits lots of benefits from the underlying WSO2 Carbon platform.

  1. Ability to use the Carbon user store through CarbonContext
  2. Ability to use WSO2 Registry API’s through CarbonContext
  3. Fine grain authorization through WSO2 Identity Server features
  4. All the benefits inherited through OSGi
  5. Easy to use Management Console for CXF JAX-WS/JAX-RS Web Applications
  6. Hot deployment and Hot update for your CXF Web Applications

Following are some screen shots of the UI provided by WSO2 AS for CXF webapps. You can upload CXF webapps through the management console as follows.

Once you upload your CXF webapp, you can see the list of webapps as follows.

By clicking on the “Find Services” link, you can see the list of Web Services exposed by the particular CXF webapp.

We’ve already completed this integration on WSO2 Carbon trunk and now we are looking at the possibilities of making this feature more useful. For example, we’ll be adding the “Try-It” capability into CXF services and providing statistics for each and every service. AS 4.5.0 is expected to be released by the end of June and it will contain this new feature.

WSO2 ESB : Enrich Mediator

The Enrich mediator of WSO2 ESB can be used to perform transformations within your integration logic. Most transformations which needs an XSLT, can be easily done using this mediator. An article which is written on ESB service chaining can be found here and it uses the Enrich mediator to perform transformations. In the example given in the article, it is used to copy values coming in a SOAP message to some other SOAP message. But there can be situations where you want to copy a complete XML element from one message to another. In such situations, Enrich mediator can be used as shown below within your synapse configuration.

        <source xmlns:xs="" clone="true" xpath="//xs:Patients"/>
        <target type="property" property="PATIENTS"/>
        <source type="inline" clone="true">
            <p:aggregate xmlns:p="">
        <target type="body"/>
        <source type="property" clone="true" property="PATIENTS"/>
        <target xmlns:p="" xpath="//p:aggregate/p:Patients"/>

In the above configuration, if you are in the out sequence of your proxy service, first enrich block copies the “xs:Patients” element from the response from your first invocation into a property. Then the second enrich block creates the request to be sent to your second service. In the third enrich block, the PATIENTS property is inserted in the place of “//p:aggregate/p:Patients” element of the second request we just created. This will make sure that the entire “Patients” element will be copied into the second request as it is.

WSO2 Application Server wins the overall Gold in NBQSA 2011

The NBQSA (National Best Quality Software Awards) Awards ceremony was held yesterday night and WSO2 won six awards with WSO2 Application Server (WSO2 AS) winning the overall Gold. Being the product manager of WSO2 AS, I’m extremely happy and proud about this outstanding achievement of being the best software product in Sri Lanka. I would like to thank Hiranya for presenting WSO2 AS in NBQSA while I was out of the country and he’s done a great job. And also I would like to congratulate G-Reg, IS and Carbon teams as well for winning awards.

WSO2 AS is the oldest WSO2 product. Initially it was started as “WSO2 Tungsten” and then renamed to “WSO2 Web Services Application Server” and then to “WSO2 Application Server”. There are plenty of past members of the team who contributed a lot to the success of the product and I should thank all of them. Azeez (Currently the Director of Architecture) was the first product manager of WSO2 AS and he did a great job in getting the product into this level. And also people like Saminda, Chinthaka, Deepal, Sumedha, Amila and Sameera were some of the past members who has contributed a lot to the success of the product. In addition to that, I should thank SupunM who’s currently working full time on WSO2 AS.

So the next step will be the APICTA competition in which the best products from lot of other countries compete for the best of the best. Looking forward to do our best in that as well.