public class MongoResource extends ServerResource
{
@Get
public JSONObject getJSON() throws MongoException, UnknownHostException
{
DBCollection collection = getCollection();
DBObject dbObject = collection.findOne(new BasicDBObject("_id", new ObjectId((String) getRequestAttributes().get("id"))));
if (dbObject != null)
return new JSONObject(dbObject.toMap());
else
{
getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
return null;
}
}
@Post
public String add(JsonRepresentation representation) throws JSONException, UnknownHostException
{
JSONObject json = representation.getJsonObject();
DBCollection collection = getCollection();
DBObject dbObject = (DBObject) JSON.parse(json.toString());
collection.insert(dbObject);
return getReference().toString() + dbObject.get("_id").toString();
}
@Put
public void update(JsonRepresentation representation) throws JSONException, UnknownHostException
{
JSONObject json = representation.getJsonObject();
DBCollection collection = getCollection();
DBObject dbObject = (DBObject) JSON.parse(json.toString());
if (collection.findAndModify(new BasicDBObject("_id", new ObjectId((String) getRequestAttributes().get("id"))), dbObject) == null)
getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
}
@Delete
public void remove() throws UnknownHostException
{
DBCollection collection = getCollection();
collection.remove(new BasicDBObject("_id", new ObjectId((String) getRequestAttributes().get("id"))));
}
private DBCollection getCollection() throws UnknownHostException
{
IMongoDB mongoDB = Activator.getInstance().getMongoDB();
DB db = mongo.getDB((String) getRequestAttributes().get("database"));
DBCollection collection = db.getCollection((String) getRequestAttributes().get("collection"));
return collection;
}
}
The only other piece of code you have to write is the provider to register the resource:
public class MongoResourceProvider implements IResourceProvider
{
@Override
public String getApplicationAlias()
{
return "/";
}
@Override
public String[] getPaths()
{
return new String[] { "/mongo/{database}/{collection}/", "/mongo/{database}/{collection}/{id}" };
}
@Override
public Finder getFinder()
{
return finder;
}
private Finder finder = new Finder(null, MongoResource.class);;
}
The code fully supports hot-swap, so the bundle providing the resource can be updated live.