Adding nodes to a MongoDB replica set using the Java driver

MongoDB console has a method for adding a replica to a replica set called rs.add. The Java driver doesn’t support this directly, but you can use the code from the mongo shell to implement add directly by running commands against the admin database.

rs.add = function (hostport, arb) {
    var cfg = hostport;
 
    var local = db.getSisterDB("local");
    assert(local.system.replset.count() <= 1, "error: local.system.replset has unexpected contents");
    var c = local.system.replset.findOne();
    assert(c, "no config object retrievable from local.system.replset");
 
    c.version++;
 
    var max = 0;
    for (var i in c.members)
        if (c.members[i]._id > max) max = c.members[i]._id;
    if (isString(hostport)) {
        cfg = { _id: max + 1, host: hostport };
        if (arb)
            cfg.arbiterOnly = true;
    }
    c.members.push(cfg);
    return this._runCmd({ replSetReconfig: c });
}

Use new version of Jackson JSON with Jersey

Guice Module:

import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
import com.google.inject.Singleton;
import com.sun.jersey.guice.JerseyServletModule;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;
 
public final class JerseyModule extends JerseyServletModule
{
   @Override
   protected void configureServlets()
   {
      bind(JacksonJaxbJsonProvider.class).in(Singleton.class);
      filter("/*").through(GuiceContainer.class);
   }
}

And the Maven pom:

<dependency>
   <groupId>com.fasterxml.jackson.jaxrs</groupId>
   <artifactId>jackson-jaxrs-json-provider</artifactId>
   <version>2.0.5</version>
</dependency>

Jersey + Guice ExceptionMapper

import com.google.inject.Singleton;
 
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
 
@Provider
@Singleton
public class MyExceptionMapper implements ExceptionMapper<MyException>
{
   @Override
   public Response toResponse(final MyException exception)
   {
      return Response.status(Status.NOT_FOUND).entity(exception.getMessage()).build();
   }
}
import com.google.inject.AbstractModule;
 
public class MyModule extends AbstractModule
{
   @Override
   protected void configure()
   {
      bind(MyExceptionMapper.class);
   }
}