users@jersey.java.net

Re: [Jersey] Design Question / Sub Resources

From: Paul Sandoz <Paul.Sandoz_at_Sun.COM>
Date: Tue, 19 May 2009 15:08:58 +0200

On May 19, 2009, at 12:31 PM, aloleary wrote:

>
> Hello,
> I may be having a slow day today but I'm trying to figure out how
> to do
> the following:
>
> Very simple example: I have two root "resource" providers:
>
> /headoffice
>
> /branch
>
> where:
> GET on /headoffice returns a list of headoffice names
> GET on /branchreturns a list of all branch names
>
> I would like to use the BranchResource as a Sub Resource provider on
> HeadOfficeResource for re-use and to offer calls like:
>
> /headoffice/{id}/branch
> /headoffice/{id}/branch/{id} etc...
>
> So now the branch resource is providing information on the branch
> but scoped
> for a specific headoffice (the headoffice 'id' would be used in DB
> queries
> etc)
>
> However Im not sure how to annotate the HeadOfficeResource to allow
> this
>
> @Path("/headoffice")
> public cleass HeadOfficeResource {
>
> ....
>
> // ------------------------------------
> // Sub Resources
>
> @Path("{id}/branch") << ??
> public BranchResource getBranchResource(); << ??
>
> }
>
> I know there is no injection done for sub resources so there is no
> way for
> me to get access to this particular {id} so is it a case of
> supplying the
> getBranchResource() with the id as a constructor param and using
> that with
> the calls i.e.:
>
> public BranchResource getBranchResource(@PathParam("id") final String
> headOfficeId) {
> return new BranchResource(headOfficeId);
> }
>
> Is there a better more JAX-RS/Jersey way of approaching this ?
>
> I would like to avoid having GlobalBranchResource and
> HeadOfficeSpecifcBranchResource ;-) if possible
>

I think subclassing might be a good solution in some circumstances if
the subclass contains specific information related to the scoping that
is not present in the base class.


It is possible to inject information into sub-resources using the
ResourceContext class.

    @Path("{id}/branch")
    public BranchResource getBranchResource(@Context ResourceContext
rc) {
        ScopedBranchResource sbr =
rc.getReource(ScopedBranchResource.class);
        ...
        return sbr;
    }


As of yet i have not been able to come up with a satisfactory solution
for construction with type safe parameters and injection.

Paul.