dev@jsr311.java.net

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,
java.net.URI 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:

baseUri=http://example.com/base
entryId=foo

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

results in

uri = http://example.com/base/foo
editUri = http://example.com/base/edit/foo

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
(entryId)
URI editUri = UriBuilder.fromURI(baseUri).path
(EditEntryResource.class).build(entryId)

also results in

uri = http://example.com/base/foo
editUri = http://example.com/base/edit/foo

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
(entryId)

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.

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