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 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
|
<chapter id="Multipart">
<title>Multipart Providers</title>
<para>RESTEasy has rich support for the "multipart/*" and "multipart/form-data" mime types. The multipart mime
format is used to pass lists of content bodies. Multiple content bodies are embedded in one message.
"multipart/form-data" is often found in web application HTML Form documents and is generally used to
upload files. The form-data format is the same as other multipart formats, except that each inlined piece
of content has a name associated with it.
</para>
<para>RESTEasy provides
a custom API for reading and writing multipart types as well as marshalling arbitrary List (for any multipart type)
and Map (multipart/form-data only)
objects</para>
<sect1 id="MultipartInput">
<title>Input with multipart/mixed</title>
<para>When writing a JAX-RS service, RESTEasy provides an interface that allows you to read in any
multipart mime type. org.jboss.resteasy.plugins.providers.multipart.MultipartInput</para>
<programlisting>
package org.jboss.resteasy.plugins.providers.multipart;
public interface MultipartInput
{
List<InputPart> getParts();
String getPreamble();
// You must call close to delete any temporary files created
// Otherwise they will be deleted on garbage collection or on JVM exit
void close();
}
public interface InputPart
{
MultivaluedMap<String, String> getHeaders();
String getBodyAsString();
<T> T getBody(Class<T> type, Type genericType) throws IOException;
<T> T getBody(org.jboss.resteasy.util.GenericType<T> type) throws IOException;
MediaType getMediaType();
boolean isContentTypeFromMessage();
}
</programlisting>
<para>MultipartInput is a simple interface that allows you to get access to each part of the multipart message.
Each part is represented by an InputPart interface. Each part has a set of headers associated with it
You can unmarshall the part by calling one of the getBody() methods. The Type genericType parameter can be null,
but the Class type parameter must be set. RESTEasy will find a MessageBodyReader based on the media type
of the part as well as the type information you pass in. The following piece of code is unmarshalling
parts which are XML into a JAXB annotated class called Customer.
</para>
<programlisting>
@Path("/multipart")
public class MyService
{
@PUT
@Consumes("multipart/mixed")
public void put(MultipartInput input)
{
List<Customer> customers = new ArrayList...;
for (InputPart part : input.getParts())
{
Customer cust = part.getBody(Customer.class, null);
customers.add(cust);
}
input.close();
}
}
</programlisting>
<para>
Sometimes you may want to unmarshall a body part that is sensitive to generic type metadata. In this case
you can use the org.jboss.resteasy.util.GenericType class. Here's an example of unmarshalling a type that
is sensitive to generic type metadata.
</para>
<programlisting>
@Path("/multipart")
public class MyService
{
@PUT
@Consumes("multipart/mixed")
public void put(MultipartInput input)
{
for (InputPart part : input.getParts())
{
List<Customer> cust = part.getBody(new GenericType>List>Customer<<() {});
}
input.close();
}
}
</programlisting>
<para>
Use of GenericType is required because it is really the only way to obtain generic type information at runtime.
</para>
</sect1>
<sect1 id="multipart_list">
<title>java.util.List with multipart data</title>
<para>If your body parts are uniform, you do not have to manually unmarshall each and every part.
You can just provide a java.util.List as your input parameter. It must have the type it is
unmarshalling with the generic parameter of the List type declaration. Here's an example again
of unmarshalling a list of customers.</para>
<programlisting>
@Path("/multipart")
public class MyService
{
@PUT
@Consumes("multipart/mixed")
public void put(List<Customer> customers)
{
...
}
}
</programlisting>
</sect1>
<sect1 id="MultipartFormData">
<title>Input with multipart/form-data</title>
<para>When writing a JAX-RS service, RESTEasy provides an interface that allows you to read in
multipart/form-data mime type. "multipart/form-data" is often found in web application HTML Form documents and is generally used to
upload files. The form-data format is the same as other multipart formats, except that each inlined piece
of content has a name associated with it. The interface used for form-data input is
org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput</para>
<programlisting>
public interface MultipartFormDataInput extends MultipartInput
{
@Deprecated
Map<String, InputPart> getFormData();
Map<String, List<InputPart>> getFormDataMap();
<T> T getFormDataPart(String key, Class<T> rawType, Type genericType) throws IOException;
<T> T getFormDataPart(String key, GenericType<T> type) throws IOException;
}
</programlisting>
<para>
It works in much the same way as MultipartInput described earlier in this chapter.
</para>
</sect1>
<sect1 id="multipart_map">
<title>java.util.Map with multipart/form-data</title>
<para>With form-data, if your body parts are uniform, you do not have to manually unmarshall each and every part.
You can just provide a java.util.Map as your input parameter. It must have the type it is
unmarshalling with the generic parameter of the List type declaration. Here's an example of
of unmarshalling a Map of Customer objects which are JAXB annotated classes.</para>
<programlisting>
@Path("/multipart")
public class MyService
{
@PUT
@Consumes("multipart/form-data")
public void put(Map<String, Customer> customers)
{
...
}
}
</programlisting>
</sect1>
<sect1 id="MultipartRelated">
<title>Input with multipart/related</title>
<para>When writing a JAX-RS service, RESTEasy provides an interface that allows you to read in
multipart/related mime type. A multipart/related is used to indicate that message parts
should not be considered individually but rather as parts of an aggregate whole. One example
usage for multipart/related is to send a web page complete with images in a single message.
Every multipart/related message has a root/start part that references the other parts of the message.
The parts are identified by their "Content-ID" headers. multipart/related is defined by RFC 2387.
The interface used for related input is org.jboss.resteasy.plugins.providers.multipart.MultipartRelatedInput</para>
<programlisting>
public interface MultipartRelatedInput extends MultipartInput
{
String getType();
String getStart();
String getStartInfo();
InputPart getRootPart();
Map<String, InputPart> getRelatedMap();
}
</programlisting>
<para>
It works in much the same way as MultipartInput described earlier in this chapter.
</para>
</sect1>
<sect1 id="multipart_output">
<title>Output with multipart</title>
<para>RESTEasy provides a simple API to output multipart data.</para>
<programlisting><![CDATA[
package org.jboss.resteasy.plugins.providers.multipart;
public class MultipartOutput
{
public OutputPart addPart(Object entity, MediaType mediaType)
public OutputPart addPart(Object entity, GenericType type, MediaType mediaType)
public OutputPart addPart(Object entity, Class type, Type genericType, MediaType mediaType)
public List<OutputPart> getParts()
public String getBoundary()
public void setBoundary(String boundary)
}
public class OutputPart
{
public MultivaluedMap<String, Object> getHeaders()
public Object getEntity()
public Class getType()
public Type getGenericType()
public MediaType getMediaType()
}
]]></programlisting>
<para>When you want to output multipart data it is as simple as creating a MultipartOutput object
and calling addPart() methods. RESTEasy will automatically find a MessageBodyWriter
to marshall your entity objects. Like MultipartInput, sometimes you may have marshalling
which is sensitive to generic type metadata. In that case, use GenericType. Most of the time though
passing in an Object and its MediaType is enough. In the example below, we are sending
back a "multipart/mixed" format back to the calling client. The parts are
Customer objects which are JAXB annotated and will be marshalling into "application/xml".</para>
<programlisting>
@Path("/multipart")
public class MyService
{
@GET
@Produces("multipart/mixed")
public MultipartOutput get()
{
MultipartOutput output = new MultipartOutput();
output.addPart(new Customer("bill"), MediaType.APPLICATION_XML_TYPE);
output.addPart(new Customer("monica"), MediaType.APPLICATION_XML_TYPE);
return output;
}
}
</programlisting>
</sect1>
<sect1 id="multipart_list_output">
<title>Multipart Output with java.util.List</title>
<para>If your body parts are uniform, you do not have to manually marshall each and every part or even
use a MultipartOutput object..
You can just provide a java.util.List. It must have the generic type it is
marshalling with the generic parameter of the List type declaration. You must also annotate the method
with the @PartType annotation to specify what media type each part is. Here's an example
of sending back a list of customers back to a client. The customers are JAXB objects</para>
<programlisting>
@Path("/multipart")
public class MyService
{
@GET
@Produces("multipart/mixed")
@PartType("application/xml")
public List<Customer> get()
{
...
}
}
</programlisting>
</sect1>
<sect1 id="multipart_formdata_output">
<title>Output with multipart/form-data</title>
<para>RESTEasy provides a simple API to output multipart/form-data.</para>
<programlisting><![CDATA[
package org.jboss.resteasy.plugins.providers.multipart;
public class MultipartFormDataOutput extends MultipartOutput
{
public OutputPart addFormData(String key, Object entity, MediaType mediaType)
public OutputPart addFormData(String key, Object entity, GenericType type, MediaType mediaType)
public OutputPart addFormData(String key, Object entity, Class type, Type genericType, MediaType mediaType)
public Map<String, OutputPart> getFormData()
public Map<String, List<OutputPart>> getFormDataMap()
}
]]></programlisting>
<para>When you want to output multipart/form-data it is as simple as creating a MultipartFormDataOutput object
and calling addFormData() methods. RESTEasy will automatically find a MessageBodyWriter
to marshall your entity objects. Like MultipartInput, sometimes you may have marshalling
which is sensitive to generic type metadata. In that case, use GenericType. Most of the time though
passing in an Object and its MediaType is enough. In the example below, we are sending
back a "multipart/form-data" format back to the calling client. The parts are
Customer objects which are JAXB annotated and will be marshalling into "application/xml".</para>
<programlisting>
@Path("/form")
public class MyService
{
@GET
@Produces("multipart/form-data")
public MultipartFormDataOutput get()
{
MultipartFormDataOutput output = new MultipartFormDataOutput();
output.addPart("bill", new Customer("bill"), MediaType.APPLICATION_XML_TYPE);
output.addPart("monica", new Customer("monica"), MediaType.APPLICATION_XML_TYPE);
return output;
}
}
</programlisting>
<para>When using form-data format the named content can be a list of OutputPart objects
as long as each object in the named list contains a uniform object and media type.
In the example below, we are sending back a "multipart/form-data" format which consists
of two named list of objects, bill and monica.
</para>
<programlisting>
@Path("/form")
public class MyService
{
@GET
@Produces("multipart/form-data")
public MultipartFormDataOutput get()
{
MultipartFormDataOutput output = new MultipartFormDataOutput();
output.addPart("smith", new Customer("Joe Smith"), MediaType.APPLICATION_XML_TYPE);
output.addPart("monica", new Employee("monica"), MediaType.APPLICATION_JSON_TYPE);
output.addPart("smith", new Customer("Deb Smith"), MediaType.APPLICATION_XML_TYPE);
output.addPart("smith", new Customer("Buba Smith"), MediaType.APPLICATION_XML_TYPE);
return output;
}
}
</programlisting>
</sect1>
<sect1 id="multipart_map_output">
<title>Multipart FormData Output with java.util.Map</title>
<para>If your body parts are uniform, you do not have to manually marshall each and every part or even
use a MultipartFormDataOutput object..
You can just provide a java.util.Map. It must have the generic type it is
marshalling with the generic parameter of the Map type declaration. You must also annotate the method
with the @PartType annotation to specify what media type each part is. Here's an example
of sending back a list of customers back to a client. The customers are JAXB objects</para>
<programlisting>
@Path("/multipart")
public class MyService
{
@GET
@Produces("multipart/form-data")
@PartType("application/xml")
public Map<String, Customer> get()
{
...
}
}
</programlisting>
</sect1>
<sect1 id="multipart_related_output">
<title>Output with multipart/related</title>
<para>RESTEasy provides a simple API to output multipart/related.</para>
<programlisting><![CDATA[
package org.jboss.resteasy.plugins.providers.multipart;
public class MultipartRelatedOutput extends MultipartOutput
{
public OutputPart getRootPart()
public OutputPart addPart(Object entity, MediaType mediaType,
String contentId, String contentTransferEncoding)
public String getStartInfo()
public void setStartInfo(String startInfo)
}
]]></programlisting>
<para>When you want to output multipart/related it is as simple as creating a MultipartRelatedOutput object
and calling addPart() methods. The first added part will be used as the root part of the multipart/related
message.
RESTEasy will automatically find a MessageBodyWriter to marshall your entity objects. Like MultipartInput,
sometimes you may have marshalling which is sensitive to generic type metadata. In that case, use
GenericType. Most of the time though passing in an Object and its MediaType is enough. In the example
below, we are sending back a "multipart/related" format back to the calling client. We are sending a
html with 2 images.</para>
<programlisting>
@Path("/related")
public class MyService
{
@GET
@Produces("multipart/related")
public MultipartRelatedOutput get()
{
MultipartRelatedOutput output = new MultipartRelatedOutput();
output.setStartInfo("text/html");
Map<String, String> mediaTypeParameters = new LinkedHashMap<String, String>();
mediaTypeParameters.put("charset", "UTF-8");
mediaTypeParameters.put("type", "text/html");
output.addPart(
"<html><body>\n"
+ "This is me: <img src='cid:http://example.org/me.png' />\n"
+ "<br />This is you: <img src='cid:http://example.org/you.png' />\n"
+ "</body></html>",
new MediaType("text", "html", mediaTypeParameters),
"<mymessage.xml@example.org>", "8bit");
output.addPart("// binary octets for me png",
new MediaType("image", "png"), "<http://example.org/me.png>",
"binary");
output.addPart("// binary octets for you png", new MediaType(
"image", "png"),
"<http://example.org/you.png>", "binary");
client.putRelated(output);
return output;
}
}
</programlisting>
</sect1>
<sect1 id="multipartform_annotation">
<title>@MultipartForm and POJOs</title>
<para>If you have a exact knowledge of your multipart/form-data packets, you can map
them to and from a POJO class to and from multipart/form-data using the
@org.jboss.resteasy.annotations.providers.multipart.MultipartForm annotation
and the JAX-RS @FormParam annotation. You simple define a POJO with
at least a default constructor and annotate its fields and/or properties
with @FormParams. These @FormParams must also be annotated with
@org.jboss.resteasy.annotations.providers.multipart.PartType if you
are doing output. For example:</para>
<programlisting>
public class CustomerProblemForm {
@FormParam("customer")
@PartType("application/xml")
private Customer customer;
@FormParam("problem")
@PartType("text/plain")
private String problem;
public Customer getCustomer() { return customer; }
public void setCustomer(Customer cust) { this.customer = cust; }
public String getProblem() { return problem; }
public void setProblem(String problem) { this.problem = problem; }
}
</programlisting>
<para>After defining your POJO class you can then use it to represent multipart/form-data. Here's
an example of sending a CustomerProblemForm using the RESTEasy client framework:</para>
<programlisting>
@Path("portal")
public interface CustomerPortal {
@Path("issues/{id}")
@Consumes("multipart/form-data")
@PUT
public void putProblem(@MultipartForm CustomerProblemForm,
@PathParam("id") int id);
}
{
CustomerPortal portal = ProxyFactory.create(CustomerPortal.class, "http://example.com");
CustomerProblemForm form = new CustomerProblemForm();
form.setCustomer(...);
form.setProblem(...);
portal.putProblem(form, 333);
}
</programlisting>
<para>You see that the @MultipartForm annotation was used to tell RESTEasy that the object has @FormParam
and that it should be marshalled from that. You can also use the same object to receive multipart data.
Here is an example of the server side counterpart of our customer portal.</para>
<programlisting>
@Path("portal")
public class CustomerPortalServer {
@Path("issues/{id})
@Consumes("multipart/form-data")
@PUT
public void putIssue(@MultipartForm CustoemrProblemForm,
@PathParam("id") int id) {
... write to database...
}
}
</programlisting>
<para>In addition to the XML data format, you can also use JSON formatted data to represent your POJO classes.
To achieve this goal, you need to plug in a JSON provider into your project. For example,
you can add RESTEasy Jackson2 Provider into your project's dependency scope:
</para>
<programlisting><![CDATA[
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson2-provider</artifactId>
<version>${resteasy.ver}</version>
</dependency>
]]></programlisting>
<para>
And then you can write an ordinary POJO class, which Jackson2 can automatically serialize/deserialize it in
JSON format:
</para>
<programlisting>
public class JsonUser {
private String name;
public JsonUser() {
}
public JsonUser(final String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
</programlisting>
<para>The resource class can be written like this:</para>
<programlisting>
import org.jboss.resteasy.annotations.providers.multipart.MultipartForm;
import org.jboss.resteasy.annotations.providers.multipart.PartType;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
@Path("/")
public class JsonFormResource {
public JsonFormResource() {
}
public static class Form {
@FormParam("user")
@PartType("application/json")
private JsonUser user;
public Form() {
}
public Form(final JsonUser user) {
this.user = user;
}
public JsonUser getUser() {
return user;
}
}
@PUT
@Path("form/class")
@Consumes("multipart/form-data")
public String putMultipartForm(@MultipartForm Form form) {
return form.getUser().getName();
}
}
</programlisting>
<para>As the code shown above, you can see the PartType of JsonUser is marked as "application/json",
and it's included in the "@MultipartForm Form" class instance.
</para>
<para>To send request to the resource method, you need to send JSON formatted data
that is corresponding with the JsonUser class. The easiest to do this is to use a proxy class that has
the same definition like the resource class. Here is the sample code of the proxy class that is corresponding
with the JsonFormResource class:
</para>
<programlisting>
import org.jboss.resteasy.annotations.providers.multipart.MultipartForm;
import javax.ws.rs.Consumes;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
@Path("/")
public interface JsonForm {
@PUT
@Path("form/class")
@Consumes("multipart/form-data")
String putMultipartForm(@MultipartForm JsonFormResource.Form form);
}
</programlisting>
<para>And then you can use the proxy class above to send request to the resource method correctly.
Here is the sample code:</para>
<programlisting>
ResteasyClient client = new ResteasyClientBuilder().build();
...
JsonForm proxy = client.target("your_request_url_address").proxy(JsonForm.class);
String name = proxy.putMultipartForm(new JsonFormResource.Form(new JsonUser("bill")));
...
</programlisting>
<para>And if your client side has Jackson2 provider included, your request will be marshaled correctly,
and your JsonUser data will be converted into JSON format and then send to the server side.
You can also use hand-crafted JSON data as your request and send it to server side, but you have to
make sure the request data is in correct form then.</para>
</sect1>
<sect1 id="xop_with_multipart_related">
<title>XML-binary Optimized Packaging (Xop)</title>
<para>RESTEasy supports Xop messages packaged as multipart/related. What does this mean? If you have a JAXB
annotated POJO that also holds some binary content you may choose to send it in such a way where the binary
does not need to be encoded in any way (neither base64 neither hex). This results in faster transport while
still using the convenient POJO. More about Xop can be read here:
<link linkend="http://www.w3.org/TR/xop10/">http://www.w3.org/TR/xop10/</link>. Now lets see an example:</para>
<para>First we have a JAXB annotated POJO to work with. @XmlMimeType tells JAXB the mime type of the binary
content (its not required to do XOP packaging but it is recommended to be set if you know the exact type):</para>
<programlisting>
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public static class Xop {
private Customer bill;
private Customer monica;
@XmlMimeType(MediaType.APPLICATION_OCTET_STREAM)
private byte[] myBinary;
@XmlMimeType(MediaType.APPLICATION_OCTET_STREAM)
private DataHandler myDataHandler;
// methods, other fields ...
}
</programlisting>
<para>In the above POJO myBinary and myDataHandler will be processed as binary attachments while the whole Xop
object will be sent as xml (in the places of the binaries only their references will be generated).
javax.activation.DataHandler is the most general supported type so if you need an java.io.InputStream or a
javax.activation.DataSource you need to go with the DataHandler. Some other special types are supported too:
java.awt.Image and javax.xml.transform.Source. Let's assume that Customer is also JAXB friendly POJO in the
above example (of course it can also have binary parts). Now lets see a an example Java client that sends this:</para>
<programlisting>
// our client interface:
@Path("mime")
public static interface MultipartClient {
@Path("xop")
@PUT
@Consumes(MultipartConstants.MULTIPART_RELATED)
public void putXop(@XopWithMultipartRelated Xop bean);
}
// Somewhere using it:
{
MultipartClient client = ProxyFactory.create(MultipartClient.class,
"http://www.example.org");
Xop xop = new Xop(new Customer("bill"), new Customer("monica"),
"Hello Xop World!".getBytes("UTF-8"),
new DataHandler(new ByteArrayDataSource("Hello Xop World!".getBytes("UTF-8"),
MediaType.APPLICATION_OCTET_STREAM)));
client.putXop(xop);
}
</programlisting>
<para>We used @Consumes(MultipartConstants.MULTIPART_RELATED) to tell RESTEasy that we want to send multipart/related
packages (that's the container format that will hold our Xop message). We used @XopWithMultipartRelated to tell
RESTEasy that we want to make Xop messages. So we have a POJO and a client service that is willing to send it. All
we need now a server that can read it:</para>
<programlisting>
@Path("/mime")
public class XopService {
@PUT
@Path("xop")
@Consumes(MultipartConstants.MULTIPART_RELATED)
public void putXopWithMultipartRelated(@XopWithMultipartRelated Xop xop) {
// do very important things here
}
}
</programlisting>
<para>We used @Consumes(MultipartConstants.MULTIPART_RELATED) to tell RESTEasy that we want to read multipart/related
packages. We used @XopWithMultipartRelated to tell RESTEasy that we want to read Xop messages. Of course we could
also produce Xop return values but we would than also need to annotate that and use a Produce annotation, too.</para>
</sect1>
<sect1 id="multipart_parsing_note">
<title>Note about multipart parsing and working with other frameworks</title>
<para>There are a lot of frameworks doing multipart parsing automatically with the help of filters and interceptors.
Like org.jboss.seam.web.MultipartFilter in Seam or org.springframework.web.multipart.MultipartResolver in Spring.
However the incoming multipart request stream can be parsed only once. RESTEasy users working with multipart should
make sure that nothing parses the stream before RESTEasy gets it.</para>
</sect1>
<sect1 id="multipart_overwrite_default_content_type">
<title>Overwriting the default fallback content type for multipart messages</title>
<para>By default if no Content-Type header is present in a part, "text/plain; charset=us-ascii" is used as fallback.
This is the value defined by the MIME RFC. However for example some web clients (like most, if not all, web browsers)
do not send Content-Type headers for all fields in a multipart/form-data request (only for the file parts). This can
cause character encoding and unmarshalling errors on the server side. To correct this there is an option to define an
other, non-rfc compliant fallback value. This can be done dynamically per request with the PreProcessInterceptor
infrastructure of RESTEasy. In the following example we will set "*/*; charset=UTF-8" as the new default fallback:
<programlisting>
import org.jboss.resteasy.plugins.providers.multipart.InputPart;
@Provider
@ServerInterceptor
public class ContentTypeSetterPreProcessorInterceptor implements PreProcessInterceptor {
public ServerResponse preProcess(HttpRequest request, ResourceMethod method)
throws Failure, WebApplicationException {
request.setAttribute(InputPart.DEFAULT_CONTENT_TYPE_PROPERTY, "*/*; charset=UTF-8");
return null;
}
}
</programlisting>
</para>
</sect1>
<sect1 id="multipart_overwrite_content_type">
<title>Overwriting the content type for multipart messages</title>
<para>Using an interceptor and the <code>InputPart.DEFAULT_CONTENT_TYPE_PROPERTY</code>
attribute allows setting a default Content-Type, but it is also possible to override
the Content-Type, if any, in any input part by calling
<methodname>org.jboss.resteasy.plugins.providers.multipart.InputPart.setMediaType()</methodname>.
For example:
</para>
<programlisting>
@POST
@Path("query")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)
public Response setMediaType(MultipartInput input) throws IOException
{
List<InputPart> parts = input.getParts();
InputPart part = parts.get(0);
part.setMediaType(MediaType.valueOf("application/foo+xml"));
String s = part.getBody(String.class, null);
...
}
</programlisting>
</sect1>
<sect1 id="multipart_overwrite_default_charset">
<title>Overwriting the default fallback charset for multipart messages</title>
<para>Sometimes, a part may have a Content-Type header with no charset parameter. If the
<code>InputPart.DEFAULT_CONTENT_TYPE_PROPERTY</code> property is set and the value has a charset parameter,
that value will be appended to an existing Content-Type header that has no charset parameter.
It is also possible to specify a default charset using the constant
<code>InputPart.DEFAULT_CHARSET_PROPERTY</code>
(actual value "resteasy.provider.multipart.inputpart.defaultCharset"):
</para>
<programlisting>
import org.jboss.resteasy.plugins.providers.multipart.InputPart;
@Provider
@ServerInterceptor
public class ContentTypeSetterPreProcessorInterceptor implements PreProcessInterceptor {
public ServerResponse preProcess(HttpRequest request, ResourceMethod method)
throws Failure, WebApplicationException {
request.setAttribute(InputPart.DEFAULT_CHARSET_PROPERTY, "UTF-8");
return null;
}
}
</programlisting>
<para>If both <code>InputPart.DEFAULT_CONTENT_TYPE_PROPERTY</code> and
<code>InputPart.DEFAULT_CHARSET_PROPERTY</code> are set, then the value of
<code>InputPart.DEFAULT_CHARSET_PROPERTY</code> will override any charset in the value of
<code>InputPart.DEFAULT_CONTENT_TYPE_PROPERTY</code>.
</para>
</sect1>
</chapter>
|