Is there a Java standalone implementation to extract values of parameters in an URI as defined by an URI-Template (RFC 6570)?
The best implementation I've found is a ruby implementation ( https://github.com/sporkmonger/addressable )
Via http://code.google.com/p/uri-templates/wiki/Implementations I found a Java implementation: Handy-URI-Templates
It supports the resolution of an URI-Template with parameter values to a final URI. Unfortunately, it can not do the reverse: extraction of parameter values in the URI according URI-Template.
Implentations of the JAX-RS (or Restlet) have this feature internally. But none seems to have isolated this feature module which could used independently.
Does anyone have another idea?
Here a example to Use spring-Web :
import org.springframework.web.util.UriTemplate;
public class UriParserSpringImpl implements UriParser {
private final UriTemplate uriTemplate;
private final String uriTemplateStr;
public UriParserSpringImpl(final String template) {
this.uriTemplateStr = template;
this.uriTemplate = new UriTemplate(template);
}
@Override
public Map<String, String> parse(final String uri) {
final boolean match = this.uriTemplate.matches(uri);
if (!match) {
return null;
}
return uriUtils.decodeParams(this.uriTemplate.match(uri));
}
@Override
public Set<String> getVariables() {
return Collections.unmodifiableSet(new LinkedHashSet<String>(this.uriTemplate.getVariableNames()));
}
}
Another for Jersey (JAX-RS implementation) :
import com.sun.jersey.api.uri.UriTemplate;
public class UriParserJerseyImpl implements UriParser {
private final UriTemplate uriTemplate;
private final Map<String, String> valuesMaps;
public UriParserJerseyImpl(final String template) {
this.uriTemplate = new UriTemplate(template);
final Map<String, String> valuesMaps = new HashMap<String, String>();
for (final String prop : this.uriTemplate.getTemplateVariables()) {
valuesMaps.put(prop, null);
}
this.valuesMaps = Collections.unmodifiableMap(valuesMaps);
}
@Override
public Map<String, String> parse(final String uri) {
final Map<String, String> values = new HashMap<String, String>(this.valuesMaps);
final boolean match = this.uriTemplate.match(uri, values);
if (!match) {
return null;
}
return values;
}
@Override
public Set<String> getVariables() {
return this.valuesMaps.keySet();
}
}
With interface :
public interface UriParser {
public Set<String> getVariables();
public Map<String, String> parse(final String uri);
}
The damnhandy uri template library has an open issue for exactly this feature. I've already gotten the PR for the feature merged and it should be out in version 2.2! Head over there and let the maintainers know you're interested.
Also if you can't wait, you can see how I did it here and use that for yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With