Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disassemble links into entities in Spring Hateoas

maybe another one stumbled upon this topic and found a nice solution. Using the HATEOAS REST approach with help of Spring HATEOAS project works pretty well for link building to resources. But in the end, to map flattened resources back to an entity object tree, I need to disassemble my link and query the persistence backend. Example given, I have an entity Item, referencing ItemType (Many-to-one). Natural key of item is the composite of ItemType foreign key and Item code itself. The URL I map in ItemController using the link builder is

@RequestMapping("/catalog/items/{itemTypeCode}_{itemCode}")

Now a unique link for an item is e.g. http://www.sample.com/catalog/items/p_abc123

To invert this link I do some very ugly string work:

@Override
public Item fromLink(Link link) {
    Assert.notNull(link);
    String baseLink = linkTo(ColorTypeController.class).toString() + "/";
    String itemTypeAndItemPart = link.getHref().replace(baseLink, "");
    int indexOfSplit = itemTypeAndItemPart.indexOf('_');
    ItemType itemType = new ItemType();
    itemType.setCode(itemTypeAndItemPart.substring(0, indexOfSplit));
    Item item = new Item();
    item.setItemType(itemType);
    item.setCode(itemTypeAndItemPart.substring(indexOfSplit + 1));
    return item;
}

And all the time I am wondering, If there isn't a much nicer and more flexible approach (beware of any query string part, that will break the code) to do this inverse mapping. I actually do not want to call another MVC controller from within a controller but it would be nice, to somehow utilize the dispatcher servlet disassembly functions to deconstruct the URL into something more handy to work with. Any helpful hints for me? Thx alot :)

like image 282
Marius Schmidt Avatar asked Feb 17 '15 19:02

Marius Schmidt


1 Answers

You can use a UriTemplate. Its match method returns a map of variables and their values that have been extracted from the URI. For example:

UriTemplate uriTemplate = new UriTemplate("/catalog/items/{itemTypeCode}_{itemCode}");
Map<String, String> variables = uriTemplate.match("http://www.sample.com/catalog/items/p_abc123");
String itemTypeCode = variables.get("itemTypeCode"); // "p"
String itemCode = variables.get("itemCode"); // "abc123"
like image 59
Andy Wilkinson Avatar answered Sep 28 '22 05:09

Andy Wilkinson