Search code examples
javarestpattern-matchingurirestlet

Restlet URI Pattern


I work on 2.1-M7 version of Restlet (I have to update it but this is an another problem)

I use directly Restlet, without any webserver before it Starting a component. Adding some virtualhosts on it.

And in the host I add entrypoints with method attach(string uriPattern, Restlet entrypoint)

My problem is : When I add with attach the uri "/test" with the entrypoint Test.class (with a method who print : "hello world") with a curl I can call "/testmeagain" and it's work (return "hello world") because it's a pattern?

So I use this : http://docs.oracle.com/javase/1.5.0/docs/api/java/util/regex/Pattern.html?is-external=true

And try "/test$" but in curl "/test" and "/testmeagain" return 404 now

Maybe I miss something?

Thank you if you have any suggestion or response to help me.


Solution

  • In fact, in Restlet, there is a matching mode for routes. Here is the behavior in the framework:

    • When you attach a route on a virtual, the default mode is "STARTS WITH". So with something like attach("/test", ...), URLs like /test and /testsomething will match.
    • When you attach a route on a router, the default mode is "EQUALS". So with something like attach("/test", ...), only URL /test will match.

    The attach method returns a template route on which you can change this matching:

    TemplateRoute route = component.getDefaultHost().attach(
            "/test", new Restlet() {
        @Override
        public void handle(Request request, Response response) {
            response.setEntity("test", MediaType.TEXT_PLAIN);
        }
    });
    
    // Default matching mode
    int defaultMatching = route.getMatchingMode();
    // Set another matching mode
    route.setMatchingMode(Template.MODE_EQUALS);
    

    In fact, it's more usually to implement a Restlet application and attach it to a virtual host on the component. In this case, you will have exact matching.

    Here is the way to do:

    Component component = new Component();
    (...)
    MyRestletApplication application = new MyRestletApplication();
    component.getDefaultHost().attachDefault(application);
    

    Here is a sample content for the application:

    public class MyRestletApplication extends Application {
        @Override
        public Restlet createInboundRoot() {
            Router router = new Router(getContext());
    
            TemplateRoute route = router.attach("/test", MyServerResource.class);
            // Default matching mode
            int defaultMatching = route.getMatchingMode();
    
            return router;
        }
    }
    

    And the content of the server resource:

    public class MyServerResource extends ServerResource {
        @Get
        public String test() throws Exception {
            return "test";
        }
    }
    

    Hope it helps you, Thierry