Search code examples
javajerseyjax-rsembedded-jetty

How to correctly configure resources with jersey programmatically


I am trying out the Jersey Programmatic Resource Builder API and I am able to configure the resource, however I get a null ContainerRequestContext object when trying to access the path parameters. What could be the issue ?

NB: I am using version 2.35

public static void main(String[] args) {
    try {

        ResourceConfig config = new ResourceConfig();

        Resource.Builder resource = Resource.builder("/api/profile");
        Resource.Builder subresource = resource.addChildResource("{msisdn}/{source}");

        subresource.addMethod("GET")
                .produces(MediaType.TEXT_PLAIN_TYPE)
                .handledBy((ContainerRequestContext ctx) -> {
                    return Response.ok("Fetched Profile {" + (ctx == null) + "}").build();
                });

        subresource.addMethod("POST")
                .produces(MediaType.TEXT_PLAIN_TYPE)
                .handledBy((ContainerRequestContext ctx) -> {
                    return Response.ok("Posted Profile {" + (ctx == null) + "}").build();
                });

        config.registerResources(resource.build());

        Server server = new Server();

        ServerConnector connector = new ServerConnector(server);
        connector.setReuseAddress(true);
        connector.setName("Mambo Bad");
        connector.setHost("127.0.0.1");
        connector.setPort(Integer.parseInt("20000"));

    
        ServletContextHandler handler = new ServletContextHandler(server, "/", ServletContextHandler.NO_SESSIONS);
        handler.addServlet(new ServletHolder(new ServletContainer(config)), "/*");

      
        HandlerCollection handlers = new HandlerCollection();
        handler.setVirtualHosts(new String[]{"@" + connector.getName()});
        handlers.addHandler(handler);
        server.addConnector(connector);
        server.setHandler(handlers);

     
        server.start();
        server.join();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

Solution

  • The problem is with your lambdas. Basically, you have

    Inflector<ContainerRequestContext, ?> lambda = (ContainerRequestContext ctx) -> {
                    return Response.ok("Posted Profile {" + (ctx == null) + "}").build();
    };
    

    If you check the method argument type:

    for (Method m : lambda.getClass().getMethods()) {
      if ("apply".equals(m.getName())) {
         for (Type t : m.getGenericParameterTypes()) {
             System.out.println(t); //java.lang.Object
         }
      }
    }
    

    you get java.lang.Object. So Jersey tries to get Object type from the entity stream and gets null.

    So you need to tell java to use ContainerRequestContext argument type by a real anonymous class:

    Inflector<ContainerRequestContext, Response> anonymous = new Inflector<>() {
        @Override
        public Response apply(ContainerRequestContext ctx) {
            return Response.ok("Posted Profile {" + (ctx == null) + "}").build();
        }
    };
    
    for (Method m : anonymous.getClass().getMethods()) {
        if ("apply".equals(m.getName())) {
            for (Type t : m.getGenericParameterTypes()) {
                System.out.println(t); // ContainerRequestContext 
            }
        }
    }