users@jersey.java.net

Re: [Jersey] Obtaining a UriTemplate for the URI being processed

From: Paul Sandoz <Paul.Sandoz_at_Sun.COM>
Date: Tue, 01 Jun 2010 16:31:40 +0200

Hi Stephen,

On Jun 1, 2010, at 4:22 PM, Stephen Colebourne wrote:

> I'm just starting with JSR-311 and trying to work out how to use the
> UriInfo/UriBuilder classes effectively. I'm particularly interested in
> how to structure resource classes wrt @Path and sub-resources to
> easily generate URIs from code without lots of duplicated paths.
>
> My initial expectation with UriInfo was that a field defined as
> @Context UriInfo on the root resource would be populated with a
> UriInfo that only contained the matched path as far as the root
> resource (while one on a sub-resource would contain the matched path
> as far as that sub-resource). However it appears that UriInfo is
> always the same regardless of which resource/sub-resource it is
> obtained on. Have I interpretted the behaviour of injected UriInfo
> correctly?

Yes.


>
> I then examined the methods on UriInfo. While there are methods
> explaining each path segment and matched parameter, there is no method
> (that I can see) that says what the full matched path is as a
> UriTemplate, or which paths were literals and which were parameters.
>
> For example, given a URI:
> /orders/123/items/456
> I want to get a UriTemplate/UriBuilder something like:
> /orders/{orderId}/items/{itemId}
> Or to be able to tell that it is segments 2 and 4 that are
> substituted.
> Have I missed something in the JSR-311 API that allows me to obtain
> this?
>
> Finally, I looked at UriBuilder fromResource(). But this appears only
> to work for root resources. This is pushing me to design my classes
> such that everything is a root resource just to be able to use the
> method, but this seems to negate the use of sub-resources (and
> requires duplicating the whole path and other code - not ideal). Is
> there a way of combining UriInfo and UriBuilder.fromResource() to
> create a template as in the example above?
>
> BTW, I'm looking ideally for solutions that work at the JSR-311 level
> rather than specifically Jersey, but am interested in any answer!

That information is unfortunately not available from the 311 API.
Jersey has ExtendedUriInfo:

   https://jersey.dev.java.net/nonav/apidocs/latest/jersey/com/sun/jersey/api/core/ExtendedUriInfo.html

which gives you almost what you require.

Paul.