Gerard Davison is a Senior Principal Software Engineer working at Oracle in the UK on SOAP and REST tooling. Currently he is contributing in the area of WADL generation and client generation in the Jersey project and is maintaining the Abbot swing automation project. He also maintain a small holding of Hudson nodes run all those tests. He graduated from the University of Reading with a degree in Human Cybernetic and can't help looking for feedback loops. Gerard is a DZone MVB and is not an employee of DZone and has posted 32 posts at DZone. You can read more from them at their website. View Full User Profile

Using UriTemplate to Change Path Parameters in a URI

03.01.2013
| 3444 views |
  • submit to reddit

I have been recently working on a client generator in the wadl.java.net project and I was solving a bug where I wanted to change path parameter on a URI. This turned out to be quite easy with existing classes that are part of the Jersey project.

First of all you need a instance of UriTemplate, depending on the very of Jersey this is in a slightly different package - you IDE's automatic import will do the work for you. 
String template = "http://example.com/name/{name}/age/{age}";
UriTemplate uriTemplate = new UriTemplate(template);
 Then you use match(...) to extract them:
  String uri = "http://example.com/name/Bob/age/47";
  Map<String, String> parameters = new HashMap<>();

  // Not this method returns false if the URI doesn't match, ignored
  // for the purposes of the this blog.
  uriTemplate.match(uri, parameters);
 Then you can replace the parameters at will and rebuild the URI:
  parameters.put("name","Arnold");

  UriBuilder builder = UriBuilder.fromPath(template);
  URI output = builder.build(parameters);



Published at DZone with permission of Gerard Davison, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)