Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Anchor
_Toc236115243
_Toc236115243
Apache Wink User Guide

Software Version: 0.1

The Apache Wink User Guide document is a broad scope document that provides detailed information about the Apache Wink 0.1 design and implementation.





 

 

Anchor
ContentsTitle
ContentsTitle

Anchor
_Toc229891935
_Toc229891935
Anchor
_Toc230416732
_Toc230416732
Anchor
_Toc236115244
_Toc236115244
Table of Contents
Anchor
_Toc230416733
_Toc230416733

Apache Wink User Guide
Table of Contents
List of Tables
1. Introduction
1.1.1. Important Note
1.2. Target Audience
1.3. JAX-RS Compliancy
2. Apache Wink Architecture
2.1. Wink Runtime Architecture Overview
2.2. Request Processor
2.3. Deployment Configuration
2.3.1. Customization
2.4. Handler Chains
2.5. Registries
2.5.1. Resources Registry
2.5.2. Providers Registry
3. Registration and Configuration
3.1. Simple Application
3.1.1. Specifying the Simple Application File Location
3.2. Wink Application
3.3. Dynamic Resources
3.3.1. Motivation
3.3.2. Usage
3.3.3. Scope
3.4. Priorities
3.4.1. Resource Priorities
3.4.2. Provider Priorities
3.5. Properties
3.5.1. Custom Properties File Definition
3.6. Runtime Registration
3.7. Media-Type Mapping
3.7.1. Customizing Mappings
3.8. Alternative Shortcuts
3.8.1. Customizing Shortcuts
4. Link Builders
4.1. Link Builders Overview
4.2. The "alt" Query Parameter
4.3. System Links Builder
4.3.1. Example
4.4. Single Link Builder
4.5. Generating Absolute or Relative Links
5. Assets
5.1. Assets Overview
5.2. Lifecycle
5.2.1. Response Entity Asset
5.2.2. Request Entity Asset
5.3. Asset Entity Methods
5.3.1. Entity Producing Methods
5.3.2. Entity Consuming Methods
5.4. Parameters
5.5. Return Type
5.6. Exceptions
5.7. Annotation Inheritance
5.8. Entity Method Matching
5.8.1. Request Entity Matching
5.8.2. Response Entity Matching
5.9. Asset Example
6. Providers
6.1. Scoping
6.1.1. Prototype Example
6.1.2. Singleton Example 1
6.1.3. Singleton Example 2
6.2. Priority
6.3. Out-of-the-Box Implementations
6.3.1. Atom Providers
6.3.2. APP Providers
6.3.3. OpenSearch Provider
6.3.4. Json Providers
6.3.5. Asset Provider
6.3.6. HTML Providers
6.3.7. CSV Providers
7. Annotations
7.1. @Workspace Annotation
7.1.1. @Workspace Annotation Example
7.2. @Asset Annotation
7.3. @Scope Annotation
7.3.1. Resource Example
7.3.2. Provider Example
7.4. @Parent Annotation
8. Resource Matching - Continued Search
8.1. Resource Matching Overview
8.2. Configuration
9. Data Models
9.1. JAXB
9.2. JSON
9.3. Syndication
9.4. Atom
9.5. Atom Publishing Protocol (APP)
9.6. Comma Separated Values (CSV)
9.7. OpenSearch
10. APP Service Document
10.1. Enabling the APP Service Document Auto Generation
10.2. Adding Resources to APP Service Document
10.2.1. Example
10.3. APP Service Document HTML Styling
10.4. Implementation
11. Spring Integration
11.1. Spring Registration
11.1.1. Spring Context Loading
11.1.2. Registering Resources and Providers
11.2. Custom Properties File Definition
11.3. Customizing Media-Type Mappings
11.4. Customizing Alternative Shortcuts
11.4.1. External Properties File
11.4.2. Spring Context File
12. WebDAV Extension
12.1. WebDAV Data Model
12.2. WebDAV Classes
12.2.1. WebDAVModelHelper
12.2.2. WebDAVResponseBuilder
12.3. Resource Method Definition
12.4. Creating a Multistatus Response
12.4.1. Using WebDAVResponseBuilder
12.4.2. WebDAVResponseBuilder Example
12.4.3. Manual Creation
13. Handler Chains
13.1. Handlers
13.2. Message Context
13.3. Request Handler Chain
13.3.1. System Request Handlers
13.3.2. User Request Handlers
13.4. Response Handler Chain
13.4.1. System Response Handlers
13.4.2. User Response Handlers
13.5. Error Handler Chain
13.5.1. System Error Handlers
13.5.2. User Error Handlers
13.6. Request Processing
14. Wink Client
14.1. This chapter contains the following sections
14.2. Wink Client Overview
14.4. Dependencies
14.5. Main Features
14.6. High Level Architecture Overview
14.7. Getting Started with the Wink Client
14.7.1. GET Request
14.7.2. POST Request
14.7.3. POST Atom Request
14.7.4. Using ClientResponse
14.8. Client Configuration
14.8.1. Important Note
14.8.2. Handler Configuration
14.8.3. Apache Http Client Configuration
14.8.4. Custom Provider Configuration
14.9. Client Handlers
14.9.1. Custom Handlers
14.9.2. Custom Handler Implementation
14.9.3. Input and Output Stream Adapters
14.9.4. Stream Adapters Example

Anchor
_Toc236115245
_Toc236115245
List of Tables

Table 1: Deployment Configuration Customizable Methods
Table 2: Wink Customization Properties
Table 3: Predefined Mappings
Table 4: Predefined Shortcuts
Table 5: AtomFeedProvider
Table 6: AtomFeedSyndFeedProvider
Table 7: AtomFeedJAXBElementProvider
Table 8: AtomEntryProvider
Table 9: AtomEntrySyndEntryProvider
Table 10: AtomEntryJAXBElementProvider
Table 11: AppServiceProvider
Table 12: AppCategoriesProvider
Table 13: CategoriesProvider
Table 14: OpenSearchDescriptionProvider
Table 15: JsonProvider
Table 16: JsonJAXBProvider
Table 17: JsonSyndEntryProvider
Table 18: JsonSyndFeedProvider
Table 19: AssetProvider
Table 20: HtmlProvider
Table 21: HtmlSyndEntryProvider
Table 22: HtmlSyndFeedProvid
Table 23: CsvSerializerProvider
Table 24: CsvDeserializerProvider
Table 25: @Workspace Annotation Specification
Table 26: @Asset Annotation Specification
Table 27: @Scope Annotation Specification
Table 28: @Parent Annotation Specification
Table 29: Request Handlers
Table 30: Response Handlers
Table 31: Error Handlers



Anchor
_Toc236115246
_Toc236115246
Anchor
_Toc112730035
_Toc112730035
Anchor
OLE_LINK1
OLE_LINK1
Anchor
OLE_LINK2
OLE_LINK2
Introduction

Anchor
OLE_LINK3
OLE_LINK3
Anchor
OLE_LINK4
OLE_LINK4
The purpose of this document is to provide detailed information about Wink and describe the additional features that the Wink runtime provides in addition to the JAX-RS Java API for REST Web Service specification.
In addition to the features description, this document also provides information regarding implementation specific issues.
This document provides the developer with a rudimentary understanding of the Wink implementation in order to highlight the underlying concepts and precepts that make up the framework to create a basis for understanding, cooperation and open development of Wink.

Anchor
_Toc229735275
_Toc229735275
Anchor
_Toc236115247
_Toc236115247
Important Note

Image Added

This User Guide is a Preliminary Draft
This document a preliminary draft and is subject to change in future a release.



Anchor
_Toc236115248
_Toc236115248
Target Audience

In order to understand the contents of this document the reader is required to have read the JAX-RS v1.0 specification and have a rudimentary understanding of the specification and the terminology used to describe the feature set.

For more information on the JAX-RS functionality, refer to the JAX-RS specification document, available at the following location:
http://jcp.org/aboutJava/communityprocess/final/jsr311/index.html

Anchor
_Toc236115249
_Toc236115249
JAX-RS Compliancy

Apache Wink is a complete Java based solution for implementing and consuming Rest based Web Services. The goal of the Wink framework is to provide a reusable and extendable set of classes and interfaces that will serve as a foundation on which a developer can efficiently construct applications.

Wink consists of a Server module for developing Rest services, and of a Client module for consuming Rest services. It cleanly separates the low-level protocol aspects from the application aspects. Therefore, in order to implement and consume Rest Web Services the developer only needs to focus on the application business logic and not on the low-level technical details.

0.1 is a complete and TCK compliant implementation of the JAX-RS v1.0 specification.

Anchor
_Toc236115250
_Toc236115250
Apache Wink Architecture

The following chapter describes the basic concepts and building blocks of Wink and explains the high-level architecture of the Wink runtime.

  1. Anchor
    _Toc229204860
    _Toc229204860

Anchor
_Toc236115251
_Toc236115251
Wink Runtime Architecture Overview

The Wink runtime is deployed on a JEE environment and is configured by defining the RestServlet in the web.xml file of the application. This servlet is the entry point of all the Http requests targeted for web services, and passes the request and response instances to the Wink engine for processing.
Image Added

Anchor
_Toc217886214
_Toc217886214
Figure 1: Request Processor Architecture
The above diagram illustrates the core components of the Wink runtime. The Wink engine is the RequestProcessor. It builds an instance of a MessageContext with all of the required information for the request and passes it through the engine handler chains. The handler chains are responsible for serving the request, invoking the required resource method and finally for generating a response.
In case of an error, the RequestProcessor invokes the Error chain with the generated exception for producing the appropriate response.
The Wink runtime maintains providers and resources in two registries, the Providers Registry and the Resource Registry utilizing them during request processing.

Anchor
_Toc229204861
_Toc229204861
Anchor
_Ref230493743
_Ref230493743
Anchor
_Toc236115252
_Toc236115252
Request Processor

The RequestProcessor is the Wink engine that is initialized by the RestServlet and is populated with an instance of a DeploymentConfiguration.
When a request is passed to the handleRequest() method of the RequestProcessor, a new instance of a MessageContext is created.
The MessageContext contains all of the information that is required for the Wink runtime to handle the request. The RequestProcessor first runs the Request Handler Chain to invoke the resource method and then the Response Handler Chain to produce the response.
If an exception occurs during any stage of the request processing, the RequestProcessor invokes the Error Handler Chain for processing the exception.

Anchor
_Toc229204862
_Toc229204862
Anchor
_Ref229301406
_Ref229301406

Anchor
_Ref230332499
_Ref230332499
Anchor
_Toc236115253
_Toc236115253
Deployment Configuration

The Wink runtime is initialized with an instance of a DeploymentConfiguration. The Deployment Configuration holds the runtime configuration, including the handler chains, registries and configuration properties.
The Deployment Configuration is initialized with an instance of a JAX-RS Application used for obtaining user resources and providers.

Anchor
_Ref229712583
_Ref229712583
Anchor
_Toc236115254
_Toc236115254
Customization

The Deployment Configuration is customized by extending the DeplymentConfiguration class, overriding specific methods and specifying the new class in the web.xml file of the application.
In order to specify a different Deployment Configuration class instead of the default Deployment Configuration, the value of the deploymentConfiguration init parameter must be set to be the fully qualified name of the customized configuration class.

<servlet>
<servlet-name>restSdkService</servlet-name>
<servlet-class>
org.apache.wink.server.internal.servlet.RestServlet
</servlet-class>
<init-param>
<param-name>deploymentConfiguration</param-name>
<param-value>org.apache.example.MyDeploymentConfig</param-value>
</init-param>
</servlet>

