Previous Topic

Next Topic

Book Contents

Book Index

Accessing Registered JAX-RS Providers Outside the Context of an HTTP Request

This guide contains examples for using the Auxiliaries for Accessing Registered JAX-RS Providers from the Auxiliaries for Development of RESTful Web Services without an HTTP request context.

Example: Deserialization of Web Socket Messages to Java Objects Outside an HTTP Request

The following example demonstrates generic utility for deserialization of web socket messages to Java objects based on the available JAX-RS providers accessible via the ProvidersAccessor utility:

/**

* {@code Message} encapsulates logic for extraction resources from messages received via websocket using JAX-RS

* providers.

*

*/

public final class Message {

  private final Providers providers;

  private final MediaType mediaType;

  private final byte[] data;

  Message(byte[] data, MediaType mediaType, BundleContext context) {

    // get a Providers instance using the factory

    this.providers = ProvidersAccessorFactory.getProvidersAccessor(context);

    

    .....

  }

  ........

  /**

   * Retrieves resource contained in message. The most prioritized of all registered {@link MessageBodyReader} services

   * is used for deserialization. Will throw an {@link IllegalArgumentException} if no provider is found for the

   * resource type.

   *

   * @param clazz The target class of deserialized resource.

   * @return An instance of the target class which represents the resource.

   * @throws IOException If an error occurs while reading object from stream.

   */

  public <T> T getData(Class<T> clazz) throws IOException {

    return getData(clazz, clazz);

  }

  /**

   * Retrieves resource contained in message. The most prioritized of all registered {@link MessageBodyReader} services

   * is used for deserialization. Will throw an {@link IllegalArgumentException} if no provider is found for the

   * resource type.

   *

   * @param clazz The target class of deserialized resource.

   * @param type Generic type of deserialized resource.

   * @return An instance of the target class which represents the resource.

   * @throws IOException If an error occurs while reading object from stream.

   */

  public <T> T getData(Class<T> clazz, Type type) throws IOException {

    MessageBodyReader<T> reader = providers

        .getMessageBodyReader(clazz, type, clazz.getAnnotations(), mediaType);

    if (reader == null) {

      throw new IllegalArgumentException("No provider for type " + clazz.getName() //$NON-NLS-1$

          + (type != null ? ("<" + type + ">") : "")); //$NON-NLS-1$  //$NON-NLS-2$  //$NON-NLS-3$

    }

    return reader.readFrom(clazz, type, clazz.getAnnotations(), mediaType, null, new ByteArrayInputStream(data));

  }

  .......

}