Search code examples
javamongodbglassfishruntime-erroreclipse-classpath

Glassfish & MongoDB connection error : NoClassDefFoundError


I am running a Glassfish server that is trying to connect to MongoDB. At first I created seperate projects for the server and MongoDB. So now I am trying to merge those projects but it appears anything I try to do it results in a faliure.

The current error I am getting is:

2018-07-05T19:54:36.249+0200|Severe: java.lang.NoClassDefFoundError: org/bson/conversions/Bson

I am well aware that the error happens in runtime and that the possible cause is my classpath.

Currently I copied all of my code from one project to another, added Maven dependencies and the following happens:

  • if I create a separate .java file for my MongoDB and run it in the same folder that the Glassfish server is, it works perfectly fine.

  • if I run the server and try to call methods from the other class (a little bit modified) the upper error appears

Simplified code example withouth error:

import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;

public class MyClass{
    public static void main(String[]args){
        String ip = "127.0.0.1";
        int port = 27017;
        MongoClient mongoClient = new MongoClient(ip,port);

        /* Remaining code */

    }
}

With error:

import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;

public class MyClass{
   private MongoClient mongoClient;
   public MyClass(String ip, int port){
       mongoClient = new MongoClient(ip, port); // Error called here
   }

   /* Remaining code */

}

Called from the server.java file:

MyClass mc = new MyClass("127.0.0.1",27017);

I also tried to download all of the bson jar files separately and add them to the project but that had no effect...


Solution

  • The working solution for me was to delete the whole project and create it once more. Apparently there was a problem with Eclipse or I made a mistake before and forgot about it.