<chapter id="StringConverter">
   <title>String marshalling for String based @*Param</title>
   
   <sect1>
   <title>Simple conversion</title>
   
   <para>
   Parameters and properties annotated with <classname>@CookieParam</classname>, 
   <classname>@HeaderParam</classname>, <classname>@MatrixParam</classname>, <classname>@PathParam</classname>, or 
   <classname>@QueryParam</classname> are represented as strings in a raw HTTP request. The specification
   says that any of these injected parameters can be converted to an object if the object's class has
   a <methodname>valueOf(String)</methodname> static method or a constructor that takes one <classname>String</classname>parameter.
   In the following, for example,
   </para>
   <programlisting>
public static class Customer {
   private String name;

   public Customer(String name) {
      this.name = name;
   }
   
   public String getName() {
      return name;
   }
}

@Path("test")
public static class TestResource {

   @GET
   @Path("")
   public Response test(@QueryParam("cust") Customer cust) {
      return Response.ok(cust.getName()).build();
   }
}

@Test
public void testQuery() throws Exception {
   Invocation.Builder request = ClientBuilder.newClient().target("http://localhost:8081/test?cust=Bill").request();
   Response response = request.get();
   ...
}
   </programlisting>
   <para>
   the query "?cust=Bill" will be transformed automatically to an instance of <classname>Customer</classname> with name
   == "Bill".  
   </para>
   </sect1>
   
   <sect1>
   <title>ParamConverter</title>
   
   <para>
   What if you have a class where <methodname>valueOf()</methodname>or this string constructor don't exist or are inappropriate
   for an HTTP request? JAX-RS 2.0 has the <classname>javax.ws.rs.ext.ParamConverterProvider</classname> to help
   in this situation.
   </para>
   
   <para>
   A <classname>ParamConverterProvider</classname> is a provider defined as follows:
   </para>
      
   <programlisting>
public interface ParamConverterProvider {

   public &lt;T&gt; ParamConverter&lt;T&gt; getConverter(Class&lt;T&gt; rawType, Type genericType, Annotation annotations[]);
}
   </programlisting>
   
   <para>
   where a <classname>ParamConverter</classname> is defined:
   </para>
   
   <programlisting>
public interface ParamConverter&lt;T&gt; {
   ...
   public T fromString(String value);
   public String toString(T value);
}
   </programlisting>
   
   <para>
   For example, consider <classname>DateParamConverterProvider</classname> and <classname>DateParamConverter</classname>:
   </para>
   
   <programlisting>
@Provider
public class DateParamConverterProvider implements ParamConverterProvider {

   @SuppressWarnings("unchecked")
   @Override
   public &lt;T&gt; ParamConverter&lt;T&gt; getConverter(Class&lt;T&gt; rawType, Type genericType, Annotation[] annotations) {
      if (rawType.isAssignableFrom(Date.class)) {
         return (ParamConverter&lt;T&gt;) new DateParamConverter();
      }
      return null;
   }
}

public class DateParamConverter implements ParamConverter&lt;Date&gt; {

   public static final String DATE_PATTERN = "yyyyMMdd";

   @Override
   public Date fromString(String param) {
      try {
         return new SimpleDateFormat(DATE_PATTERN).parse(param.trim());
      } catch (ParseException e) {
         throw new BadRequestException(e);
      }
   }

   @Override
   public String toString(Date date) {
      return new SimpleDateFormat(DATE_PATTERN).format(date);
   }
}
   </programlisting>
   
   <para>
   Sending a <classname>Date</classname> in the form of a query, e.g., "?date=20161217" will cause the string "20161217"
   to be converted to a <classname>Date</classname> on the server.
   </para>
   </sect1>
   
   <sect1>
   <title>StringParameterUnmarshaller</title>
   
   <para>
   In addition to the JAX-RS <classname>javax.ws.rs.ext.ParamConverterProvider</classname>,
   RESTEasy also has its own <classname>org.jboss.resteasy.StringParameterUnmarshaller</classname>, defined
   </para>
   
   <programlisting>
public interface StringParameterUnmarshaller&lt;T&gt;
{
   void setAnnotations(Annotation[] annotations);

