Search code examples
restletrestlet-2.0

issue binding context route using Restlet


I'm using restlet in a proof-of-concept as follows:

    final Component component = new Component();
    component.getServers().add(Protocol.HTTP, 8182);
    final Router router = new Router(component.getContext().createChildContext());
    router.attachDefault(HttpListener.class);
    component.start();

This should give me a URL path of http://localhost:8182/*. However, I just get 404 errors when trying to GET from this URL:

http://localhost:8182/      -> 404
http://localhost:8182/xyz   -> 404

Restlet isn't routing any requests to my HttpListener class.

My HttpListener class:

public class HttpListener extends ServerResource {

    public static void main(String[] args) throws Exception {
        final Component component = new Component();
        component.getServers().add(Protocol.HTTP, 8182);
        final Router router = new Router(component.getContext().createChildContext());
        router.attachDefault(HttpListener.class);
        component.start();
    }

    @Get()
    public Representation getDBName() {
        String body = "hello, world";
        Representation representation = new StringRepresentation(body, MediaType.APPLICATION_JSON);
        representation.setCharacterSet(CharacterSet.UTF_8);
        return representation;
    }
}

Solution

  • I had to attach the route as follows:

    public static void main(String[] args) throws Exception {
    
        final Router router = new Router();
        router.attachDefault(HttpListener.class);
    
        Application myApp = new Application() {
            @Override
            public org.restlet.Restlet createInboundRoot() {
                router.setContext(getContext());
                return router;
            };
        };
        Component component = new Component();
        component.getDefaultHost().attach("/", myApp);
    
        new Server(Protocol.HTTP, 8182, component).start();
    }
    

    Thanks to https://stackoverflow.com/a/13165900/1033422 for this answer.