Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine JAX-RS resource paths programatically?

Tags:

java

url

jax-rs

Suppose I have a set of JAX-RS locators and sublocators, like the following:

@Path("/users")
public class UserListResource {
   @Path("/{id}")
   public UserResource getCustomer(@PathParam("id") int id) {
      // Find and return user object
   }
}

public class UserResource {
  @GET
  public String get() {...}
}

For example, a UserResource object with the ID 5 would have the path "/users/5". In my system, I have several different resources.

Now the question is: How can the server figure out the path of a given resource? Can I do this programmatically via some JAX-RS API or do I have to implement code that uses reflection? (I know how to do the latter, but would prefer the other approach.)

  • At the point when I need to know the path, I do not have a request object at all. For example, I have a timer which does some background processing, then changes some entities in the domain model, then informs all clients about the changed entities (including their paths).
  • I know that within the scope of a request, I can inject a UriInfo object that provides this, but I need to know the path in advance (to inform clients of a change that did not necessarily happen through the JAX-RS resource).
  • I don't want to repeat the path information in another place, and I also don't want to have a set of path fragment constants for each resource type (in this case "/users" and "/{id}").
like image 300
Jens Bannmann Avatar asked Oct 06 '22 04:10

Jens Bannmann


1 Answers

As I read your question, you need to build a URI knowing only the resource class and the id parameter.

It can be done using the UriBuilder class as in:

UriBuilder builder=UriBuilder.fromResource(UserListResource.class);
URI uri=builder.path(UserListResource.class,"getCustomer").build(5);

It uses reflection under the hood, so it is not so easy to refactor, but it is all it is available at the moment.

like image 50
Carlo Pellegrini Avatar answered Oct 18 '22 08:10

Carlo Pellegrini