You can use the Template class to build URIs from patterns like the ones
you use to attach resources to the router.
To avoid having to maintain these patterns in several places, I register
all the templates of an application as constants (using an enum) that I can
use in attach statements and when building URIs. Here's a simplified
example:
public enum AppPattern {
USER("/users/{user}"),
USER_ORDERS("/users/{user}/orders"),
USER_ORDER("/users/{user}/order/{order}"),
;
public String pattern() {
return template.getPattern();
}
public String format(String... args) {
return template.format(valueMapFromArgs(args) );
}
AppPattern(String pattern) {
this.template = new Template(pattern);
}
private Template template;
private Map<String, ?> valueMapFromArgs(String[] args) { ... }
}
import static org.example.MyApp.AppPattern.*;
router.attach(USER.pattern(), UserResource.class);
router.attach(USER_ORDERS.pattern(), UserOrdersResource.class);
router.attach(USER_ORDER.pattern(), UserOrderResource.class);
...
String userId = ...;
String orderId = ...;
String orderUri = USER_ORDER.format("user", userId, "order", orderId);
--tim
On Sat, Jun 30, 2012 at 1:05 PM, Larry Sanders <[email protected]> wrote:
> Is there a way to generate the URI to a resource from within another
> resource for an application?
>
> For example, in the restlet tutorial we have the following bindings:
> --------------------------
> // Attach the resources to the router
> router.attach("/users/{user}", UserResource.class);
> router.attach("/users/{user}/orders", OrdersResource.class);
> router.attach("/users/{user}/orders/{order}", OrderResource.class);
> --------------------------
>
> Let's assume that I want a Users (plural) resource that provides summary
> data on users and provides URIs to UserResources.
>
> So, there'd be:
> router.attach("/users", UsersResource.class)
>
> In that class, when I return the collection of URIs to a particular User,
> do I have to build that URI manually (getting the base URI of the request
> and hardcoding "/users/" + username, etc?
>
> It seems like there should be a way to programmatically generate the URIs.
>
> Any pointers are welcomed. Thanks.
>
> ------------------------------------------------------
>
> http://restlet.tigris.org/ds/viewMessage.do?dsForumId=4447&dsMessageId=2974129
>
------------------------------------------------------
http://restlet.tigris.org/ds/viewMessage.do?dsForumId=4447&dsMessageId=2974146