Re: How to create URIs?

From: Marc Hadley <Marc.Hadley_at_Sun.COM>
Date: Thu, 19 Jul 2007 14:45:56 -0400

See the attached Javadoc for a proposed addition to the API that aims
to help developers in creating URIs. With the UriBuilder class I've
tried to achieve three things:

(i) Make it easy (or at least easier) to build a URI instance, is fine but as an immutable class it can be awkward to
use when you want to build a URI from various components and it
doesn't help much with query strings, matrix parameters or paths
(ii) Support URI templates during the build process
(iii) Integrate with root resource classes (those annotated with
@UriTemplate) to save having to copy string literals around or define
separate constants for them.

A few examples to demonstrate usage:


URI uri = UriBuilder.fromURI(baseURI).path(entryId).build()
URI editUri = UriBuilder.fromURI(baseUri).path("edit",entryId).build()

results in

uri =
editUri =

If EntryResource and EditEntryResource are root resources annotated
with UriTemplate values of "{entryId}" and "edit/{entryId}"
respectively then the following:

URI uri = UriBuilder.fromURI(baseUri).path(EntryResource.class).build
URI editUri = UriBuilder.fromURI(baseUri).path

also results in

uri =
editUri =

I think its going to be a common use case that the current request
URI or the base URI is used when constructing new URIs so I think it
would be worth adding a couple of contextual convenience methods to
UriInfo so you could write:

URI uri = uriInfo.getBaseUriBuilder().path(entryId).build() or
URI uri = uriInfo.getBaseUriBuilder().path(EntryResource.class).build

where each method returns a pre-initialized UriBuilder. In the above
uriInfo.getBaseUriBuilder() will be a shortcut for UriBuilder.fromUri
(uriInfo.getBaseUri()) though I guess its not that much shorter.

Thoughts ?


Marc Hadley <marc.hadley at>
CTO Office, Sun Microsystems.