Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jersey: get URL of a method

I want to get URI for specific method without 'hardcoding' it.

I tried UriBuilder.fromMethod but it only generates URI that is specified in the @Path annotation for that method, it doesn't take into account the @Path of the resource class it's in.

For example, here's the class

@Path("/v0/app")
public class AppController {

    @Path("/{app-id}")
    public String getApp(@PathParam("app-id") int appid) {
        // ...
    }

}

I want to get the URL for the getApp method, this /v0/app/100 for example.

UPDATE:

I want to get the URL from method other than getApp

like image 773
8bra1nz Avatar asked May 05 '17 07:05

8bra1nz


1 Answers

It works if you use UriBuilder.fromResource, then add the method path with path(Class resource, String method)

URI uri = UriBuilder
        .fromResource(AppController.class)
        .path(AppController.class, "getApp")
        .resolveTemplate("app-id", 1)
        .build();

Not sure why it doesn't work with fromMethod.

Here's a test case

public class UriBuilderTest {

    @Path("/v0/app")
    public static class AppController {

        @Path("/{app-id}")
        public String getApp(@PathParam("app-id") int appid) {
            return null;
        }
    }

    @Test
    public void testit() {
       URI uri = UriBuilder
               .fromResource(AppController.class)
               .path(AppController.class, "getApp")
               .resolveTemplate("app-id", 1)
               .build();

        assertEquals("/v0/app/1", uri.toASCIIString());
    }
}
like image 142
Paul Samsotha Avatar answered Nov 20 '22 18:11

Paul Samsotha