The following table details the customizable methods of the DeploymentConfiguration class.

Deployment Configuration

Anchor
_Toc231898861
_Toc231898861
Table 1: Deployment Configuration Customizable Methods

Method

Description

initAlternateShortcutMap

Initializes the AlternateShortcutMap.
Refer to section ‎3.8

initMediaTypeMapper

Initializes the MediaTypeMapper.
Refer to section ‎3.7

initRequestUserHandlers

Return a list of User Handler instances to embed in the Request chain.
Refer to section ‎13.3

initResponseUserHandlers

Return a list of User Handler instances to embed in the Response chain.
Refer to section ‎13.4

initErrorUserHandlers

Return a list of User Handler instances to embed in the Error chain.
Refer to section ‎13.5

Anchor
_Toc229204863
_Toc229204863


Anchor
_Toc236115255
_Toc236115255
Handler Chains

The handler chain pattern is used by the Wink runtime for implementing the core functionalities.
There are three handler chains utilized by the Wink runtime:

  • RequestHandlersChain
  • ResponseHandlersChain
  • ErrorHandlersChain


Refer to chapter ‎13 for more information on Handler Chains.

Anchor
_Toc229204864
_Toc229204864
Anchor
_Toc236115256
_Toc236115256
Registries

The Wink runtime utilizes two registries for maintaining the JAX-RS resources and providers. Both registries maintain their elements in a sorted state according to the JAX-RS specification for increasing performance during request processing. In addition to the JAX-RS specification sorting, Wink supports the prioritization of resources and providers.

Refer to chapter 3, section ‎3.4 for more information on Priorities.



Anchor
_Toc229204865
_Toc229204865

Anchor
_Toc236115257
_Toc236115257
Resources Registry

Image Added
Figure 2: Resource Registry
The resources registry maintains all of the root resources in the form of Resource Records.
A Resource Record holds the following:

  • URI Template Processor – represents a URI template associated with a resource. Used during the resource matching process.
  • Resource Metadata – holds the resource metadata collected from the resource annotations.
  • Sub-Resource Records – records of all the sub-resources (methods and locators) collected from the sub-resource annotations.
  • Resource Factory – a factory that retrieves an instance of the resource in accordance to the creation method defined for the resource. Possible creation methods include:
  • singleton
  • prototype
  • spring configuration
  • user customizable

Anchor
_Toc229204866
_Toc229204866
Anchor
_Toc236115258
_Toc236115258
Providers Registry

The providers registry maintains of all of the system and user providers and manages them in an efficient way.

Anchor
_Toc229122246
_Toc229122246
Anchor
_Ref229368976
_Ref229368976
Anchor
_Ref230510193
_Ref230510193
Anchor
_Ref230517576
_Ref230517576
Anchor
_Toc236115259
_Toc236115259
Registration and Configuration

Wink provides several methods for registering resources and providers. This chapter describes registration methods and Wink configuration options.

  1. Anchor
    _Toc229122247
    _Toc229122247

Anchor
_Toc236115260
_Toc236115260
Simple Application

