Thursday, May 14, 2015

MongoDB java connectivity "Exception in thread "main" java.lang.NoClassDefFoundError: org/bson/codecs/Decoder"

Hello,

MongoDB is cross platform,document based,NoSQL database.I am using mongodb 3.0.3.If u search for mongodb java driver,you will get the following link http://mongodb.github.io/mongo-java-driver/ as search result.

This page is the download page for mongodb java driver.You have to select the Operating System and version for the driver.While writing this blog the driver was having 2 versions 3.0.1 and 2.13.1.I used 3.0.1.

Here is the simple java code.
 import com.mongodb.MongoClient;  
 public class mongoCon {  
      public static void main(String[] args)  
      {  
           MongoClient c1=new MongoClient("localhost",27017);  
           List<String> dbs=c1.getDatabaseNames();  
           for(String db: dbs)  
           {  
                System.out.println(db);  
           }  
      }  
 }  

I used eclipse IDE and configured it for mongodb java driver by adding driver as external jar file.

When I execute the code it gets melt down.

It shows following error.
 Exception in thread "main" java.lang.NoClassDefFoundError: org/bson/codecs/Decoder  
   at mongo_java.mongoCon.main(mongoCon.java:12)  
 Caused by: java.lang.ClassNotFoundException: org.bson.codecs.Decoder  

It is because of jar file that I was using.When I opened it using archive manager there was no class file for Decoder.Even there was no folder codecs inside org/bson.

The solution is to download source code of driver and build it to get jar.
I downloaded it from https://github.com/mongodb/mongo-java-driver/releases.
Then extract it and change directory to the extracted location and type ./gradlew.
 tar -xf mongo-java-driver-r3.0.1.tar.gz  
 cd mongo-java-driver-r3.0.1  
 ./gradlew jar  
  It will build the project and will  show "BUILD SUCCESSFUL" if everything is ok. If your network requires proxy setting just change "./gradlew jar" to
 ./gradlew -Dhttps.proxyHost=192.168.4.254 -Dhttps.proxyPort=3128 jar  
After this,you can get the jar file in mongo-java-driver directory of mongo-java-driver-r3.0.1. Just add this jar file as the external jar for your eclipse project and it will work.



2 comments:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training from India . Nowadays Java has tons of job opportunities on various vertical industry.

    ReplyDelete