A few tutorials ago,in the tutorial about RestEasy and Hibernate, we saw how we could integrate RESTEasy with Hibernate.Now in this tutorial we will see how can we create Restful web services with RestEasy and MongoDB.

As an example we will see how to expose  the documents of collection named Categories.The service class will be:

package com.javaonly.service;

import com.javaonly.Daos.DaoFactory;
import com.javaonly.Daos.TutorialDao;
import com.javaonly.mongo.daos.CategoryDao;
import com.javaonly.mongo.daos.MongDaoFactory;
import com.javaonly.mongo.model.Categories;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

@Path("/categories")
public class CategoryService {
    //initialize category dao
    CategoryDao categoriesDao=MongDaoFactory.getCategoryDao();
    @GET
    @Path("/all")
    @Produces("application/json")
    public List getAll(){
        List all=new ArrayList();
         DBCursor cursor = categoriesDao.getAll();
         while(cursor.hasNext()){
            DBObject next = cursor.next();
            all.add(next);
        }
        return all;
    }
    
}

Since our service class is ready  we now need to create the Application class:

package com.javaonly.service;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;


public class CategoryApplication extends Application {

    private Set<Class<?>> classes=new HashSet<Class<?>>();
   private Set<Object> singletons = new HashSet<Object>();
 
	public TutorialApplication() {
		singletons.add(new CategoryService());
	}
 
	
	public Set<Object> getSingletons() {
		return singletons;
	}
}

Finally, in order to configure RESTEasy we must add the following snippet in the web.xml:

<context-param>
        <param-name>resteasy.scan</param-name>
        <param-value>true</param-value>
    </context-param>
	
    <context-param>
        <param-name>resteasy.servlet.mapping.prefix</param-name>
        <param-value>/rest</param-value>
    </context-param>
     
   
    <servlet>
        <servlet-name>Resteasy</servlet-name>
        <servlet-class>
            org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
        </servlet-class>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>com.javaonly.service.TutorialApplication</param-value>
        </init-param>
    </servlet>
 
    <servlet-mapping>
        <servlet-name>Resteasy</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

 As you may have noticed in the CategoryService class we used MongoDaoFactory class to initialize The categoryDao.In order to optimize the comunication with mongoDB we used DataAccessObject Pattern and so,we've created The appopriate DAO for every collection in the database.The DAO class hierarchy is shown below.First we begin with the AbstractDao class:

package com.javaonly.mongo.daos;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

public class AbstractDao {
    
    private DBCollection collection;
    private Class cla;
    public AbstractDao(){
        
    }

    
   
    public DBCollection getCollection() {
        return collection;
    }

   
    public void setCollection(DBCollection collection) {
        this.collection = collection;
    }
    
    public DBCursor getAll(){
        DBCursor find=collection.find();
        return find;
    }
    public void insert(BasicDBObject dbObject){
        collection.insert(dbObject);
    }
    public void remove(BasicDBObject dbObject){
        collection.remove(dbObject);
    }
    public void update(BasicDBObject old,BasicDBObject dbObject){
        collection.update(old, dbObject);
    }
    public DBObject getByID(int id){
        DBObject returnObject=null;
        BasicDBObject query=new BasicDBObject();
        query.put("id", new Integer(id));
        DBCursor find=collection.find(query);
        while(find.hasNext()){
            returnObject=find.next();
            
        }
        return returnObject;
    }

   
}

Now every DAO class will extend AbstractDAO class.So in the case of categoryDAO we will have:

package com.javaonly.mongo.daos;

public class CategoryDao extends AbstractDao{
    
    public CategoryDao(){
        super();
    }
    
}

Of course,in CategoryDAO class, we can add category-specific methods.The Factory class for createing and initializing DAOs will be:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.javaonly.mongo.daos;


import com.javaonly.mongo.database.MongoDBUtil;
import com.mongodb.DBCollection;

public class MongDaoFactory {
     public static CategoryDao getCategoryDao()
    {
        return (CategoryDao)getDAOByClassAndName(CategoryDao.class,"category");
    }
    public static AbstractDao getDAOByClassAndName(Class c,String name)
    {
        try 
        {
            DBCollection collection= getCollection(name);
            
            AbstractDao d = (AbstractDao)c.newInstance();
             d.setCollection(collection);       
            return d;
        } catch (InstantiationException ex) {
            ex.printStackTrace();
        } catch (IllegalAccessException ex) {
            ex.printStackTrace();
        }
        return null;
    }
     public static DBCollection getCollection(String name)
    {
        return MongoDBUtil.getCollection(name);
    }
}

As can see in the above class we've used a class named MongoDBUtil. MongoDBUtil is an utility class for handling the connection with MongoDB:

package com.javaonly.mongo.database;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;


public class MongoDBUtil {
    
    private static DB database;
    
    static{
        try {
            Mongo mongo=new Mongo("localhost",27017);
            database=mongo.getDB("categories");
        } catch (UnknownHostException ex) {
            Logger.getLogger(MongoDBUtil.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MongoException ex) {
            Logger.getLogger(MongoDBUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public static DBCollection getCollection(String collectionName){
        
        return database.getCollection(collectionName);
    }
}