1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
|
<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 <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation annotations[]);
}
</programlisting>
<para>
where a <classname>ParamConverter</classname> is defined:
</para>
<programlisting>
public interface ParamConverter<T> {
...
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 <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) {
if (rawType.isAssignableFrom(Date.class)) {
return (ParamConverter<T>) new DateParamConverter();
}
return null;
}
}
public class DateParamConverter implements ParamConverter<Date> {
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<T>
{
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<? extends StringParameterUnmarshaller> value();
}
</programlisting>
<para>
For example,
</para>
<programlisting>
@Retention(RetentionPolicy.RUNTIME)
@StringParameterUnmarshallerBinder(TestDateFormatter.class)
public @interface TestDateFormat {
String value();
}
public static class TestDateFormatter implements StringParameterUnmarshaller<Date> {
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<T>, Set<T>, or SortedSet<T>, 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&q=2&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<String, String> 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<String, String> 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<String, String> 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<String, Cookie> 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<PathSegment> 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<PathSegment> 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<T></classname>,
<classname>Set<T></classname>, <classname>SortedSet<T></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<String> list) {
return Response.ok(stringify(list)).build();
}
}
private static <T> String stringify(List<T> 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&q=20161218&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 <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) {
if (List.class.isAssignableFrom(rawType)) {
return (ParamConverter<T>) new MultiValuedParamConverter();
}
return null;
}
}
public static class MultiValuedParamConverter implements ParamConverter<List<?>> {
@Override
public List<?> fromString(String param) {
if (param == null || param.trim().isEmpty()) {
return null;
}
return parse(param.split(","));
}
@Override
public String toString(List<?> list) {
if (list == null || list.isEmpty()) {
return null;
}
return stringify(list);
}
private static List<String> parse(String[] params) {
List<String> list = new ArrayList<String>();
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<String> 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<Foo[]> {
@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 < values.length; i++) {
sb.append(values[i].getFoo()).append(",");
}
if (sb.length() > 0) {
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
}
@Provider
public static class FooArrayParamConverterProvider implements ParamConverterProvider {
@SuppressWarnings("unchecked")
@Override
public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) {
if (rawType.equals(Foo[].class));
return (ParamConverter<T>) 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>
|