Wink provides the SimpleWinkApplication class in order to support the loading of resources and providers through a simple text file that contains a list of fully qualified class names of the resource and provider classes.
Each line contains a single fully qualified class name that is either a resource or a provider. Empty lines and lines that begin with a number sign (#) are permitted and ignored.

  1. Providers
    com.example.MyXmlProvider
    com.example.MyJSONProvider

  2. Resources
    com.example.FooResource
    com.example.BarResource



Anchor
_Toc236115261
_Toc236115261
Specifying the Simple Application File Location

The path to a simple application file is configured via the applicationConfigLocation init-param in the web.xml file. It is possible to specify multiple files by separating them with a semicolon.

<servlet>
<servlet-name>restSdkService</servlet-name>
<servlet-class>
org.apache.wink.server.internal.servlet.RestServlet
</servlet-class>
<init-param>
<param-name>applicationConfigLocation</param-name>
<param-value>/WEB-INF/providers;/WEB-INF/resources</param-value>
</init-param>
</servlet>

Anchor
_Toc229122248
_Toc229122248
Anchor
_Ref229187547
_Ref229187547
Anchor
_Toc236115262
_Toc236115262
Wink Application

Wink extends the javax.ws.rs.core.Application class with the org.apache.wink.common.WinkApplication class in order to provide the Dynamic Resources and the Priorities functionality.

Refer to chapter 3, sections ‎3.3 and ‎3.4 for more information on Dynamic Resources and Priorities.

An application may provide an instance of WinkApplication to the Wink runtime as specified by the JAX-RS specification.

Anchor
_Ref229129883
_Ref229129883
Anchor
_Toc229122249
_Toc229122249

Anchor
_Ref230510113
_Ref230510113
Anchor
_Ref230516856
_Ref230516856
Anchor
_Toc236115263
_Toc236115263
Dynamic Resources

Dynamic Resources enable the binding of a Resource class to a URI path during runtime instead of by using the @Path annotation. A dynamic resource must implement the org.apache.wink.server.DynamicResource interface and must not be annotated with the @Path annotation.

Anchor
_Toc236115264
_Toc236115264
Motivation

A Dynamic Resource is useful for situations where a resource class must be bound to multiple paths, for example, a sorting resource:

public class SortingResource<E extends Comparable<? super E>> {
private List<E> list;
@POST
public void sort() {
Collections.sort(list);
}
public void setList(List<E> list) {
this.list = list;
}
public List<E> getList() {
return list;
}
}

In this example, the SortingResource class can sort any list. If the application manages a library of books and exposes the following resource paths, then the SortingResource class can be used for the implementation of all these resource paths, assuming that it could be bound to more than one path.

/sort-books
/sort-authors
/sort-titles

A dynamic resource is also useful for situations where the resource path is unknown during development, and is only known during the application startup.

Anchor
_Toc236115265
_Toc236115265
Usage

A Dynamic Resource is a resource class that implements the org.apache.wink.server.DynamicResource interface or extends the org.apache.wink.server.AbstractDynamicResource convenience class.
A Dynamic Resource is not registered in Wink through the Application#getClasses() method or the Application#getSignletons() method, since the same class can be used for multiple resources.
In order to register Dynamic Resources in the system, the WinkApplication#getInstances()method must be used.

Refer to chapter 3, section ‎3.2 for more information about Wink Application.

Anchor
_Toc236115266
_Toc236115266
Scope

The scope of a Dynamic Resource is limited to singleton as it is initialized prior to its registration, and the system does not have enough information to create it in runtime. This limitation is irrelevant when working with Spring.

Refer to chapter ‎11 for more information about Spring Integration.

Anchor
_Ref229368433
_Ref229368433
Anchor
_Ref229276910
_Ref229276910
Anchor
_Ref229129924
_Ref229129924
Anchor
_Toc229122250
_Toc229122250

Anchor
_Ref230324132
_Ref230324132
Anchor
_Toc236115267
_Toc236115267
Priorities

Although JAX-RS defines the algorithm for searching for resources and providers, Wink extends this algorithm by providing the ability to specify priorities on them. This is achieved by enabling the registration of multiple Application instances with different priorities, rendering the order of their registration irrelevant as long as they have different priorities.
In order to register a prioritized Application, it is necessary to register an instance of a WinkApplication class.
Priority values range between 0 and 1. In the event that the priority was not specified, a default priority of 0.5 is used.

Anchor
_Ref230510146
_Ref230510146
Anchor
_Toc236115268
_Toc236115268
Resource Priorities

Priorities on resources are useful in situations where an application registers core resources bound to paths, and allows extensions to register resources on the same paths in order to override the core resources.
The Wink runtime first sorts the resources based on their priority and then based on the JAX-RS specification, thus if two resources have the same path, the one with higher priority is invoked.

Anchor
_Ref230580727
_Ref230580727
Anchor
_Toc236115269
_Toc236115269
Provider Priorities

JAX-RS requires that application-provided providers be used in preference to implementation pre-packaged providers. Wink extends this requirement by allowing applications to specify a priority for providers.
The Wink runtime initially sorts the matching providers according to the JAX-RS specification, and uses the priority as the last sorting key for providers of equal standing.
If two providers have the same priority, the order in which they are registered determines their priority such that the latest addition receives the highest priority.
In order to meet the JAX-RS requirements, the pre-packages providers are registered using a priority of 0.1.

Anchor
_Toc229122251
_Toc229122251
Anchor
_Ref229359347
_Ref229359347
Anchor
_Ref229370876
_Ref229370876
Anchor
_Ref229371591
_Ref229371591
Anchor
_Ref229371697
_Ref229371697
Anchor
_Ref229372352
_Ref229372352
Anchor
_Ref229389643
_Ref229389643
Anchor
_Ref229390051
_Ref229390051
Anchor
_Ref229454165
_Ref229454165

Anchor
_Ref230516917
_Ref230516917
Anchor
_Toc236115270
_Toc236115270
Properties

Wink provides a properties file in order to enable simple customizations. By default, Wink predefines default values for all possible properties.
Customization Properties

Anchor
_Toc206471219
_Toc206471219
Anchor
_Toc231898862
_Toc231898862
Table 2: Wink Customization Properties

Property Name

Description

Default Value

Ref

wink.http.uri

URI that is used by the Link Builders in case of HTTP

Use the URI from the request.

chapter ‎4

wink.https.uri

URI used by the Link Builders in case of HTTPS.

Use the URI from the request.

chapter ‎4

wink.context.uri

Context path used by the Link Builders.

Use the context path from the request.

chapter ‎4

wink.defaultUrisRelative

Indicates if URIs generated by the Link Builders are absolute or relative. Valid values: true or false

true – links will be relative.

chapter ‎4


wink.addAltParam

Indicates if the "alt" query parameter should be added to URIs generated by the Link Builders. Valid values are: true, false.

true – add the alt query parameter

chapter ‎4

wink.searchPolicyContinuedSearch

Indicates if continues search is enabled. Valid values: true, false

false – continued search is disabled.

chapter ‎8

wink.rootResource

Indicates if a root resource with Service Document generation capabilities should be added.
Valid values are: none, atom, atom+html

atom+html –atom and HTML Service Document generation capabilities

chapter ‎10

wink.serviceDocumentCssPath

Defines path to a css file that is used in the HTML Service Document generation. Relevant only if HTML Service Document is defined.

No css file defined.

chapter ‎10



Anchor
_Toc236115271
_Toc236115271
Custom Properties File Definition

In order to provide a custom properties file, the application should define the propertiesLocation init-param in the Wink Servlet definition.

<servlet>
<servlet-name>restSdkService</servlet-name>
<servlet-class>
org.apache.wink.server.internal.servlet.RestServlet
</servlet-class>
<init-param>
<param-name>propertiesLocation</param-name>
<param-value>/WEB-INF/configuration.properties</param-value>
</init-param>
<init-param>
<param-name>applicationConfigLocation</param-name>
<param-value>/WEB-INF/application</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>


Anchor
_Toc236115272
_Toc236115272
Runtime Registration

Wink provides several APIs for Runtime Registration. The APIs appear in the org.apache.wink.server.utils.RegistrationUtils class.
The most important method is the one that registers an instance of the javax.ws.rs.core.Application class

static void registerApplication(Application application, ServletContext servletContext)

Note

Image Added

Double Registration
Registration is ignored and a warning is printed to the log if the same instance is registered more than once.

Anchor
_Toc228867040
_Toc228867040
Anchor
_Toc229122252
_Toc229122252
Anchor
_Ref229388839
_Ref229388839
Anchor
_Toc236115273
_Toc236115273
Anchor
GlossaryTitle
GlossaryTitle
Anchor
_Toc95274224
_Toc95274224
Media-Type Mapping

It is sometimes necessary to override the Content-Type response header based on the client user agent. For example, the Firefox browser cannot handle the application/atom+xml media type for Atom content, unless it is defined as a text/xml.
Wink provides a set of predefined Media-Type mappings for use in such cases by supplying the MediaTypeMapper class. Applications may extend or override the MediaTypeMapper class to define additional mappings.
Mappings

Anchor
_Toc231898863
_Toc231898863
Table 3: Predefined Mappings

User Agent

Content-Type

Map To

Mozilla/

application/atom+xml

text/xml

Mozilla/

application/atomsvc+xml

text/xml

Mozilla/

application/opensearchdescription+xml

text/xml

Anchor
_Toc236115274
_Toc236115274
Customizing Mappings

In order to customize these mappings the application should create an instance of a org.apache.wink.server.internal.MediaTypeMapper class and set it on the DeploymentConfiguration instance.

Refer to chapter 2, section ‎2.3.1 for more information on Customizing the Default Deployment Configuration.

Anchor
_Toc228867041
_Toc228867041
Anchor
_Toc229122253
_Toc229122253
Anchor
_Ref229388770
_Ref229388770
Anchor
_Ref229707781
_Ref229707781
Anchor
_Toc236115275
_Toc236115275
Alternative Shortcuts

Clients specify the requested media type by setting the Http Accept header. Wink provides an alternate method for specifying the requested media type via use of the "alt" request parameter. This functionality is useful for situations where the client has little affect on the Accept header, for example when requesting a resource using a browser.
A request to "/entry?alt=application/xml" specifies that the requested response media type is application/xml.
Wink provides a shortcut mechanism for specifying the media type of the alt query parameter and provides a predefined set of shortcuts for common media types.
Shortcuts

Anchor
_Toc231898864
_Toc231898864
Table 4: Predefined Shortcuts

Shortcut

Media type

json

text/javascript

atom

application/atom+xml

xml

application/xml

text

text/plain

html

text/html

csv

text/csv

opensearch

application/opensearchdescription+xml

Anchor
_Toc236115276
_Toc236115276
Customizing Shortcuts

The shortcuts table can be customized by overriding the DeploymentConfiguration class.

Refer to chapter 2, section ‎2.3 for more information about Deployment Configuration.


Anchor
_Ref229301528
_Ref229301528
Anchor
_Toc236115277
_Toc236115277
Link Builders

The LinkBuilders interface enables access to two types of links builders, the SystemLinksBuilder and the SingleLinkBuilder. An instance of LinkBuilders is injected into a class field or method parameter using the @Context annotation. Upon creation, the LinkBuilders automatically detects if the target method being invoked is a resource method or a sub-resource method. The "resource" and "subResource" properties of the builder are initialized according to the invoked method type. The link builder interfaces reside in the org.apache.wink.server.utils package.

Anchor
_Toc236115278
_Toc236115278
Link Builders Overview

The JAX-RS specification defines the UriBuilder interface used to construct a URI from a template, but does not specify any mechanism that can automatically generate all resource links.
Wink provides the SystemLinksBuilder for automatic generation of all the alternate links to a resource, one link per every supported media type. For example, this is useful for an application that produces Atom feeds to include in the feed all the alternate representations of the resource.
Wink provides a mechanism for defining if the generated links should be absolute links or relative to a base URI. For example, links embedded in an Atom feed should be as short as possible in order to optimize the payload size.

Anchor
_Toc236115279
_Toc236115279
The "alt" Query Parameter

Wink supports the special query parameter "alt" that is used to override the value of the request Accept header. When the link builders generate a link that specifies the "type" attribute, then the "alt" query parameter is automatically added to the generated link. This is controlled by setting the wink.addAltParam key of the configuration properties file or by calling the LinksBuilder#addAltParam() method.

Refer to chapter 3, section ‎3.5 for more information on Configuration Properties.

Anchor
_Toc236115280
_Toc236115280
System Links Builder

The SystemLinksBuilder interface enables the generation of all, or a subset of, the system links to a resource or its sub-resources. The links are generated as absolute URIs or as relative to the base URI according to the SystemLinksBuilder state, request information or the application configuration.

Anchor
_Toc236115281
_Toc236115281
Example

@Path("defects/{id}")
public class DefectResource {
@GET
@Produces("application/atom+xml")
public SyndEntry getAtom() {
...
}
@GET
@Produces("application/json")
public JSONObject getJson() {
...
}
@GET
@Produces("application/xml")
public Defect getXml(@Context LinkBuilders linkBuilders) {
SystemLinksBuilder builder = linkBuilders.systemLinksBuilder();
List<SyndLink> systemLinks = builder.build(null);
...
}
}

The DefectResource#getXml() method is invoked when a GET request for application/xml is made to /defects/3. The Wink runtime injects an instance of LinkBuilders to the linkBuilder parameter and a new instance of a SystemLinksBuilder is created by invoking the systemLinksBuilder() method.
The call to the build() method of the SystemLinksBuilder generates three alternate links to the DefectResource and the self link:

  • <link rel="self" href="/defects/3"/>
  • <link rel="alternate" type="application/json" href="/defects/3"/>
  • <link rel="alternate" type="application/xml" href="/defects/3"/>
  • <link rel="alternate" type="application/xtom+xml" href="/defects/3"/>

Anchor
_Toc236115282
_Toc236115282
Single Link Builder

The SingleLinkBuilder interface enables the generation of a single link referencing a resource or a sub-resource, allowing the specification of the 'rel' and 'type' attributes of the generated link. The links are generated as absolute URIs or as relative to the base URI according to the SingleLinkBuilder state, request information or the application configuration.

The link builders generate absolute or relative links based on the following algorithm:

  1. Use the value that was passed to the relativize() method of the builder.
  2. If the relativize() method was not called, then use the value of the "relative-urls" query parameter from the request. The value must be either true or false.
  3. If the request does not contain the "relative-urls" query parameter, then use the value of the wink.defaultUrisRelative key set in the application configuration properties file. The value must be either true or false.

    Refer to chapter 3, section ‎3.5 for more information on the Configuration Properties file.


  4. If the configuration key does not exist, then use true.

Anchor
_Ref229215958
_Ref229215958
Anchor
_Toc229458428
_Toc229458428
Anchor
_Toc236115284
_Toc236115284
Anchor
_Toc229294223
_Toc229294223
Anchor
_Toc229294569
_Toc229294569
Assets

An Asset is a special entity that is returned by a resource method or is injected into a resource method as an entity parameter. The asset is used for retrieving the actual request entity or response entity.
The purpose of an asset is to act as a container of an entity data model while providing the transformation methods of the data model into data models of other representations.
Asset classes are POJOs, annotated with the @Asset annotation, that have any number of entity methods.
When an asset instance is returned from a resource method or is set as the entity on a Response instance, it is used by the Wink runtime to retrieve the actual response entity by invoking the appropriate entity-producing method of the asset.

Refer to chapter 5, section ‎5.3.1 for more information on Entity-Producing Methods.

When an asset is the entity parameter of a resource method, it is used by the Wink runtime to set the actual request entity by invoking the appropriate entity-consuming method of the asset.

Refer to chapter 5, section ‎5.3.2 for more information on Entity-Consuming Methods.

Anchor
_Toc236115285
_Toc236115285
Assets Overview

A typical application exposes each resource in a number of representations. Some form of data model usually backs the resource, and the application business logic relies on the manipulation of that data model.
The application will most likely expose resource methods allowing the consumption of the data model in more than one representation (for example Atom and XML) and the production of the data model in other representation (for example Atom, XML and JSON).
According to the JAX-RS specification, the optimal method for implementing a resource is one that consumes and produces an application data model and makes use of a different provider for every media type.
For example, if a resource implements methods that consume and produce a "Defect" bean, then a provider must be implemented for each representation of the "Defect" (Atom, XML and JSON). However, there are times that the transformation of the application data model into a representation requires information that may only be available to the resource but is unavailable to a provider (for example, a connection to the Database).
There are several solutions for dealing with the problem of a provider not having sufficient information to perform application data transformations. The following is a description of two possible solutions:

  • Passing the information as members on the resource and accessing the resource from the provider via the UriInfo context. This solution is only plausible if the resource scope is "per request" and does not work if the resource is a singleton.
  • Passing the information from the resource to the provider via the attributes of the HttpServletRequest. This solution is only plausible when the application is deployed in a JEE container and is not the optimal solution.

Anchor
_Toc229458430
_Toc229458430
In addition to the previously mentioned problem, the creation of a provider for every data model per media type may result in the inflation of providers in the system, causing the provider selection algorithm to consider a large set of potential providers.
As a result, the selection of the actual provider from the set of potential providers is non-deterministic, because the selection between them is undefined.
Note

Image Added

Performance Degradation
An additional side effect of provider inflation is performance degradation.


The use of an asset solves the problem of passing information between a resource and a provider and reduces the amount of registered providers in the system.

Anchor
_Toc236115286
_Toc236115286
Lifecycle

Resource methods can use an asset as a response entity and as a request entity. The Wink runtime applies different lifecycles for each case.

Anchor
_Toc229458431
_Toc229458431
Anchor
_Toc236115287
_Toc236115287
Response Entity Asset

The lifecycle of an asset as a response entity is as follows:

  • The application creates and returns the asset from the resource method.
  • The appropriate entity-producing method is invoked by the Wink runtime to retrieve the actual response entity.
  • The appropriate message body writer as obtained from the Providers#getMessageBodyWriter() method serializes the entity obtained at the previous step.
  • The asset is made available for garbage collection.

Anchor
_Toc229458432
_Toc229458432
Anchor
_Toc236115288
_Toc236115288
Request Entity Asset

The lifecycle of an asset as a request entity is as follows:

  • An asset class is instantiated by the Wink runtime by invoking the asset default constructor. Note that this implies that the asset class must have a public default constructor.
  • The appropriate message body reader as obtained from the Providers#getMessageBodyReader() method is invoked by the Wink runtime to read the request entity.
  • The appropriate entity-consuming method is invoked on the asset to populate the asset with the request entity.
  • The asset is injected into the resource method as the entity parameter.
  • The asset is made available for garbage collection after returning from the resource method.

Anchor
_Toc229458433
_Toc229458433
Anchor
_Toc236115289
_Toc236115289
Asset Entity Methods

Asset Entity methods are the public methods of an asset annotated with either @Consumes or @Produces annotation. Annotating a method with both @Consumes and @Produces annotations is not supported and may result in unexpected behavior.

Anchor
_Ref229101299
_Ref229101299
Anchor
_Toc229367556
_Toc229367556
Anchor
_Toc229458434
_Toc229458434
Anchor
_Toc236115290
_Toc236115290
Entity Producing Methods

An Entity Producing Method is a public asset method annotated with the @Produces annotation, designating it to produce the actual response entity. Such methods produce an entity only for the media types declared in the @Produces annotation. Note that under this definition, wildcard ("/") is allowed.
The Wink runtime will not invoke an entity-producing method whose effective value of @Produces does not match the request Accept header

Anchor
_Ref229101332
_Ref229101332
Anchor
_Toc229367557
_Toc229367557
Anchor
_Toc229458435
_Toc229458435
Anchor
_Toc236115291
_Toc236115291
Entity Consuming Methods

An Entity Consuming Method is a public asset method annotated with the @Consumes annotation, designating it to consume the actual request entity for populating the asset. Such methods consume an entity only for the media types declared in the @Consumes annotation. Note that under this definition, wildcard ("/") is allowed.
The Wink runtime will not invoke an entity-consuming method whose effective value of @Consumes does not match the request Content-Type header.

Anchor
_Toc229367558
_Toc229367558
Anchor
_Toc229458436
_Toc229458436
Anchor
_Toc236115292
_Toc236115292
Parameters

Asset Entity methods support the same parameter types as JAX-RS specifies for a resource method.

Anchor
_Toc229458437
_Toc229458437
Anchor
_Toc236115293
_Toc236115293
Return Type

Entity methods may return any type that is permissible to return from a resource method.

Anchor
_Toc229458438
_Toc229458438
Anchor
_Toc236115294
_Toc236115294
Exceptions

Exceptions thrown from an entity method are treated as exceptions thrown from a resource method.

Anchor
_Toc229458439
_Toc229458439
Anchor
_Toc236115295
_Toc236115295
Annotation Inheritance

The @Produces and @Consumes annotations are not inherited when an asset sub-class overrides an asset entity method. Asset sub-classes must re-declare the @Produces and @Consumes annotations for the overriding method to be an entity method.

Anchor
_Toc229458440
_Toc229458440
Anchor
_Toc236115296
_Toc236115296
Entity Method Matching

Asset classes are handled by the AssetProvider which is a JAX-RS provider that is capable of consuming and producing all media types.

Refer to chapter 3, section ‎6.3.5 for more information on Asset Providers.

Anchor
_Ref229452789
_Ref229452789
Anchor
_Toc229458441
_Toc229458441


Anchor
_Toc236115297
_Toc236115297
Request Entity Matching

The following points describe the process of selecting the asset entity-consuming method to handle the request entity. This process occurs during the invocation of the AssetProvider#isReadable() method.

  • Collect all the entity-consuming methods of the asset. These are the public methods annotated with @Consumes annotation.
  • Sort the collected entity-consuming methods in descending order, where methods with more specific media types precede methods with less specific media types, following the rule n/m > n/* > /.
  • Select the first method that supports the media type of the request entity body as provided to the AssetProvider#isReadable() method, and return true.
  • If no entity-consuming method supports the media type of the request entity body, return false. The Wink runtime continues searching for a different provider to handle the asset as a regular entity.

Anchor
_Ref229451559
_Ref229451559
Anchor
_Toc229458442
_Toc229458442
Anchor
_Toc236115298
_Toc236115298
Response Entity Matching

The following points describe the process of selecting an entity-producing method to produce the actual response entity. The following process occurs during the invocation of the AssetProvider#isWriteable()method.

  • Collect all the entity-producing methods of the asset. These are the public methods annotated with @Produces annotation.
  • Sort the collected entity-producing methods in descending order, where methods with more specific media types precede methods with less specific media types, following the rule n/m > n/* > /.
  • Select the first method that supports the media type of the response entity body as provided to the AssetProvider#isWriteable()method and return true.
  • If no entity-producing method supports the media type of the response entity body, return false. The Wink runtime continues searching for a different provider to handle the asset as a regular entity.

Anchor
_Toc229458443
_Toc229458443


Anchor
_Toc236115299
_Toc236115299
Asset Example

The following example illustrates the use of an asset. The "Defect" bean is a JAXB annotated class.
The DefectAsset class is the asset backed by an instance of a "Defect" bean. The DefectResource class is a resource that is anchored to the URI path "defects/{id}" within the Wink runtime.
DefectAsset Class

@Asset
public class DefectAsset {
public Defect defect;
public DefectAsset(Defect defect) {
this.defect = defect;
}
@Produces("application/xml")
public Defect getDefect() {
return this.defect;
}
@Produces("text/html")
public String getDefectAsHtml() {
String html = ...;
return html;
}

@Produces("application/atom+xml")
public AtomEntry getDefectAsAtom() {
AtomEntry entry = ...;
return entry;
}
@Consumes("application/xml")
public void setDefect(Defect defect) {
this.defect = defect;
}
}

Anchor
_Toc229458445
_Toc229458445

DefectResource Class

@Path("defects/{id}")
public class DefectResource {
@GET
public DefectAsset getDefect(@PathParam("id") String id) {
return new DefectAsset(defects.get(id));
}
@PUT
public DefectAsset updateDefect(DefectAsset defectAsset,
@PathParam("id") String id) {
defects.put(id, defectAsset.getDefect());
return defectAsset;
}
}

Scenario Explanation 1

  • A client issues an HTTP GET request with a URI="/defects/1" and Accept Header= "application/xml"
  • The Wink runtime analyzes the request and invokes the DefectResource#getDefect() resource method.
  • The DefectResource#getDefect() resource method creates an instance of DefectAsset and populates it with defect "1" data.
  • The DefectResource#getDefect() resource method returns the DefectAsset instance back to Wink runtime.
  • The Wink runtime analyzes the asset and invokes the DefectAsset#getDefect() entity-producing method to obtain the reference to the "Defect" bean.
  • The "Defect" bean is serialized by Wink runtime as an XML using the appropriate provider.

Anchor
_Toc229458446
_Toc229458446
Scenario Explanation 2

  • A Client issues an HTTP GET request with a URI="/defects/1" and Accept Header= "text/html"
  • The Wink runtime analyzes the request and invokes the DefectResource#getDefect() resource method
  • The DefectResource#getDefect() resource method creates an instance of DefectAsset and populates it with defect "1" data.
  • The DefectResource#getDefect() method returns the populated asset back to the Wink runtime.
  • The Wink runtime analyzes the asset and invokes the DefectAsset#getDefectAsHtml() entity-producing method in order to obtain the reference to the "Defect" bean.
  • The "Defect" is serialized by Wink runtime as an HTML using the appropriate provider.

Anchor
_Toc229458447
_Toc229458447
Scenario Explanation 3

  • A Client issues an HTTP PUT request with a URI="/defects/1" and Accept Header= "text/html"
  • The Wink runtime analyzes the request and invokes the DefectResource#updateDefect() method with an instance of DefectAsset populated with the request entity.
  • A DefectAsset is instantiated by the Wink runtime
  • The DefectAsset#setDefect() entity-consuming method is invoked in order to populate the DefectAsset with the defect data.

Anchor
_Toc236115300
_Toc236115300
Providers

In addition to JAX-RS standard providers (section 4.2 of the JAX-RS specification), Wink provides a set of complementary providers. The purpose of these providers is to provide mapping services between various representations (for example Atom, APP, OpenSearch, CSV, JSON and HTML) and their associated Java data models.
The Wink providers are pre-registered and delivered with the Wink runtime along with the JAX-RS standard providers.

Anchor
_Toc229294224
_Toc229294224
Anchor
_Toc229294570
_Toc229294570
Anchor
_Toc236115301
_Toc236115301
Scoping

The JAX-RS specification defines that by default, a singleton instance of each provider class is instantiated for each JAX-RS application. Wink fully supports this requirement and in addition provides a "Prototype" lifecycle, which is an instance per-request lifecycle.
Prototype means that a new instance of a provider class is instantiated for each request. The @Scope annotation (section‎0) is used on a provider class to specify its lifecycle. The lifecycle of a provider that does not specify the @Scope annotation defaults to the singleton lifecycle.

Anchor
_Toc236115302
_Toc236115302
Prototype Example

The following example shows how to define a provider with a prototype lifecycle.

@Scope(ScopeType.PROTOTYPE)
@Provider
public class MyProvider implements MessageBodyReader<String>{
...
}

Anchor
_Toc236115303
_Toc236115303
Singleton Example 1

The following example shows how to define a provider with a singleton lifecycle.

@Scope(ScopeType.SINGELTON)
@Provider
public class MyProvider implements MessageBodyReader<String>{
...
}

Anchor
_Toc236115304
_Toc236115304
Singleton Example 2

The following example shows that when the @Scope annotation is not used, the provider will be a singleton, as per the JAX-RS specification.

@Provider
public class MyProvider implements MessageBodyReader<String>{
...
}

Anchor
_Toc229294227
_Toc229294227
Anchor
_Toc229294573
_Toc229294573
Anchor
_Toc236115305
_Toc236115305
Priority

Wink provides a method for setting a priority for a provider.

Refer to chapter 3, section ‎3.4.2 for more information on Provider Priorities.


Anchor
_Toc229294228
_Toc229294228
Anchor
_Toc229294574
_Toc229294574

Anchor
_Toc236115306
_Toc236115306
Out-of-the-Box Implementations

The following section describes the Wink providers that are an addition to the JAX-RS requirements.

Anchor
_Toc229294229
_Toc229294229
Anchor
_Toc229294575
_Toc229294575
Anchor
_Toc236115307
_Toc236115307
Atom Providers

Wink provides a set of entity providers that are capable of mapping Atom Feed and Atom Entry XML documents to and from an Atom data model.

Refer to chapter ‎9 for more information on Data Models.

The following tables list these providers.
AtomFeedProvider

Anchor
_Toc231898865
_Toc231898865
Table 5: AtomFeedProvider

 

Supported

Media Types

Entity

Read

Yes

application/atom+xml

AtomFeed

Write

Yes

application/atom+xml

 

AtomFeedSyndFeedProvider

Anchor
_Toc231898866
_Toc231898866
Table 6: AtomFeedSyndFeedProvider

 

Supported

Media Types

Entity

Read

Yes

application/atom+xml

SyndFeed

Write

Yes

application/atom+xml

 



AtomFeedJAXBElementProvider

Anchor
_Toc231898867
_Toc231898867
Table 7: AtomFeedJAXBElementProvider

 

Supported

Media Types

Entity

Read

Yes

application/atom+xml

JAXBElement<AtomFeed>

Write

Yes

application/atom+xml

 


AtomEntryProvider

Anchor
_Toc231898868
_Toc231898868
Table 8: AtomEntryProvider

 

Supported

Media Types

Entity

Read

Yes

application/atom+xml

AtomEntry

Write

Yes

application/atom+xml

 


AtomEntrySyndEntryProvider

Anchor
_Toc231898869
_Toc231898869
Table 9: AtomEntrySyndEntryProvider

 

Supported

Media Types

Entity

Read

Yes

application/atom+xml

SyndEntry

Write

Yes

application/atom+xml

 



AtomEntryJAXBElementProvider

Anchor
_Toc231898870
_Toc231898870
Table 10: AtomEntryJAXBElementProvider

 

Supported

Media Types

Entity

Read

Yes

application/atom+xml

JAXBElement<AtomEntry>

Write

Yes

application/atom+xml

 

Anchor
_Toc229294230
_Toc229294230
Anchor
_Toc229294576
_Toc229294576
Anchor
_Toc236115308
_Toc236115308
APP Providers

Wink provides a set of providers that are capable of mapping APP Service Document and APP Categories data models to their xml representations. The following tables list these providers.

Refer to chapter 9, section ‎9.5 in chapter 9 for more information on the Atom Publishing Protocol.

AppServiceProvider

Anchor
_Toc231898871
_Toc231898871
Table 11: AppServiceProvider

 

Supported

Media Types

Entity

Read

No

N/A

N/A

Write

Yes

application/atomsvc+xml

AppService


AppCategoriesProvider

Anchor
_Toc231898872
_Toc231898872
Table 12: AppCategoriesProvider

 

Supported

Media Types

Entity

Read

No

N/A

N/A
AppCategories

Write

Yes

application/atomcat+xml

 

Anchor
_Toc229294231
_Toc229294231
Anchor
_Toc229294577
_Toc229294577
CategoriesProvider
Anchor
_Toc231898873
_Toc231898873
Table 13: CategoriesProvider

 

Supported

Media Types

Entity

Read

No

N/A

N/A

Write

Yes

application/atomcat+xml

Categories

Anchor
_Toc236115309
_Toc236115309
OpenSearch Provider

Wink provides a single provider that is capable of serializing the OpenSearch data model.

Refer to the xml representations chapter 9, section ‎9.7 for more information on OpenSearch.


Anchor
_Toc229294232
_Toc229294232
Anchor
_Toc229294578
_Toc229294578
OpenSearchDescriptionProvider
Anchor
_Toc231898874
_Toc231898874
Table 14: OpenSearchDescriptionProvider

 

Supported

Media Types

Entity

Read

No

N/A

N/A

Write

Yes

application/opensearchdescription+xml

OpenSearchDescription


Anchor
_Toc236115310
_Toc236115310
Json Providers

Wink provides a set providers that are capable of serializing a number of data models (JSONObject, JAXBElement, SyndEntry, SyndFeed) into JSON representations. The following tables list these providers.
JsonProvider

Anchor
_Toc231898875
_Toc231898875
Table 15: JsonProvider

 

Supported

Media Types

Entity

Read

No

N/A

N/A

Write

Yes

application/json , application/javascript

JSONObject


JsonJAXBProvider

Anchor
_Toc231898876
_Toc231898876
Table 16: JsonJAXBProvider

 

Supported

Media Types

Entity

Read

No

N/A

N/A

Write

Yes

application/json , application/javascript

JAXB object,
JAXBElement<?>


JsonSyndEntryProvider

Anchor
_Toc231898877
_Toc231898877
Table 17: JsonSyndEntryProvider

 

Supported

Media Types

Entity

Read

No

N/A

N/A

Write

Yes

application/json , application/javascript

SyndEntry

Anchor
_Toc229294233
_Toc229294233
Anchor
_Toc229294579
_Toc229294579
JsonSyndFeedProvider
Anchor
_Toc231898878
_Toc231898878
Table 18: JsonSyndFeedProvider

 

Supported

Media Types

Entity

Read

No

N/A

N/A

Write

Yes

application/json , application/javascript

SyndFeed

Anchor
_Ref230580436
_Ref230580436
Anchor
_Toc236115311
_Toc236115311
Asset Provider

Wink provides a special provider that is responsible for reading and writing Asset objects.

Refer to chapter 5 for more information on Assets.

Anchor
_Toc229294234
_Toc229294234
Anchor
_Toc229294580
_Toc229294580

AssetProvider
Anchor
_Toc231898879
_Toc231898879
Table 19: AssetProvider

 

Supported

Media Types

Entity

Read

Yes

/

POJOs annotated with @Asset annotation.

Write

Yes

/

POJOs annotated with @Asset annotation.



Anchor
_Toc236115312
_Toc236115312
HTML Providers

Wink provides a set of providers that are capable of serializing a number of data models (SyndEntry, SyndFeed and HtmlDescriptor) as HTML. The following tables list these providers.
HtmlProvider

Anchor
_Toc231898880
_Toc231898880
Table 20: HtmlProvider

 

Supported

Media Types

Entity

Read

NO

N/A

N/A

Write

Yes

text/html

HtmlDescriptor


HtmlSyndEntryProvider

Anchor
_Toc231898881
_Toc231898881
Table 21: HtmlSyndEntryProvider

 

Supported

Media Types

Entity

Read

NO

N/A

N/A

Write

Yes

text/html

SyndEntry

Anchor
_Toc229294235
_Toc229294235
Anchor
_Toc229294581
_Toc229294581

HtmlSyndFeedProvid
Anchor
_Toc231898882
_Toc231898882
Table 22: HtmlSyndFeedProvid

 

Supported

Media Types

Entity

Read

NO

N/A

N/A

Write

Yes

text/html

SyndFeed

Anchor
_Toc236115313
_Toc236115313
CSV Providers

Wink supports the serializing and de-serializing of data as a CSV.

Refer to chapter 9, section ‎9.6 for more information on Comma Separated Values.


The following tables list the providers that provide this functionality.
CsvSerializerProvider

Anchor
_Toc231898883
_Toc231898883
Table 23: CsvSerializerProvider

 

Supported

Media Types

Entity

Read

NO

N/A

N/A

Write

Yes

text/csv

CsvSerializer


CsvDeserializerProvider

Anchor
_Toc231898884
_Toc231898884
Table 24: CsvDeserializerProvider

 

Supported

Media Types

Entity

Read

Yes

text/csv

CsvDeserializer

Write

NO

N/A

N/A


Anchor
_Toc236115314
_Toc236115314
Annotations

Wink provides several annotations in addition to those defined by the JAX-RS specification. The following section describes these annotations in detail.

Anchor
_Ref229371856
_Ref229371856
Anchor
_Toc236115315
_Toc236115315
@Workspace Annotation

The purpose of the @Workspace annotation is to associate a "Collection Resource" with a workspace element and collection elements in an APP Service Document.

Refer to chapter ‎10 for more information on APP Service Document.

The workspaceTitle annotation parameter specifies the title of the workspace and the collectionTitle annotation parameter specifies the title of the collection.
Annotation Specification

Anchor
_Toc231898885
_Toc231898885
Table 25: @Workspace Annotation Specification

Value

Description

 

Mandatory

No

 

Target

Resource class

 

Parameters

Name

Type

 

workspaceTitle

String

 

collectionTitle

String

Example

@Workspace(workspaceTitle = "Title",
collectionTitle = "Collection")

 

Anchor
_Toc236115316
_Toc236115316
@Workspace Annotation Example

The following example demonstrates the use of @Workspace annotation on two resources in order to have the auto-generated APP service document contain the information about them.
Given the following collection Resources definitions, ResourceA and ResourceB, the result is displayed in the "Auto Generated APP Service Document" table that follows.
ResourceA Definition

@Workspace(workspaceTitle = "Services", collectionTitle = "Service1")
@Path("services/service1")
public class ResourceA {
@POST
@Produces("text/plain")
@Consumes({"application/atom+xml", "application/xml"})
public String getText() {return "hey there1";}
}

ResourceB Definition

@Workspace(workspaceTitle = "Services", collectionTitle = "Service2")
@Path("services/service2")
public class ResourceB {
@POST
@Produces("text/plain")
@Consumes({"application/atom+xml", "application/xml"})
public String getText() {return "hey there2";}
}


The auto-generated APP Service Document is as follows:
Auto Generated APP Service Document

<service xmlns:atom=http://www.w3.org/2005/Atom
xmlns="http://www.w3.org/2007/app">
<workspace>
<atom:title>Services</atom:title>
<collection href="services/service1">
<atom:title>Service1</atom:title>
<accept>application/xml</accept>
<accept>application/atom+xml</accept>
</collection>
<collection href="services/service2">
<atom:title>Service2</atom:title>
<accept>application/xml</accept>
<accept>application/atom+xml</accept>
</collection>
</workspace>
</service>



Anchor
_Toc236115317
_Toc236115317
@Asset Annotation

The @Asset annotation is a marker annotation used by the Wink runtime in order to identify an entity as an Asset.

Refer to chapter ‎5 for more information on Assets.

Anchor
_Toc229294588
_Toc229294588
Anchor
_Ref229368941
_Ref229368941

Annotation Specification
Anchor
_Toc231898886
_Toc231898886
Table 26: @Asset Annotation Specification

Value

Description

Mandatory

No

Target

Resource class

Parameters

None

Example

@Asset



Anchor
_Ref230580684
_Ref230580684
Anchor
_Toc236115318
_Toc236115318
@Scope Annotation

The JAX-RS specification defines the default lifecycle behavior for resources and providers, and the option for controlling the lifecycle through the javax.ws.rs.core.Application class.
Wink provides the @Scope annotation to specify the lifecycle of a provider or resource.

Anchor
_Toc229294590
_Toc229294590

Annotation Specification
Anchor
_Toc231898887
_Toc231898887
Table 27: @Scope Annotation Specification

Value

Description

 

Mandatory

No

 

Target

Provider class or Resource class

 

Parameters

Name

Type

 

value

ScopeType enum

Example

@Scope(ScopeType.PROTOTYPE)

 

Anchor
_Toc236115319
_Toc236115319
Resource Example

The following example illustrates how to define a resource with a singleton lifecycle.

@Scope(ScopeType.SINGLETON)
@Path("service1")
public class ResourceA {
...
}

Anchor
_Toc236115320
_Toc236115320
Provider Example

The following example illustrates how to define a provider with a prototype lifecycle.

@Scope(ScopeType.PROTOTYPE)
@Provider
public class EntityProvider implements MessageBodyReader<String> {
...
}

Anchor
_Toc236115321
_Toc236115321
@Parent Annotation

The @Parent annotation provides the ability to define a base template URI for the URI specified in a resources @Path annotation.
If a resource is annotated with the @Parent annotation, the Wink runtime calculates the final resource template by first retrieving the value of the @Parent annotation, which holds the parent resource class, and then concatenates the resource path template definition to the path template definition of the parent resource.
Annotation Specification

Anchor
_Toc231898888
_Toc231898888
Table 28: @Parent Annotation Specification

Value

Description

 

Mandatory

No

 

Target

Resource class

 

Parameters

Name

Type

 

value

Class<?>

Example

@Parent(ParentResource.class)

 

Example

@Path("services")
public class ParentResource {
...
}


@Parent(BaseResource.class)
@Path("service1")
public class ResourceA {
...
}

Explanation
In the example, the user defined two resources: A ParentResource and ResourceA. ParentResource defines the @Path annotation to associate it with "services" URI. ResourceA defines the @Path annotation to associate it with "service1" URI and defines ParentResource to be its parent by specifying it in the @Parent annotation. In this case, the final URI path for ResourceA is "services/service1".

Anchor
_Toc228867059
_Toc228867059
Anchor
_Ref229128763
_Ref229128763
Anchor
_Ref229301513
_Ref229301513
Anchor
_Toc236115322
_Toc236115322
Resource Matching - Continued Search

Wink provides a Continued Search mode when searching for a resource method to invoke during request processing, which is an extended search mode to the algorithm defined by the JAX-RS specification.

Anchor
_Toc236115323
_Toc236115323
Resource Matching Overview

Section 3.7.2 of the JAX-RS specification describes the process of matching requests to resource methods. The fact that only the first matching root resource (section 1(f) of the algorithm) and only the first matching sub-resource locator (section 2(g) of the algorithm) are selected during the process makes it difficult for application developers to implement certain scenarios.
For example, it is impossible to have two resources anchored to the same URI, each having its own set of supported methods:

@Path("my/service")
public class ResourceA {
@GET
@Produces("text/plain")
public String getText() {...}
}

@Path("my/service")
public class ResourceB {
@GET
@Produces("text/html")
public String getHtml() {...}
}

Explanation
In order to implement this according to the JAX-RS specification, ResourceB must extend ResourceA and be registered instead of ResourceA. However, this may not always be possible, such as in an application that uses JAX-RS as the web service frontend while providing an open architecture for registering extending services. For example, Firefox that provides an Extensions mechanism. The extending service must be aware of the core implementation workings and classes, that may not always be plausible. Moreover, it is impossible for a service to extend the functionality of another service without knowing the inner workings of that service, that creates an "evil" dependency between service implementations.
In order to solve this problem, Wink provides a special resource Continued Search mode when searching for a resource and method to invoke. By default, this mode is off, meaning that the search algorithm is strictly JAX-RS compliant. When this mode is activated, and a root resource or sub-resource locator proves to be a dead-end, the Wink runtime will continue to search from the next root-resource or sub-resource locator, as if they were the first match.
In the previous example, there is no way to know which of the resources is a first match for a request to "/my/service". If the Continued Search mode is off, either the getText() method is unreachable or the getHtml() method is unreachable. However, when the Continued Search mode is active, a request for text/plain reaches the getText() method in ResourceA, and a request for text/html reaches the getHtml() method in ResourceB.

Anchor
_Toc236115324
_Toc236115324
Configuration

The Continued Search mode is activated by setting the value of the wink.searchPolicyContinuedSearch key in the application configuration properties file to true.
If the key is set to anything else but true or if it does not exist in the properties file, then the Continued Search mode is set to off, and the behavior is strictly JAX-RS compliant.

Anchor
_Ref229389860
_Ref229389860
Anchor
_Toc236115325
_Toc236115325
Data Models

The following chapter describes the out-of-the-box data models provided and supported by the Wink runtime.

Anchor
_Toc236115326
_Toc236115326
JAXB

Wink supports JAXB objects for consuming and producing XML (application/xml), and for producing JSON (application/json).
An application may provide a ContextResolver for obtaining the JAXBContext of the JAXB object. If no suitable JAXBContext is obtained from a ContextResolver, then the Wink runtime uses a default JAXBContext initialized with the JAXB object.

Anchor
_Toc236115327
_Toc236115327
JSON

Wink utilizes the json.org implementation for producing JSON (application/json).

Anchor
_Toc236115328
_Toc236115328
Syndication

Wink provides a syndication data model for producing Atom (application/atom+xml), HTML (text/html), JSON (application/json) and CSV (text/csv), and for consuming Atom and CSV. All of the model classes are located under the org.apache.wink.common.model.synd package.

Anchor
_Ref229389929
_Ref229389929
Anchor
_Toc236115329
_Toc236115329
Atom

Wink provides an Atom 1.0 data model for consuming and producing Atom feeds and entries (application/atom+xml). All of the model classes are located under the org.apache.wink.common.model.atom package.

Anchor
_Ref229389892
_Ref229389892
Anchor
_Toc236115330
_Toc236115330
Atom Publishing Protocol (APP)

Wink provides an Atom Publishing Protocol data model for producing Service Documents (application/atomsvc+xml) and Categories Documents (application/atomcat+xml). The APP data model can also be used to produce Service and Categories documents in HTML (text/html) and JSON (application/json) formats. All of the model classes are located under the org.apache.wink.common.model.app package.

Anchor
_Ref229389975
_Ref229389975
Anchor
_Toc236115331
_Toc236115331
Comma Separated Values (CSV)

Wink provides a CSV data model for producing and consuming CSV (text/csv). The model is based on a Serialization and a Deserialization interface, in addition to a simple CSV Table class. All of the model classes are located under the org.apache.wink.common.model.csv package.

Anchor
_Ref229389913
_Ref229389913
Anchor
_Toc236115332
_Toc236115332
OpenSearch

Wink provides an OpenSearch data model for producing OpenSearch Description Documents (application/opensearchdescription+xml). All of the model classes are located under the org.apache.wink.common.model.opensearch package.

Anchor
_Ref229207493
_Ref229207493
Anchor
_Toc236115333
_Toc236115333
APP Service Document

Wink supports the automatic and manual generation of APP Service Documents by providing an APP data model and set of complementary providers.
Atom Publishing Protocol Service Documents are designed to support the auto-discovery of services. APP Service Documents represent server-defined groups of Collections used to initialize the process of creating and editing resources. These groups of collections are called Workspaces. The Service Document can indicate which media types and categories a collection accepts.
The Wink runtime supports the generation of the APP Service Documents in the XML (application/atomsvc+xml) and HTML (text/html) representations.

Anchor
_Toc236115334
_Toc236115334
Enabling the APP Service Document Auto Generation

APP Service Document generation is activated by setting the wink.rootResource key in the configuration properties file. By default, the key value is set to "atom+html", indicating that both XML (application/atomsvc+xml) and HTML (text/html) representations are available.
Once activated, the auto-generated APP Service Document is available at the application root URL "http://host:port/application".

Anchor
_Toc236115335
_Toc236115335
Adding Resources to APP Service Document

Wink provides the @Workspace annotation used to associate a Collection Resource with an APP Service Document workspace and collection elements. The only requirement to incorporate a collection resource in a service document is to place the @Workspace annotation on the resource.

Refer to chapter 7, section ‎7.1 for more information on the @Workspace annotation.



Anchor
_Toc236115336
_Toc236115336
Example

Given the following collection resource definition:

@Workspace(workspaceTitle = "Workspace", collectionTitle = "Title")
@Path("my/service")
public class ResourceA {
...
}

The auto-generated APP Service Document is:

<service xmlns:atom=http://www.w3.org/2005/Atom
xmlns="http://www.w3.org/2007/app">
<workspace>
<atom:title>Workspace</atom:title>
<collection href="my/service">
<atom:title>Title</atom:title>
<accept/>
</collection>
</workspace>
</service>

Anchor
_Toc236115337
_Toc236115337
APP Service Document HTML Styling

Wink provides the ability to change the default styling of the APP Service Document HTML representation. The styling is changed by setting the value of the wink.serviceDocumentCssPath key in the configuration properties file to the application specific CSS file location.

Anchor
_Toc236115338
_Toc236115338
Implementation

The following classes implement the APP Service Document support:

  • org.apache.wink.server.internal.resources.RootResource – generates the XML (application/atomsvc+xml) representation of the APP Service Document.
  • org.apache.wink.server.internal.resources. HtmlServiceDocumentResource - generates the HTML (text/html) representation of the APP Service Document.


Anchor
_Ref229301429
_Ref229301429
Anchor
_Ref229301456
_Ref229301456
Anchor
_Toc229302820
_Toc229302820
Anchor
_Ref229389761
_Ref229389761
Anchor
_Toc236115339
_Toc236115339
Spring Integration

Wink provides an additional module deployed as an external jar in order to provide Spring integration.
The Spring integration provides the following features:

  • The ability to register resources and providers from the Spring context, registered as classes or as Spring beans.
  • The ability to define the lifecycle of resources or providers that are registered as Spring beans, overriding the default scope specified by the JAX-RS specification.
  • Resources and providers can benefit from Spring features such as IoC and post-processors.
  • Customize Wink from the Spring context. When working with Spring, Wink defines a core spring context that contains customization hooks, enabling easy customization that would otherwise require coding.


Anchor
_Toc236115340
_Toc236115340
Spring Registration

Spring makes it convenient to register resources and providers as spring beans.

Anchor
_Toc236115341
_Toc236115341
Spring Context Loading

In order to load the Spring Context, it is necessary to add a Context Load Listener definition to the web.xml file. The contextConfigLocation context-param must specify the location of the Wink core context file and the application context file, as described in the following example:

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:META-INF/server/wink-core-context.xml
classpath:mycontext.xml
</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

Anchor
_Toc236115342
_Toc236115342
Registering Resources and Providers

Wink provides the org.apache.wink.spring.Registrar class in order to register resources and providers through a Spring context. The Registrar class extends the WinkApplication class and must be registered as a singleton spring bean. It is possible to define multiple registrars in the same context.
All registrars are automatically collected by the runtime and registered as WinkApplication objects during the context loading.
The registrar provides the following properties:

  • instances – instances of resources and providers. Ordinarily, these instances are Spring beans, so they can benefit from IoC and other Spring features.
  • classes – a set of resources and providers class names. This property is similar to the getClasses() method of the Application class.
  • priority – the priority of the WinkApplication


Refer to chapter 3, section ‎3.4 for more information on Priorities.

<bean class="org.apache.wink.spring.Registrar">
<property name="classes">
<set value-type="java.lang.Class">
<value>package.className</value>
</set>
</property>
<property name="instances">
<set>
<ref bean="resources.resource1" />
<ref bean="resources.resource2" />
<ref bean="providers.provider1" />
</set>
</property>
</bean>



Anchor
_Toc236115343
_Toc236115343
Custom Properties File Definition

Wink provides a set of customizable properties. When working with Spring, the user should redefine the custom properties file using the Spring context:

<bean id="customPropertiesFactory"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>WEB-INF/configuration.properties</value>
</list>
</property>
</bean>
<bean id="customConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="order" value="1" />
<property name="propertiesArray">
<list>
<props>
<prop key="winkInternalPropertiesFactory">customPropertiesFactory</prop>
</props>
</list>
</property>
</bean>


  • The customPropertiesFactory bean loads the properties file.
  • The customConfigurer bean overrides the default factory with a custom factory.
  • The order is set to "1". This makes the customConfigurer bean run before the default Wink configurer.
  • In addition, notice that ignoreUnresolvablePlaceholders must be set to true, otherwise the configurer will fail, since some unresolved properties can remain in the context.

Anchor
_Toc236115344
_Toc236115344
Customizing Media-Type Mappings

Wink provides the ability to customize the Media-Type mappings using Spring context.

Refer to chapter 3, section ‎3.7 for more information on Media-Type Mapping.


<bean id="custom.MediaTypeMapper" class="org.apache.wink.server.internal.MediaTypeMapper">
<property name="mappings">
<list>
<map>
<entry key="userAgentStartsWith" value="Mozilla/" />
<entry key="resultMediaType">
<util:constant static-field=" javax.ws.rs.core.MediaType.ATOM" />
</entry>
<entry key="typeToSend">
<util:constant static-field="javax.ws.rs.core.MediaType.TEXT_XML" />
</entry>
</map>
</list>
</property>
</bean>
<bean id="customConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="order" value="1" />
<property name="propertiesArray">
<list>
<props>
<prop key="winkMediaTypeMapper">custom.MediaTypeMapper</prop>
</props>
</list>
</property>
</bean>


  • The custom.MediaTypeMapper bean creates a new Media-Type mapper.
  • The customConfigurer bean overrides the default factory with a custom factory.

Note

Image Added

customConfigurer
The order is set to "1". This makes the customConfigurer run before the default Wink configurer.

  • In addition, notice that ignoreUnresolvablePlaceholders must be set to true, otherwise the configurer will fail, since some unresolved properties can remain in the context.


Anchor
_Toc236115345
_Toc236115345
Customizing Alternative Shortcuts

Wink provides the ability to customize the Alternative Shortcuts in one of two ways.

Refer to chapter 3, section ‎3.8 for more information on Alternative Shortcuts Mappings.

Anchor
_Toc236115346
_Toc236115346
External Properties File

The shortcuts are defined in a properties file. The shortcuts properties file is loaded in the same way that the configuration properties file is loaded.

<bean id="custom.Shortcuts"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>WEB-INF/shortcuts</value>
</list>
</property>
</bean>
<bean id="customConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="order" value="1" />
<property name="propertiesArray">
<list>
<props>
<prop key="winkAlternateShortcutsMap">custom.Shortcuts</prop>
</props>
</list>
</property>
</bean>

Anchor
_Toc236115347
_Toc236115347
Spring Context File

Defines the map of the shortcuts in the Spring context.

Anchor
_Toc236115348
_Toc236115348
WebDAV Extension

Anchor
_Toc223239121
_Toc223239121
Wink provides an extension module for supporting the WebDAV protocol. The extension contains the complete WebDAV XML model and a WebDAV response builder for easing the process of creating a WebDAV multistatus response.
The WebDAV extension is a single jar wink-webdav-<version>.jar, and it has no special dependencies.

Anchor
_Toc236115349
_Toc236115349
Anchor
_Toc223239122
_Toc223239122
WebDAV Data Model

The WebDAV extension provides a Java data model that reflects the WebDAV XMLs defined in the WebDAV RFC. All classes of the data model are located in the org.apache.wink.webdav.model package.

Anchor
_Toc223239123
_Toc223239123
Anchor
_Toc236115350
_Toc236115350
WebDAV Classes

The WebDAV extension provides several classes that applications can use in order to receive basic support for common WebDAV methods

Anchor
_Toc236115351
_Toc236115351
WebDAVModelHelper

The WebDAVModelHelper class provides helper methods for XML marshaling and unmarshaling of the WebDAV data model classes. It also provides helper methods for creating generic properties as DOM element classes to populate the WebDAV Prop element.

Anchor
_Toc236115352
_Toc236115352
WebDAVResponseBuilder

The WebDAVResponseBuilder class is used in order to create responses to WebDAV PROPFIND requests. It takes a SyndEntry or SyndFeed as input in order to create the response.

Anchor
_Toc236115353
_Toc236115353
Resource Method Definition

A resource method is defined to handle the desired WebDAV method by annotating it with one of the WebDAV method designators defined in the WebDAVMethod enum.
The supported WebDAV Http methods are as follows:

  • PROPFIND
  • PROPPATCH
  • MKCOL
  • COPY
  • MOVE
  • LOCK
  • UNLOCK.

Anchor
_Toc223239125
_Toc223239125
Anchor
_Toc236115354
_Toc236115354
Creating a Multistatus Response

In order to create a MULTISTATUS response to a PROPFIND request the user can use the WebDAVResponseBuilder class, or create the response manually.

Anchor
_Toc236115355
_Toc236115355
Using WebDAVResponseBuilder

In order to create a multistatus response using the WebDAVResponseBuilder class, call one of the propfind() methods.
The WebDAVResponseBuilder class also enables the user to provide the properties to include in the response by extending the PropertyProvider class, overriding the setPropertyValue() method and passing the property provider instance to the response builder propfind() method.

Anchor
_Toc236115356
_Toc236115356
WebDAVResponseBuilder Example

@Path("defects/{defect}")
public class DefectResource {
@WebDAVMethod.PROPFIND
@Consumes("application/xml")
@Produces(application/xml")
public Response propfindDefect(@PathParam("defect") String defected) {
SyndFeed feed = ...
return WebDAVResponseBuilder.propfind(feed);
}
}

The propfindDefect() method is associated with the PROPFIND WebDAV Http method using the @WebDAVMethod.PROPFIND annotation.
When the propfindDefect() method is invoked, an instance of a org.apache.wink.common.model.synd.SyndFeed is created and passed to the WebDAVResponseBuilder.propfind() method in order to create the actual response.

Anchor
_Toc236115357
_Toc236115357
Manual Creation

In order to create a Multistatus response manually, perform the following steps:

  1. Create a new org.apache.wink.webdav.model.Multistatus instance and set its fields according to the application logic.
  2. Create a new javax.ws.rs.core.Response instance, set the response code to MULTI_STATUS (207), and set its entity to be the Multistatus instance.
  3. Return the Response instance from the resource method


Anchor
_Ref229389760
_Ref229389760
Anchor
_Toc236115358
_Toc236115358
Handler Chains

The Wink runtime utilizes three Handler Chains for the complete processing of a request: Request chain, Response chain and Error chain.
A handler receives a MessageContext instance for accessing and manipulating the current request information and a HandlerChain instance for advancing the chain. It is the responsibility of the handler to pass control to the next handler on the chain by invoking the doChain() method on the HandlerChain instance.
A handler may call the doChain() method several times if needed, so handlers are required to consider the possibility they will be invoked more than once for the same request.
All handler related interfaces reside in the org.apache.wink.server.handlers package.
The implementation of separate chains provides the ability to move up and down one chain before moving on to the next chain. This is particularly useful for the implementation of the JAX-RS resource-method search algorithm that includes invoking sub-resource locators, and implementing the Continued Search mode.

Anchor
_Toc236115359
_Toc236115359
Handlers

There are two types of handlers:

  • System Handler
  • User Handler

System Handlers are the handlers that implement the core engine of the Wink runtime. The Wink runtime will not function correctly if any of the system handlers are removed from the chain.
User Handlers are the handlers that are provided by an application to customize a chains behavior and to add unique functionality to it. User handlers are not part of the core functionality of Wink.

Refer to chapter 2, section ‎2.3.1 for more details on User Handlers Customization.

Anchor
_Toc236115360
_Toc236115360
Message Context

The MessageContext allows the following:

  • Allows handlers to access and manipulate the current request information
  • Allows handlers to maintain a state by setting attributes on the message context, as the handlers themselves are singletons and therefore stateless
  • Allows handlers to pass information to other handlers on the chain

Anchor
_Ref229714686
_Ref229714686
Anchor
_Toc236115361
_Toc236115361
Request Handler Chain

The Request Handler Chain is responsible for processing a request according to the JAX-RS specification by accepting the request, searching for the resource method to invoke, de-serializing the request entity and finally for invoking the resource method. It is responsible for invoking sub-resource locators by moving up and down the chain as needed.
A Request handler is a class that implements the org.apache.wink.server.handlers.RequestHandler interface.

Anchor
_Toc236115362
_Toc236115362
System Request Handlers

The following is a list of system handlers comprising the request handler chain in the order that they appear in the chain.
Request Handlers

Anchor
_Toc231898889
_Toc231898889
Table 29: Request Handlers

Handler

Description

SearchResultHandler

Responsible for throwing the search result error if there was one during the search for the resource method

OptionsMethodHandler

Generates a response for an OPTIONS request in case that there is no resource method that is associated with OPTIONS, according to the JAX-RS spec

HeadMethodHandler

Handles a response for a HEAD request in case that there is no resource method that is associated with HEAD, according to the JAX-RS spec

FindRootResourceHandler

Locates the root resource that best matches the request

FindResourceMethodHandler

Locates the actual method to invoke that matches the request, invoking sub-resource locators as needed

CreateInvocationParametersHandler

Creates the parameters of the resource method to invoke and de-serializes the request entity using the appropriate MessageBodyReader

InvokeMethodHandler

Invokes the resource method

Anchor
_Ref229714610
_Ref229714610
Anchor
_Toc236115363
_Toc236115363
User Request Handlers

User request handlers are inserted before the InvokeMethodHandler handler.

Refer to chapter 2, section ‎2.3.1 for more details on User Handlers Customization.

Anchor
_Ref229714693
_Ref229714693
Anchor
_Toc236115364
_Toc236115364
Response Handler Chain

The Response Handler Chain is responsible for handling the object returned from invoking a resource method or sub-resource method according to the JAX-RS specification. It is responsible for determining the response status code, selecting the response media type and for serializing the response entity.
A Response handler is a class that implements the org.apache.wink.server.handlers.ResponseHandler interface.

Anchor
_Toc236115365
_Toc236115365
System Response Handlers

The following is a list of system handlers comprising the response handler chain in the order that they appear in the chain.
Response Handlers

Anchor
_Toc231898890
_Toc231898890
Table 30: Response Handlers

Handler

Description

PopulateResponseStatusHandler

Determines the response status code, according to the JAX-RS spec

PopulateResponseMediaTypeHandler

Determines the response media type, according to the JAX-RS spec


FlushResultHandler

Serializes the response entity using the appropriate MessageBodyWriter

HeadMethodHandler

Performs cleanup operations in case that there was no resource method that was associated with HEAD.

Anchor
_Ref229714620
_Ref229714620
Anchor
_Toc236115366
_Toc236115366
User Response Handlers

User response handlers are inserted before the FlushResultHandler handler. Wink initializes the user response handler chain with the CheckLocationHeaderHandler handler that verifies that the "Location" response header is present on a response when there is a status code that requires it, for example, status code: 201.

Refer to chapter 2, section ‎2.3.1 for more details on User Handlers Customization.

Anchor
_Ref229714700
_Ref229714700
Anchor
_Toc236115367
_Toc236115367
Error Handler Chain

The Error Handler Chain is responsible for handling all of the exceptions that are thrown during the invocation of the Request and Response handler chains, according to the JAX-RS specification for handling exceptions. It is responsible for determining the response status code, selecting the response media type and for serializing the response entity.
An Error handler is a class that implements the org.apache.wink.server.handlers.ResponseHandler interface.

Anchor
_Toc236115368
_Toc236115368
System Error Handlers

The following is a list of system handlers comprising the error handler chain in the order that they appear in the chain.
Error Handlers

Anchor
_Toc231898891
_Toc231898891
Table 31: Error Handlers

Handler

Description

PopulateErrorResponseHandler

Prepares the response entity from a thrown exception according to the JAX-RS specification

PopulateResponseStatusHandler

Determines the response status code according to the JAX-RS spec

PopulateResponseMediaTypeHandler

Determines the response media type, according to the JAX-RS spec

FlushResultHandler

Serializes the response entity using the appropriate MessageBodyWriter

Anchor
_Ref229714630
_Ref229714630
Anchor
_Toc236115369
_Toc236115369
User Error Handlers

User error handlers are inserted before the FlushResultHandler handler.

Refer to chapter 2, section ‎2.3.1 for more details on User Handlers Customization.




Anchor
_Toc236115370
_Toc236115370
Request Processing

The following details how the Wink runtime performs request processing:

  1. Create new instances of the three handler chains. The handlers themselves are singletons.
  2. Create a new instance of a MessageContext to pass between the handlers.
  3. Invoke the first handler on the Request chain.
  4. Once the request chain is complete, invoke the Response chain and pass it the MessageContext that was used in the Request chain.
  5. Make both chains and the MessageContext available for garbage collection.
  6. If at any time during the execution of a Request or Response chain an exception is thrown, catch the exception, wrap it in a new MessageContext instance and invoke the Error chain to produce an appropriate response.


Anchor
_Toc236115371
_Toc236115371
Wink Client

The following chapter describes the Wink Client and provides a detailed description of the Wink Client component and its functionality.

Anchor
OpenSearch-ClassOpenSearchRepresentation
OpenSearch-ClassOpenSearchRepresentation
Anchor
_Toc236115372
_Toc236115372
This chapter contains the following sections

  • Dependencies
  • Main Features
  • High Level Architecture Overview
  • Getting Started with the Wink Client
  • Configuration
  • Handlers

Anchor
_Toc231887192
_Toc231887192
Anchor
_Toc236115373
_Toc236115373
Wink Client Overview

The Wink Client is an easy-to-use, high level Java API for writing clients that consume HTTP-based RESTful Web Services. It utilizes JAX-RS concepts, encapsulates Rest standards and protocols and maps Rest principles concepts to Java classes, which facilitates the development of clients for any HTTP-based Rest Web Services.
The Wink Client also provides a Handlers mechanism that enables the manipulation of HTTP request/response messages.

Anchor
_Toc231887193
_Toc231887193

Anchor
_Toc236115374
_Toc236115374
Dependencies

Table 32: Wink Client Dependencies

3-rd Party

Java 1.5

Java 1.6

Comments

xercesImpl-2.6.2.jar

Required

Required

 

json-20080701.jar

Required

Required

 

jsr311-api.jar

Required

Required

 

wink-common-<VERSION>.jar

Required

Required

 

slf4j-simple-1.5.8.jar

Required

Required

May be replaced with another SLF4J bindings, e.g. application that uses log4j will replace this one by slf4j-log4j12-1.5.8.jar

slf4j-api-1.5.8.jar

Required

Required

 

jaxb-api-2.1.jar

Required

Not Required

 

jaxb-impl-2.1.4.jar

Required

Not Required

 

activation-1.1.jar

Required

Not Required

 

stax-api-1.0-2.jar

Required

Not Required

 


Anchor
_Toc236115375
_Toc236115375
Main Features

The Wink Clients main features are as follows:

  • Utilizes JAX-RS Providers for resource serialization and deserialization
  • Provides Java object models, such as Atom, APP, OpenSearch and Json along with providers to serialize and deserialize these models
  • Uses the JDK HttpUrlConnection as default underlying Http client
  • Provides integration with Apache Http Client 4.0
  • Allows for the easy replacement of the underlying Http transport
  • Provides a Handlers mechanism for manipulation of HTTP request and response messages.

Supports

  • Http proxy
  • SSL

Anchor
_Toc231887194
_Toc231887194
Anchor
_Toc236115376
_Toc236115376
High Level Architecture Overview

The following diagram illustrates the high-level architecture of the Wink Client.
Image Added

Anchor
_Toc217886230
_Toc217886230
Figure 3: Wink Client high-level view
The RestClient class is the Wink Client entry point and is responsible for holding different configuration options and the provider registry.
The RestClient is used to create instances of the Resource class. The Resource class represents a web resource associated with a specific URI and is used to perform uniform interface operations on the resource it represents.
Every method invocation goes through a user defined handlers chain that enables for manipulation of the request and response.
Anchor
_Toc231887195
_Toc231887195

Anchor
_Toc236115377
_Toc236115377
Getting Started with the Wink Client

The following section details the getting started examples that demonstrate how to write a simple client that consume RESTful Web Services with the Wink Client.

Anchor
_Toc231887196
_Toc231887196

Anchor
_Toc236115378
_Toc236115378
GET Request

// create the rest client instance 1 RestClient client = new RestClient();
// create the resource instance to interact with 2 Resource resource = client.resource("http://services.com/HelloWorld"); // perform a GET on the resource. The resource will be returned as plain text 3 String response = resource.accept("text/plain").get(String.class);

Explanation
The RestClient is the entry point for building a RESTful Web Service client. I order to start working with the Wink Client, a new instance of RestClient needs to be created, as the example shows in line 1 of the example. A new Resource is then created with the given URI, by calling the RestClient#resource() method as appears in line 2.
Finally, the Resource#get() method is invoked in order to issue an Http GET request as appears in line 3.
Once the Http response is returned, the client invokes the relevant provider to desterilizes the response in line 3.

Anchor
_Toc231887197
_Toc231887197

Anchor
_Toc236115379
_Toc236115379
POST Request


// create the rest client instance
1 RestClient client = new RestClient();

// create the resource instance to interact with
2 Resource resource = client.resource("http://services.co");

// issue the request
3 String response = resource.contentType("text/plain").accept("text/plain").post(String.class, "foo");

Anchor
Introspection_of_an_Atom_Service_Documen
Introspection_of_an_Atom_Service_Documen
Explanation
The POST Request example demonstrates how to issue a simple Http POST request that sends and receives resources as strings.
First, a new instance of a Resource is created through the RestClient. The Http POST request is then issued by specifying the request and response media types and the response entity type (String.class).

Anchor
_Toc231887198
_Toc231887198
Anchor
_Toc236115380
_Toc236115380
POST Atom Request


// create the rest client instance
1 RestClient client = new RestClient();

// create the resource instance to interact with
2 Resource resource = client.resource("http://services.co");

3 AtomEntry request = getAtomEntry();

// issue the request
4 AtomEntry response = resource.contentType("application/atom+xml").accept("application/atom+xml").post(AtomEntry.class, request);

Explanation
The Wink Client provides an object model for Atom (atom feed and atom entry), and supplies out-of-the-box providers that enable sending and receiving atom feeds and entries. The example demonstrates how to issue an Http POST request that sends and receives atom entries.

Anchor
_Toc231887199
_Toc231887199
Anchor
_Toc236115381
_Toc236115381
Using ClientResponse


// create the rest client instance
1 RestClient client = new RestClient();

// create the resource instance to interact with
2 Resource resource = client.resource("http://services.co");

// issue the request
3 ClientResponse response = resource.accept("text/plain").get();

// deserialize response
4 String responseAsString = response.getEntity(String.class);

Explanation
This example demonstrates how to use the ClientResponse object in order to deserialize the response entity. If the response entity type is not provided when invoking the Resource#get() method that appears in line 3, the response will be returned as the raw ClientResponse. In order to trigger the response deserialization mechanism, the ClientResponse#getEntity() method needs to be invoked as it appears in line 4 with the required response entity type.

Anchor
_Toc236115382
_Toc236115382
Anchor
_Toc231887200
_Toc231887200
Client Configuration

The RestClient configuration is performed by using the ClientConfig class. An instance of the configuration class is passed to the constructor of the RestClient when constructing a new RestClient.

Anchor
_Toc236115383
_Toc236115383
Important Note

Image Added

ApacheHttpClientConfig is used instead of default ClientConfig , if integration with Apache Http Client 4.0 is required.



The following options can be configured in the RestClient:

  • Custom providers via JAX-RS Application
  • Handler chain
  • Proxy host & port
  • Connect and read timeouts
  • Redirect


Anchor
_Toc236115384
_Toc236115384
Handler Configuration

1 ClientConfig config = new ClientConfig();

// Create new JAX-RS Application
2 config.handlers(new DummyHandler());
// create the rest client instance 3 RestClient client = new RestClient(config);
// create the resource instance to interact with 4 Resource resource = client.resource("http://services.com/HelloWorld"); // perform a GET on the resource
// the resource will be returned as plain text 5 String response = resource.accept("text/plain").get(String.class);

Explanation
This example demonstrates how to register a custom handler. First, a new instance of a ClientConfig is created as it appears in line 1. Then the new handler is added to the handlers chain by invoking the handlers() method on the ClientConfig instance as it appears in line 2. Finally, a new instance of a RestClient is created with this configuration as it appears in line 3.

Anchor
_Toc236115385
_Toc236115385
Apache Http Client Configuration

1 ClientConfig config = new new ApacheHttpClientConfig(new DefaultHttpClient()) ();

// Create new JAX-RS Application
2 config.handlers(new SimpleHandler());
// create the rest client instance 3 RestClient client = new RestClient(config);
// create the resource instance to interact with 4 Resource resource = client.resource("http://services.com/HelloWorld"); // perform a GET on the resource
// the resource will be returned as plain text 5 String response = resource.accept("text/plain").get(String.class);

Explanation
This example demonstrates how to use Apache Http Client 4.0 as Wink underlying Http client. By default, Wink Client uses HttpUrlConnection to perform to HTTP request execution. User, that wants to use Apache Http Client 4.0 instead, needs to create RestClient with ApacheHttpClientConfig, as it appears in line 3.

Anchor
_Toc236115386
_Toc236115386
Custom Provider Configuration

1 ClientConfig config = new ClientConfig();

// Create new JAX-RS Application
2 Application app = new Application() {
@Override
public Set<Class<?>> getClasses() {
HashSet<Class<?>> set = new HashSet<Class<?>>();
set.add(FooProvider.class);
return set;}};
3 conf.applications(app);
// create the rest client instance 4 RestClient client = new RestClient(config);
// create the resource instance to interact with 5 Resource resource = client.resource("http://services.com/HelloWorld"); // perform a GET on the resource. the resource will be returned as plain text 6 String response = resource.accept("text/plain").get(String.class);

Explanation
This example demonstrates how to register a custom entity provider. First, a new instance of ClientConfig is created as it appears in line 1. Then a new anonymous Application is instantiated and set on the ClientConfig as it appears in line 2 and 3. Finally, a new instance of a RestClient is created with this configuration as it appears in line 4.

Anchor
_Toc231887201
_Toc231887201

Anchor
_Toc236115387
_Toc236115387
Client Handlers

The Wink Client provides a Handlers mechanism that intercepts Http requests and responses. This mechanism is used to manipulate the request and response headers and allows the manipulation of the input and output entity streams by use of adapters.
An application develops custom handlers by implementing the ClientHandler interface. Custom handlers are registered via the ClientConfig configuration object. All registered handlers are invoked for every issued request, according to their registration order.

Anchor
_Toc231887202
_Toc231887202
Anchor
_Toc236115388
_Toc236115388
Custom Handlers

A custom handler implements the ClientHandler interface. The entry point of the handler is the handle() method. It receives the ClientRequest instance that encapsulates request information and allows for request data manipulation. It also receives the HandlerContext instance that is used to pass control to the next handler on the chain and to set input and output stream adapters.
Handlers are responsible for the flow control. It is handler's responsibility to call the next handler on the chain by invoking the doChain() method on the HandlerContext instance.

Anchor
_Toc236115389
_Toc236115389
Custom Handler Implementation

A typical implementation of the "handle" method appears as follows:


public class MyHandler implements ClientHandler {

public ClientResponse handle(ClientRequest rqs, HandlerContext ctx) {

// Do something before request is issued to the web resource
1 rqs.getHeaders().add("CUSTOM-REQUEST-HEADER", "Foo-Request");

2 ClientResponse resp = ctx.doChain(request);

// Do something before response is returned to the client
3 resp.getHeaders().add("CUSTOM-RESPONSE-HEADER", "Foo-Response");

4 return resp;
}
}

Explanation
This example illustrates a typical implementation of the custom handler. First, the handler adds a custom header to the request as it appears in line 1, then it calls the next handler on the chain by invoking the doChain() method (line 2), adds a custom header to a response as it appears in line 3 and finally returns the response as it appears in line 4.

Anchor
_Toc236115390
_Toc236115390
Input and Output Stream Adapters

The Wink Client provides the ability to manipulate raw Http input and output entity streams through the InputStreamAdapter and the OutputStreamAdapter interfaces. This is useful for modifying the input and output streams, regardless of the actual entity, for example when adding compression capabilities.
The adapt() method of the output stream adapter is called before the request headers are committed, in order to allow the adapter to manipulate them.
The adapt() method of the input stream adapter is called after the response status code and the headers are received in order to allow the adapter to behave accordingly.

Anchor
_Toc236115391
_Toc236115391
Stream Adapters Example

The following example demonstrates how to implement input and output adapters.
Gzip Handler


public class GzipHandler implements ClientHandler {
public ClientResponse handle(ClientRequest request,
HandlerContext context) {
request.getHeaders().add("Accept-Encoding", "gzip");
context.addInputStreamAdapter(new GzipInputAdapter());
context.addOutputStreamAdapter(new GzipOutputAdapter());
return context.doChain(request);
}}

Gzip Input Stream Adapter


class GzipInputAdapter implements InputStreamAdapter{
public InputStream adapt(InputStream is,
ClientResponse response) {
String header = response.getHeaders().getFirst("Content-Encoding");
if (header != null && header.equalsIgnoreCase("gzip")) {
return new GZIPInputStream(is);
}
return is;
}}

Gzip Output Stream Adapter


class GzipOutputAdapter implements OutputStreamAdapter {
public OutputStream adapt(OutputStream os,
ClientRequest request) {
request.getHeaders().add("Content-Encoding", "gzip");
return new GZIPOutputStream(os);
}}

Explanation
The Gzip handler creates instances of the GzipInputAdapter and the GzipOutputAdapter and adds them to the stream adapters of the current request by invoking the addInputStreamAdapter() and addOutputStreamAdapter() on the HandlerContext instance.

The Wink Developer Guide provides the developer with a rudimentary understanding of the Wink framework and the building blocks that comprise it.

Contents

...

1 Introduction to Apache Wink                   

...

5 Resources                   

...

9 Runtime Deligate

...

2 Apache Wink Building Blocks

...

6 Providers

...

10 Apache Wink Client

...

3 Getting Started with Apache Wink

...

7 Context

...

11 Migration from Version 1.6

...

4 Applications

...

8 Environment

...