   T fromString(String str);
}
   </programlisting>
   <para>
   It is similar to <classname>javax.ws.rs.ext.ParamConverter</classname> except that
   </para>
   <itemizedlist>
      <listitem>it converts only from <classname>String</classname>s;</listitem>
      <listitem>it is configured with the annotations on the injected parameter, which 
                allows for fine-grained control over the injection; and</listitem>
      <listitem>it is bound to a given parameter by an annotation that is annotated with the meta-annotation
                <classname>org.jboss.resteasy.annotations.StringParameterUnmarshallerBinder:</classname></listitem>
   </itemizedlist>
   
   <programlisting>
@Target({ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface StringParameterUnmarshallerBinder
{
   Class&lt;? extends StringParameterUnmarshaller&gt; value();
}
   </programlisting>
   <para>
   For example,
   </para>
   
   <programlisting>
   @Retention(RetentionPolicy.RUNTIME)
   @StringParameterUnmarshallerBinder(TestDateFormatter.class)
   public @interface TestDateFormat {
      String value();
   }

   public static class TestDateFormatter implements StringParameterUnmarshaller&lt;Date&gt; {
      private SimpleDateFormat formatter;

      public void setAnnotations(Annotation[] annotations) {
         TestDateFormat format = FindAnnotation.findAnnotation(annotations, TestDateFormat.class);
         formatter = new SimpleDateFormat(format.value());
      }

      public Date fromString(String str) {
         try {
            return formatter.parse(str);
         } catch (ParseException e) {
            throw new RuntimeException(e);
         }
      }
   }
   
   @Path("/")
   public static class TestResource {

      @GET
      @Produces("text/plain")
      @Path("/datetest/{date}")
      public String get(@PathParam("date") @TestDateFormat("MM-dd-yyyy") Date date) {
         Calendar c = Calendar.getInstance();
         c.setTime(date);
         return date.toString();
      }
   }
   </programlisting>
   
   <para>
   Note that the annotation <classname>@StringParameterUnmarshallerBinder</classname> on the
   annotation <classname>@TestDateFormat</classname> binds the formatter
   <classname>TestDateFormatter</classname> to a parameter annotated with <classname>@TestDateFormat</classname>.
   In this example, <classname>TestDateFormatter</classname> is used to format the <classname>Date</classname> parameter.
   Note also that the parameter "MM-dd-yyyy" to <classname>@TestDateFormat</classname> is accessible from
   <methodname>TestDateFormatter.setAnnotations()</methodname>.
   </para>
   </sect1>
   
   <sect1>
   <title>Collections</title>
   
   <para>
   For parameters and properties annotated with <classname>@CookieParam</classname>, <classname>@HeaderParam</classname>,
   <classname>@MatrixParam</classname>, <classname>@PathParam,</classname> or <classname>@QueryParam</classname>, the JAX-RS specification
   [<ulink url="https://jcp.org/aboutJava/communityprocess/final/jsr339/index.html">https://jcp.org/aboutJava/communityprocess/final/jsr339/index.html</ulink>]
   allows conversion as defined in the Javadoc of the
   corresponding annotation. In general, the following types are supported: 
   </para>
   
   <orderedlist>
   <listitem>
   Types for which a <classname>ParamConverter</classname> is available via a registered <classname>ParamConverterProvider</classname>. See
   Javadoc for these classes for more information.
   </listitem>
   <listitem>
   Primitive types.
   </listitem>
   <listitem>
   Types that have a constructor that accepts a single <classname>String</classname> argument.
   </listitem>
   <listitem>
   Types that have a static method named <methodname>valueOf</methodname> or <methodname>fromString</methodname>
   with a single <classname>String</classname> argument
   that return an instance of the type. If both methods are present then <methodname>valueOf</methodname> MUST be used
   unless the type is an enum in which case <methodname>fromString</methodname> MUST be used.
   </listitem>
   <listitem>
   List&lt;T&gt;, Set&lt;T&gt;, or SortedSet&lt;T&gt;, where T satisfies 3 or 4 above.
   </listitem>
   </orderedlist>
   
   <para>
   Items 1, 3, and 4 have been discussed above, and item 2 is obvious. Note that item 5 allows for
   collections of parameters. How these collections are expressed in HTTP messages depends, by
   default, on the particular kind of parameter. In most cases, the notation for collections is based
   on convention rather than a specification.
   </para>
   
   <sect2>
   <title>@QueryParam</title>
   
   <para>
   For example, a multivalued query parameter is conventionally expressed like this:
   </para>
   
   <programlisting>
http://bluemonkeydiamond.com?q=1&amp;q=2&amp;q=3
   </programlisting>
   
   <para>
   In this case, there is a query with name "q" and value {1, 2, 3}. This notation is further supported
   in JAX-RS by the method
   </para>
   
   <programlisting>
public MultivaluedMap&lt;String, String&gt; getQueryParameters();
   </programlisting>
   
   <para>
   in <classname>javax.ws.rs.core.UriInfo</classname>.
   </para>
   </sect2>
   
   <sect2>
   <title>@MatrixParam</title>
   
   <para>
   There is no specified syntax for collections derived from matrix parameters, but
   </para>
   
   <orderedlist>
   <listitem>
   matrix parameters in a URL segment are conventionally separated by ";", and
   </listitem>
   <listitem>
   the method
   <programlisting>
MultivaluedMap&lt;String, String&gt; getMatrixParameters();
   </programlisting>
   <para>
   in <classname>javax.ws.rs.core.PathSegment</classname> supports extraction of collections from matrix parameters.
   </para>
   </listitem>
   </orderedlist>
      
   <para>
   RESTEasy adopts the convention that multiple instances of a matrix parameter with the same name
   are treated as a collection. For example,
   </para>
   <programlisting>
http://bluemonkeydiamond.com/sippycup;m=1;m=2;m=3
   </programlisting>
   
   <para>
   is interpreted as a matrix parameter on path segment "sippycup" with name "m" and value {1, 2, 3}.
   </para>
   </sect2>
   
   <sect2>
   <title>@HeaderParam</title>
   
   <para>
   The HTTP 1.1 specification doesn't exactly specify that multiple components of a header value
   should be separated by commas, but commas are used in those headers that naturally use lists,
   e.g. Accept and Allow. Also, note that the method
   </para>
  
   <programlisting>
public MultivaluedMap&lt;String, String&gt; getRequestHeaders();
   </programlisting>
   
   <para>
   in <classname>javax.ws.rs.core.HttpHeaders</classname> returns a <classname>MultivaluedMap</classname>.
   It is natural, then, for RESTEasy to treat
   </para>
   
   <programlisting>
x-header: a, b, c
   </programlisting>
   
   <para>
   as mapping name "x-header" to set {a, b, c}.
   </para>
   </sect2>
   
   <sect2>
   <title>@CookieParam</title>
   
   <para>
   The syntax for cookies is specified, but, unfortunately, it is specified in multiple competing
   specifications. Typically, multiple name=value cookie pairs are separated by ";". However, unlike
   the case with query and matrix parameters, there is no specified JAX-RS method that returns a
   collection of cookie values. Consequently, if two cookies with the same name are received on
   the server and directed to a collection typed parameter, RESTEasy will inject only the second one.
   Note, in fact, that the method
   </para>
   
   <programlisting>
public Map&lt;String, Cookie&gt; getCookies();
   </programlisting>
   
   <para>
   in <classname>javax.ws.rs.core.HttpHeaders</classname> returns a <classname>Map</classname> rather than a
   <classname>MultivaluedMap</classname>.
   </para>
   
   </sect2>
   
   <sect2>
   <title>@PathParam</title>
   
   <para>
   Deriving a collection from path segments is somewhat less natural than it is for other parameters,
   but JAX-RS supports the injection of multiple <classname>javax.ws.rs.core.PathSegment</classname>s. There are a
   couple of ways of obtaining multiple <classname>PathSegment</classname>s. One is through the use of multiple path
   variables with the same name. For example, the result of calling <methodname>testTwoSegmentsArray()</methodname> and
   <methodname>testTwoSegmentsList()</methodname> in
   </para>
   
   <programlisting>
@Path("")
public static class TestResource {

   @GET
   @Path("{segment}/{other}/{segment}/array")
   public Response getTwoSegmentsArray(@PathParam("segment") PathSegment[] segments) {
      System.out.println("array segments: " + segments.length);
      return Response.ok().build();
   }
   
   @GET
   @Path("{segment}/{other}/{segment}/list")
   public Response getTwoSegmentsList(@PathParam("segment") List&lt;PathSegment&gt; segments) {
      System.out.println("list segments: " + segments.size());
      return Response.ok().build();
   }
}

...

   @Test
   public void testTwoSegmentsArray() throws Exception {
      Invocation.Builder request = client.target("http://localhost:8081/a/b/c/array").request();
      Response response = request.get();
      Assert.assertEquals(200, response.getStatus());
      response.close();
   }
   
   @Test
   public void testTwoSegmentsList() throws Exception {
      Invocation.Builder request = client.target("http://localhost:8081/a/b/c/list").request();
      Response response = request.get();
      Assert.assertEquals(200, response.getStatus());
      response.close();
   }
   </programlisting>
   
   <para>is</para>
   
   <programlisting>
array segments: 2
list segments: 2
   </programlisting>
   
   <para>
   An alternative is to use a wildcard template parameter. For example, the output of calling
   <methodname>testWildcardArray()</methodname> and <methodname>testWildcardList() </methodname>in
   </para>
   
   <programlisting>
@Path("")
public static class TestResource {

   @GET
   @Path("{segments:.*}/array")
   public Response getWildcardArray(@PathParam("segments") PathSegment[] segments) {
      System.out.println("array segments: " + segments.length);
      return Response.ok().build();
   }
   
   @GET
   @Path("{segments:.*}/list")
   public Response getWildcardList(@PathParam("segments") List&lt;PathSegment&gt; segments) {
      System.out.println("list segments: " + segments.size());
      return Response.ok().build();
   }
   
...

   @Test
   public void testWildcardArray() throws Exception {
      Invocation.Builder request = client.target("http://localhost:8081/a/b/c/array").request();
      Response response = request.get();
      response.close();
   }
   
   @Test
   public void testWildcardList() throws Exception {
      Invocation.Builder request = client.target("http://localhost:8081/a/b/c/list").request();
      Response response = request.get();
      response.close();
   }
   </programlisting>
   
   <para>is</para>
   
   <programlisting>
array segments: 3
list segments: 3
   </programlisting>
   
   </sect2>
   </sect1>
   
   <sect1>
   <title>Extension to <classname>ParamConverter</classname> semantics</title>
   
   <para>
   In the JAX-RS semantics, a <classname>ParamConverter</classname> is supposed to convert a single <classname>String</classname> that
   represents an individual object. RESTEasy extends the semantics to allow a <classname>ParamConverter</classname>
   to parse the <classname>String</classname> representation of multiple objects and generate a <classname>List&lt;T&gt;</classname>,
   <classname>Set&lt;T&gt;</classname>, <classname>SortedSet&lt;T&gt;</classname>, array, or, indeed, any multivalued data structure
   whatever. First, consider the resource
   </para>
   
   <programlisting>
@Path("queryParam")
public static class TestResource {

   @GET
   @Path("")
   public Response conversion(@QueryParam("q") List&lt;String&gt; list) {
      return Response.ok(stringify(list)).build();
   }
}

private static &lt;T&gt; String stringify(List&lt;T&gt; list) {
   StringBuffer sb = new StringBuffer();
   for (T s : list) {
      sb.append(s).append(',');
   }
   return sb.toString();
}
   </programlisting>
   
   <para>
   Calling <classname>TestResource</classname> as follows, using the standard notation,
   </para>
   
   <programlisting>
@Test
public void testQueryParamStandard() throws Exception {
   ResteasyClient client = new ResteasyClientBuilder().build();
   Invocation.Builder request = client.target("http://localhost:8081/queryParam?q=20161217&amp;q=20161218&amp;q=20161219").request();
   Response response = request.get();
   System.out.println("response: " + response.readEntity(String.class));
}
   </programlisting>
   
   <para>results in</para>
   
   <programlisting>
response: 20161217,20161218,20161219,
   </programlisting>
   
   <para>
   Suppose, instead, that we want to use a comma separated notation. We can add
   </para>
   
   <programlisting>
public static class MultiValuedParamConverterProvider implements ParamConverterProvider

   @SuppressWarnings("unchecked")
   @Override
   public &lt;T&gt; ParamConverter&lt;T&gt; getConverter(Class&lt;T&gt; rawType, Type genericType, Annotation[] annotations) {
      if (List.class.isAssignableFrom(rawType)) {
         return (ParamConverter&lt;T&gt;) new MultiValuedParamConverter();
      }
      return null;
   }   
}

public static class MultiValuedParamConverter implements ParamConverter&lt;List&lt;?&gt;&gt; {

   @Override
   public List&lt;?&gt; fromString(String param) {
      if (param == null || param.trim().isEmpty()) {
         return null;
      }
      return parse(param.split(","));
   }

   @Override
   public String toString(List&lt;?&gt; list) {
      if (list == null || list.isEmpty()) {
         return null;
      }
      return stringify(list);
   }
   
   private static List&lt;String&gt; parse(String[] params) {
      List&lt;String&gt; list = new ArrayList&lt;String&gt;();
      for (String param : params) {
         list.add(param);
      }
      return list;
   }
}
   </programlisting>
   
   <para>Now we can call</para>
   
   <programlisting>
@Test
public void testQueryParamCustom() throws Exception {
   ResteasyClient client = new ResteasyClientBuilder().build();
   Invocation.Builder request = client.target("http://localhost:8081/queryParam?q=20161217,20161218,20161219").request();
   Response response = request.get();
   System.out.println("response: " + response.readEntity(String.class));
}
   </programlisting>
   
   <para>and get</para>
   
   <programlisting>
response: 20161217,20161218,20161219,
   </programlisting>
   
   <para>
   Note that in this case, <methodname>MultiValuedParamConverter.fromString()</methodname> creates and returns an
   <classname>ArrayList</classname>, so <methodname>TestResource.conversion()</methodname> could be rewritten
   </para>
   
   <programlisting>
@Path("queryParam")
public static class TestResource {

   @GET
   @Path("")
   public Response conversion(@QueryParam("q") ArrayList&lt;String&gt; list) {
      return Response.ok(stringify(list)).build();
   }
}
   </programlisting>
   
   <para>
   On the other hand, <classname>MultiValuedParamConverter</classname> could be rewritten to return a
   <classname>LinkList</classname> and the parameter list in <methodname>TestResource.conversion()</methodname>
   could be either a <classname>List</classname> or a <classname>LinkedList</classname>.
   </para>
   
   <para>
   Finally, note that this extension works for arrays as well. For example,
   </para>
   
   <programlisting>
  public static class Foo {
      private String foo;
      public Foo(String foo) {this.foo = foo;}
      public String getFoo() {return foo;}
   }
   
   public static class FooArrayParamConverter implements ParamConverter&lt;Foo[]&gt; {

      @Override
      public Foo[] fromString(String value)
      {
         String[] ss = value.split(",");
         Foo[] fs = new Foo[ss.length];
         int i = 0;
         for (String s : ss) {
            fs[i++] = new Foo(s);
         }
         return fs;
      }

      @Override
      public String toString(Foo[] values)
      {
         StringBuffer sb = new StringBuffer();
         for (int i = 0; i &lt; values.length; i++) {
            sb.append(values[i].getFoo()).append(",");
         }
         if (sb.length() &gt; 0) {
            sb.deleteCharAt(sb.length() - 1);
         }
         return sb.toString();
      }
   }
   
   @Provider
   public static class FooArrayParamConverterProvider implements ParamConverterProvider {

      @SuppressWarnings("unchecked")
      @Override
      public &lt;T&gt; ParamConverter&lt;T&gt; getConverter(Class&lt;T&gt; rawType, Type genericType, Annotation[] annotations) {
         if (rawType.equals(Foo[].class));
         return (ParamConverter&lt;T&gt;) new FooArrayParamConverter();
      }
   }
   
   @Path("")
   public static class ParamConverterResource {

      @GET
      @Path("test")
      public Response test(@QueryParam("foos") Foo[] foos) {
         return Response.ok(new FooArrayParamConverter().toString(foos)).build();
      }
   }
   </programlisting>
   </sect1>
   
</chapter>
