Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use URI templates to change path parameters in a URL in java

I followed the tutorial available in here for replacing path parameters with given values and ran the sample code which is given below

import org.glassfish.jersey.uri.UriTemplate;

import javax.ws.rs.core.UriBuilder;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

public class Demo {
    public static void main(String[] args) {
        String template = "http://example.com/name/{name}/age/{age}";
        UriTemplate uriTemplate = new UriTemplate(template);
        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);
        System.out.println(parameters);
        parameters.put("name","Arnold");
        parameters.put("age","110");

        UriBuilder builder = UriBuilder.fromPath(template);
        URI output = builder.build(parameters);
        System.out.println(output.toASCIIString());


    }
}

but when I compile the code it gives me this error

Exception in thread "main" java.lang.IllegalArgumentException: The template variable 'age' has no value

Please help me out to fix this, (may be my imports are causing the issue)

like image 457
Kasun Siyambalapitiya Avatar asked Apr 27 '17 09:04

Kasun Siyambalapitiya


1 Answers

public static void main(String[] args) {
    String template = "http://example.com/name/{name}/age/{age}";
    UriTemplate uriTemplate = new UriTemplate(template);
    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);
    System.out.println(parameters);
    parameters.put("name","Arnold");
    parameters.put("age","110");

    UriBuilder builder = UriBuilder.fromPath(template);
    // Use .buildFromMap()
    URI output = builder.buildFromMap(parameters);
    System.out.println(output.toASCIIString());

}

If you are using .build for filling the template, you have to provide the values one by one like .build("Arnold", "110"). In your case you want to use .buildFromMap() with your parameters map.

like image 151
Norb Braun Avatar answered Sep 21 '22 13:09

Norb Braun