June 14, 2013

Restlet and Spring integration

Restlet supports publication of their services either through a servlet or an indepdendent server out of the box. To better integrate the REST service into a Spring MVC framework, I created some glue to better bind them together. While Restlet supports Spring through their own Spring integration, I wanted to avoid the use of a an another servlet for the Restlet integration. Instead I wanted to use an automatically configured Spring MVC controller. In addition I wanted to use the new Spring JavaConfig for configuring the Spring Beans.

The first step was to create a Spring MVC controller, wrapping REST requests:

@Controller
@RequestMapping("/rest")
public class RestletController {

    @Autowired
    private Restlet root;

    @Autowired
    private Context context;

    private ServletAdapter adapter;

    public RestletController() {
    }

    @PostConstruct
    public final void postConstruct() {
        final Application application = new Application(this.context);
        application.setInboundRoot(this.root);

        this.adapter = new ServletAdapter(new DummyServletContext());
        this.adapter.setNext(application);
    }

    @RequestMapping("/**")
    public final void request(final HttpServletRequest request,
            final HttpServletResponse response)
            throws ServletException, IOException {
        this.adapter.service(request, response);
    }
}

This controller sets up the Restlet application when all dependencies has been injected. This happens in the method annotated with a @PostContruct annotation. The ServletAdapter class is normally used in the Restlet servlet, but are here used as a target for forwarding the request and response objects. This will result in requests being handles as if the servlet was configured for the application container.

This application uses Spring JavaConfig for configuring the application, and this is the configuration class for setting up the Restlet environment:

@Configuration
public class RestletConfig {

    @Bean
    public Restlet root() {
        final SpringRouter router = new SpringRouter(this.restletContext());
        router.attach("/users", new SpringFinder() {
            @Override
            public ServerResource create() {
                // lookup-method
                return RestletConfig.this.usersResource();
            }
        });
        router.attach("/users/{domain}/{username}", new SpringFinder() {
            @Override
            public ServerResource create() {
                // lookup-method
                return RestletConfig.this.userResource();
            }
        });

        return router;
    }

    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
    public Context restletContext() {
        return new Context();
    }

    @Bean
    public ServiceSpringSecurityVerifier verifier() {
        return new ServiceSpringSecurityVerifier();
    }

    @Bean
    public UsersResource usersResource() {
        return new UsersResource();
    }

    @Bean
    public UserResource userResource() {
        return new UserResource();
    }
}

This class configures routes for the REST service, and utilizes the Restlet Spring integration to map server resources to Spring beans. For each mapping we can see that the create method looks up beans from the Spring container. By doing this, we are able to utilize injection of dependencies for our server resources.

This is the server resource for list of users:

public class UsersResource extends ServerResource {

    @Autowired
    private UserDao userDao;

    @Get("json")
    public final Representation getUsers() {
        return this.convertCollection(this.userDao.getAll());
    }

    @Post("json")
    public final void addUser(final User user) {
        this.userDao.persist(user);
    }

    private Representation convertCollection(final Collection<?> collection) {
        final JSONArray result = new JSONArray();
        for (final Object bean : collection) {
            result.put(new JSONObject(bean));
        }
        return new JsonRepresentation(result);
    }
}

This class injects a user DAO service, which in turn fetches users from the database. The first method covers the get-scenario for all users. This request should return a list of all known users. This server resource is also used for adding new users through the post-scenario. Unfortunately Restlet does not handle collections, which means that a method will need to be built to convert a collection into a JSONArray object, which in turn is returned as a list.

This is the server resource for single users:

public class UserResource extends ServerResource {

    @Autowired
    private UserDao userDao;

    @Get("json")
    public final Representation getUser() {
        final String userName = (String)
                this.getRequestAttributes().get("username");
        final User user = this.userDao.get(userName);

        if (user != null) {
            return new JsonRepresentation(user);
        } else {
            this.doError(Status.CLIENT_ERROR_NOT_FOUND);
            return null;
        }
    }

    @Put("json")
    public final void updateUser(final User user) {
        this.userDao.persist(user);
    }

    @Delete
    public final void deleteUser() {
        final String userName = (String)
                this.getRequestAttributes().get("username");
        final User user = this.userDao.get(userName);
        if (user != null) {
            this.userDao.delete(user);
        }
    }
}

In the get-scenario for a single user, you get that user if it can be found. If it cannot be found, a standard error should be given. The put-scenario replaces the user selected. The last method covers the delete-scenario, which simply deletes the selected user from the database.

The more observant reader would probably see that the same method is used for both adding and replacing a user. This is intentional, as we want to make is slightly easier to add and replace users. If a user with a given username is found in either of these scenarios, it will be replaced, Otherwise, the user will be added.

2 comments:

  1. Excellent example, can you explain how you bootstrap Spring from your web.xml

    ReplyDelete
  2. Hi Runar, thanks for the good examples. I have one query where i am stuck as of now.
    (new DummyServletContext());
    Is this bespoke class written? if yes what needs to be implemented in this class?
    Thanks ,
    Mangesh

    ReplyDelete