Entity providers supply mapping services between representations and their associated Java types. The two types of entity providers are MessageBodyReader and MessageBodyWriter. For HTTP requests, the MessageBodyReader is used to map an HTTP request entity body to method parameters. On the response side, a return value is mapped to an HTTP response entity body by using a MessageBodyWriter. If the application needs to supply additional metadata, such as HTTP headers or a different status code, a method can return a Response that wraps the entity and that can be built by using Response.ResponseBuilder.
Table 13–3 shows the standard types that are supported automatically for entities. You need to write an entity provider only if you are not choosing one of these standard types.
Table 13–3 Types Supported for Entities
Java Type |
Supported Media Types |
---|---|
byte[] |
All media types (*/*) |
java.lang.String |
All text media types (text/*) |
java.io.InputStream |
All media types (*/*) |
java.io.Reader |
All media types (*/*) |
java.io.File |
All media types (*/*) |
javax.activation.DataSource |
All media types (*/*) |
javax.xml.transform.Source |
XML media types (text/xml, application/xml, and application/*+xml) |
javax.xml.bind.JAXBElement and application-supplied JAXB classes |
XML media types (text/xml, application/xml, and application/*+xml) |
MultivaluedMap<String, String> |
Form content (application/x-www-form-urlencoded) |
StreamingOutput |
All media types (*/*), MessageBodyWriter only |
The following example shows how to use MessageBodyReader with the @Consumes and @Provider annotations:
@Consumes("application/x-www-form-urlencoded") @Provider public class FormReader implements MessageBodyReader<NameValuePair> {
The following example shows how to use MessageBodyWriter with the @Produces and @Provider annotations:
@Produces("text/html") @Provider public class FormWriter implements MessageBodyWriter<Hashtable<String, String>> {
The following example shows how to use ResponseBuilder:
@GET public Response getItem() { System.out.println("GET ITEM " + container + " " + item); Item i = MemoryStore.MS.getItem(container, item); if (i == null) throw new NotFoundException("Item not found"); Date lastModified = i.getLastModified().getTime(); EntityTag et = new EntityTag(i.getDigest()); ResponseBuilder rb = request.evaluatePreconditions(lastModified, et); if (rb != null) return rb.build(); byte[] b = MemoryStore.MS.getItemData(container, item); return Response.ok(b, i.getMimeType()). lastModified(lastModified).tag(et).build(); }