Search code examples
web-servicesrestjerseycorsrestlet

Restlet + JAXRS extension - how to use filters?


I have a REST service implemented in Restlet + JAXRS extension. At a certain point, I had to add the CORS headers to responses. I have a lot of REST calls, and adding by hand the headers as this is working:

        return Response.status(200).header("Access-Control-Allow-Origin", "*").
                header("Access-Control-Allow-Headers", "Authorization, Origin, X-Requested-With, Content-Type").
                header("Access-Control-Expose-Headers", "Location, Content-Disposition").
                header("Access-Control-Allow-Methods", "POST, PUT, GET, DELETE, HEAD, OPTIONS").
                entity(fsJSON).build();

but I'd like to use filters in order to add those headers to all the responses, without adding those manually. I found a lot of examples of using filters in JAX-RS, like those:

https://jersey.java.net/documentation/latest/filters-and-interceptors.html

http://javatech-blog.blogspot.it/2015/04/jax-rs-filters-example.html

http://blog.dejavu.sk/2014/02/04/filtering-jax-rs-entities-with-standard-security-annotations/

But I can't understand how to integrate them with Restlet + JAX-RS environment. For example, I can't see the ContainerResponseFilter class anywhere. Anyone can help me?


Solution

  • When creating a JaxRS application within Restlet, you create a JaxRsApplication (see this link: http://restlet.com/technical-resources/restlet-framework/guide/2.2/extensions/jaxrs). This class extends the standard application of Restlet. The latter provides the way to configure services on it using the getServices method.

    So in your case, you don't need to use filters...

    See this answer regarding the configuration of the CorsService of Restlet: How to use CORS in Restlet 2.3.1?.

    Here a way to configure CORS within a Restlet JaxRS application:

    Component comp = new Component();
    Server server = comp.getServers().add(Protocol.HTTP, 8182);
    
    JaxRsApplication application = new JaxRsApplication(comp.getContext());
    application.add(new ExampleApplication());
    
    CorsService corsService = new CorsService();         
    corsService.setAllowedOrigins(new HashSet(Arrays.asList("*")));
    corsService.setAllowedCredentials(true);
    
    application.getServices().add(corsService);
    component.getDefaultHost().attachDefault(application);
    

    Otherwise JAX-RS filters aren't supported by the corresponding extensions of Restlet. To add a filter, you need to add it as a Restlet filter in front of the application, as described below:

    JaxRsApplication application = new JaxRsApplication(comp.getContext());
    application.add(new ExampleApplication());
    
    MyRestletFilter filter = new MyRestletFilter();
    filter.setNext(application);
    
    component.getDefaultHost().attachDefault(filter);
    

    Hope it helps you, Thierry