abdera-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From James M Snell <jasn...@gmail.com>
Subject URI/IRI Templates
Date Mon, 26 Nov 2007 19:22:35 GMT
I've added support for URI/IRI Templates to the IRI module based on
http://bitworking.org/projects/URI-Templates/draft-gregorio-uritemplate-02.html

Examples:

Template instances are immutable and threadsafe.

private static final Template template =
  new
Template("http://example.org{-opt|/~|user}{user}{-opt|/-/|categories}{-listjoin|/|categories}{-opt|?|foo,bar}{-join|&|foo,bar}");


Templates can be resolved from a Map, from Java object getters and
fields, or from a custom Context implementation

 Map<String,Object> map = new HashMap();
 map.put("user","james");
 map.put("categories", new String[] {"a","b","c"});
 map.put("foo", "abc");
 map.put("bar", "xyz");
 System.out.println(template.expand(map));

 > http://example.org/~james/-/a/b/c?foo=abc&bar=xyz


The Java object approach will examine the public fields and getters of
passed in java objects.

 public static class MyObject {
   public String user = "james";
   public List getCategories() {
     List<String> list =
       new ArrayList<String>();
     list.add("a");
     list.add("b");
     list.add("c");
     return list;
   }
   public Foo[] getFoo() {
     return new Foo[] {
       new Foo(),
       new Foo()
     };
   }
   public String getBar() {
     return "xyz";
   }
 }

 private static class Foo {
   public String toString() { return "abcæ"; }
 }

 MyObject myObject = new MyObject();
 System.out.println(template.expand(myObject,true));

 > http://example.org/~james/-/a/b/c?foo=abc%C3%A6&foo=abc%C3%A6&bar=xyz


The custom Context implementation approach allows template variables to
be resolved dynamically,

  CachingContext context = new CachingContext() {
    private static final long serialVersionUID = 4896250661828139020L;
    protected <T> T resolveActual(String var) {
      if (var.equals("user")) return (T)"james";
      else if (var.equals("categories"))
        return (T)new String[] {"a","b","c"};
      else if (var.equals("foo")) return (T)"abc";
      else if (var.equals("bar")) return (T)"xyz";
      else return null;
    }
    public Iterator<String> iterator() {
      return Arrays.asList(
        new String[] {"user","categories","foo","bar"}).iterator();
      }
    };
  System.out.println(template.expand(context));

  > http://example.org/~james/-/a/b/c?foo=abc&bar=xyz

The implementation will continue to evolve as the URI Template spec evolves.

- James

Mime
View raw message