<!--
<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.4//EN"
                         "http://www.docbook.org/xml/4.4/docbookx.dtd">
 -->
<chapter id="LinkHeader">
	<title>Linking resources</title>
	<para>
		There are two mechanisms available in RESTEasy to link a resource to another, and to link resources to
		operations: the Link HTTP header, and Atom links inside the resource representations.
	</para>
	<section>
		<title>Link Headers</title>
		<para>
		RESTEasy has both client and server side support for the <ulink url="http://tools.ietf.org/html/draft-nottingham-http-link-header-06">Link header specification</ulink>.
		See the javadocs for org.jboss.resteasy.spi.LinkHeader, org.jboss.resteasy.spi.Link, and org.jboss.resteasy.client.ClientResponse.
		</para>
		<para>
		The main advantage of Link headers over Atom links in the resource is that those links are available
		without parsing the entity body.
		</para>
	</section>
	<section>
		<title>Atom links in the resource representations</title>
		<para>
		RESTEasy allows you to inject <ulink url="http://tools.ietf.org/html/rfc4287#section-4.2.7">Atom links</ulink> directly inside the entity objects you are sending to the
		client, via auto-discovery.
		</para>
		<warning>
			<para>This is only available when using the Jackson2 or JAXB providers (for JSON and XML).</para>
		</warning>
		<para>
		The main advantage over Link headers is that you can have any number of Atom links directly over the
		concerned resources, for any number of resources in the response. For example, you can have Atom links
		for the root response entity, and also for each of its children entities.
		</para>
		<section>
			<title>Configuration</title>
			<para>
				There is no configuration required to be able to inject Atom links in your resource
				representation, you just have to have this maven artifact in your path:
			</para>
			<table>
				<caption>Maven artifact for Atom link injection</caption>
				<thead>
					<tr>
						<th>Group</th>
						<th>Artifact</th>
						<th>Version</th>
					</tr>
				</thead>
				<tbody>
					<tr>
						<td>org.jboss.resteasy</td>
						<td>resteasy-links</td>
						<td>4.7.9.Final</td>
					</tr>
				</tbody>
			</table>
		</section>
		<section>
			<title>Your first links injected</title>
			<para>
			You need three things in order to tell RESTEasy to inject Atom links in your entities:
			</para>
			<itemizedlist>
				<listitem>
					<para>
					Annotate the JAX-RS method with <classname>@AddLinks</classname> to indicate that you want
					Atom links injected in your response entity.
					</para>
				</listitem>
				<listitem>
					<para>
					Add <classname>RESTServiceDiscovery</classname> fields to the resource classes where you
					want Atom links injected.
					</para>
				</listitem>
				<listitem>
					<para>
					Annotate the JAX-RS methods you want Atom links for with <classname>@LinkResource</classname>,
					so that RESTEasy knows which links to create for which resources.
					</para>
				</listitem>
			</itemizedlist>
			<para>
			The following example illustrates how you would declare everything in order to get the Atom links
			injected in your book store:
			</para>
			<programlisting language="Java"><![CDATA[@Path("/")
@Consumes({"application/xml", "application/json"})
@Produces({"application/xml", "application/json"})
public interface BookStore {

	@AddLinks
	@LinkResource(value = Book.class)
	@GET
	@Path("books")
	public Collection<Book> getBooks();

	@LinkResource
	@POST
	@Path("books")
	public void addBook(Book book);

	@AddLinks
	@LinkResource
	@GET
	@Path("book/{id}")
	public Book getBook(@PathParam("id") String id);

	@LinkResource
	@PUT
	@Path("book/{id}")
	public void updateBook(@PathParam("id") String id, Book book);

	@LinkResource(value = Book.class)
	@DELETE
	@Path("book/{id}")
	public void deleteBook(@PathParam("id") String id);
}]]></programlisting>
			<para>
			And this is the definition of the Book resource:
			</para>
			<programlisting language="Java"><![CDATA[@Mapped(namespaceMap = @XmlNsMap(jsonName = "atom", namespace = "http://www.w3.org/2005/Atom"))
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class Book {
	@XmlAttribute
	private String author;

	@XmlID
	@XmlAttribute
	private String title;

	@XmlElementRef
	private RESTServiceDiscovery rest;
}]]></programlisting>
			<para>
			If you do a GET /order/foo you will then get this XML representation:
			</para>
			<programlisting language="XML"><![CDATA[<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<book xmlns:atom="http://www.w3.org/2005/Atom" title="foo" author="bar">
 <atom:link href="http://localhost:8081/books" rel="list"/>
 <atom:link href="http://localhost:8081/books" rel="add"/>
 <atom:link href="http://localhost:8081/book/foo" rel="self"/>
 <atom:link href="http://localhost:8081/book/foo" rel="update"/>
 <atom:link href="http://localhost:8081/book/foo" rel="remove"/>
</book>]]></programlisting>
			<para>
			And in JSON format:
			</para>
			<programlisting language="JavaScript"><![CDATA[{
 "book":
 {
  "@title":"foo",
  "@author":"bar",
  "atom.link":
   [
    {"@href":"http://localhost:8081/books","@rel":"list"},
    {"@href":"http://localhost:8081/books","@rel":"add"},
    {"@href":"http://localhost:8081/book/foo","@rel":"self"},
    {"@href":"http://localhost:8081/book/foo","@rel":"update"},
    {"@href":"http://localhost:8081/book/foo","@rel":"remove"}
   ]
 }
}]]></programlisting>
		</section>
		<section>
			<title>Customising how the Atom links are serialised</title>
			<para>
			Because the <classname>RESTServiceDiscovery</classname> is in fact a JAXB type which inherits from
			<classname>List</classname> you are free to annotate it as you want to customise the JAXB serialisation,
			or just rely on the default with <classname>@XmlElementRef</classname>.
			</para>
		</section>
		<section>
			<title>Specifying which JAX-RS methods are tied to which resources</title>
			<para>
			This is all done by annotating the methods with the <classname>@LinkResource</classname> annotation.
			It supports the following optional parameters:
			</para>
			<table>
				<caption><para><classname>@LinkResource</classname> parameters</para></caption>
				<thead>
					<tr>
						<th>Parameter</th>
						<th>Type</th>
						<th>Function</th>
						<th>Default</th>
					</tr>
				</thead>
				<tbody>
					<tr>
						<td>value</td>
						<td><classname>Class</classname></td>
						<td>Declares an Atom link for the given type of resources.</td>
						<td>Defaults to the entity body type (non-annotated parameter), or the method's return type.
						This default does not work with <classname>Response</classname> or <classname>Collection</classname>
						types, they need to be explicitly specified.</td>
					</tr>
					<tr>
						<td>rel</td>
						<td><classname>String</classname></td>
						<td>The Atom link relation</td>
						<td>
							<variablelist>
								<varlistentry>
									<term>list</term>
									<listitem><para>For <classname>GET</classname> methods returning a <classname>Collection</classname></para></listitem>
								</varlistentry>
								<varlistentry>
									<term>self</term>
									<listitem><para>For <classname>GET</classname> methods returning a non-<classname>Collection</classname></para></listitem>
								</varlistentry>
								<varlistentry>
									<term>remove</term>
									<listitem><para>For <classname>DELETE</classname> methods</para></listitem>
								</varlistentry>
								<varlistentry>
									<term>update</term>
									<listitem><para>For <classname>PUT</classname> methods</para></listitem>
								</varlistentry>
								<varlistentry>
									<term>add</term>
									<listitem><para>For <classname>POST</classname> methods</para></listitem>
								</varlistentry>
							</variablelist>
						</td>
					</tr>
				</tbody>
			</table>
			<para>
			You can add several <classname>@LinkResource</classname> annotations on a single method by enclosing
			them in	a <classname>@LinkResources</classname> annotation. This way you can add links to the same
			method on several resource types. For example the <constant>/order/foo/comments</constant> operation
			can belongs on the <classname>Order</classname> resource with the <constant>comments</constant>
			relation, and on the <classname>Comment</classname> resource with the <constant>list</constant>
			relation.
			</para>
		</section>
		<section>
			<title>Specifying path parameter values for URI templates</title>
			<para>
			When RESTEasy adds links to your resources it needs to insert the right values in the URI template.
			This is done either automatically by guessing the list of values from the entity, or by specifying
			the values in the <classname>@LinkResource</classname> <varname>pathParameters</varname> parameter.
			</para>
			<section>
				<title>Loading URI template values from the entity</title>
				<para>
					URI template values are extracted from the entity from fields or Java Bean properties
					annotated with <classname>@ResourceID</classname>, JAXB's <classname>@XmlID</classname> or
					JPA's <classname>@Id</classname>. If there are more than one URI template
					value to find in a given entity, you can annotate your entity with <classname>@ResourceIDs</classname>
					to list the names of fields or properties that make up this entity's Id. If there are other
					URI template values required from a parent entity, we try to find that parent in a field or
					Java Bean property
					annotated with <classname>@ParentResource</classname>. The list of URI template
					values extracted up every <classname>@ParentResource</classname> is then reversed and used
					as the list of values for the URI template.
				</para>
				<para>For example, let's consider the previous Book example, and a list of comments:</para>
			<programlisting language="Java"><![CDATA[@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class Comment {
	@ParentResource
	private Book book;

	@XmlElement
	private String author;

	@XmlID
	@XmlAttribute
	private String id;

	@XmlElementRef
	private RESTServiceDiscovery rest;
}]]></programlisting>
				<para>
				Given the previous book store service augmented with comments:
				</para>
			<programlisting language="Java"><![CDATA[@Path("/")
@Consumes({"application/xml", "application/json"})
@Produces({"application/xml", "application/json"})
public interface BookStore {

	@AddLinks
	@LinkResources({
		@LinkResource(value = Book.class, rel = "comments"),
		@LinkResource(value = Comment.class)
	})
	@GET
	@Path("book/{id}/comments")
	public Collection<Comment> getComments(@PathParam("id") String bookId);

	@AddLinks
	@LinkResource
	@GET
	@Path("book/{id}/comment/{cid}")
	public Comment getComment(@PathParam("id") String bookId, @PathParam("cid") String commentId);

	@LinkResource
	@POST
	@Path("book/{id}/comments")
	public void addComment(@PathParam("id") String bookId, Comment comment);

	@LinkResource
	@PUT
	@Path("book/{id}/comment/{cid}")
	public void updateComment(@PathParam("id") String bookId, @PathParam("cid") String commentId, Comment comment);

	@LinkResource(Comment.class)
	@DELETE
	@Path("book/{id}/comment/{cid}")
	public void deleteComment(@PathParam("id") String bookId, @PathParam("cid") String commentId);

}]]></programlisting>
				<para>
				Whenever we need to make links for a <classname>Book</classname> entity, we look up the ID
				in the <classname>Book</classname>'s <classname>@XmlID</classname> property. Whenever we make links
				for <classname>Comment</classname> entities, we have a list of values taken from the <classname>Comment</classname>'s
				<classname>@XmlID</classname> and its <classname>@ParentResource</classname>: the <classname>Book</classname> and
				its <classname>@XmlID</classname>.
				</para>
				<para>
				For a <classname>Comment</classname> with <varname>id</varname> <constant>"1"</constant> on a <classname>Book</classname>
				with <varname>title</varname> <constant>"foo"</constant> we will therefore get a list of URI
				template values of <constant>{"foo", "1"}</constant>, to be replaced in the URI template, thus
				obtaining either <constant>"/book/foo/comments"</constant> or <constant>"/book/foo/comment/1"</constant>.
				</para>
			</section>
			<section>
				<title>Specifying path parameters manually</title>
				<para>
				If you do not want to annotate your entities with resource ID annotations (<classname>@ResourceID</classname>,
				<classname>@ResourceIDs</classname>, <classname>@XmlID</classname> or <classname>@Id</classname>) and
				<classname>@ParentResource</classname>, you can also specify the URI template values inside the
				<classname>@LinkResource</classname> annotation, using Unified Expression Language expressions:
				</para>
				<table>
					<caption><para><classname>@LinkResource</classname> URI template parameter</para></caption>
					<thead>
						<tr>
							<th>Parameter</th>
							<th>Type</th>
							<th>Function</th>
							<th>Default</th>
						</tr>
					</thead>
					<tbody>
						<tr>
							<td>pathParameters</td>
							<td><classname>String[]</classname></td>
							<td>Declares a list of UEL expressions to obtain the URI template values.</td>
							<td>Defaults to using <classname>@ResourceID</classname>, <classname>@ResourceIDs</classname>,
							<classname>@XmlID</classname> or <classname>@Id</classname> and <classname>@ParentResource</classname>
							annotations to extract the values from the model.</td>
						</tr>
					</tbody>
				</table>
				<para>
				The UEL expressions are evaluated in the context of the entity, which means that any unqualified
				variable will be taken as a property for the entity itself, with the special variable
				<varname>this</varname> bound to the entity we're generating links for.
				</para>
				<para>
				The previous example of <classname>Comment</classname> service could be declared as such:
				</para>
				<programlisting language="Java"><![CDATA[@Path("/")
@Consumes({"application/xml", "application/json"})
@Produces({"application/xml", "application/json"})
public interface BookStore {

	@AddLinks
	@LinkResources({
		@LinkResource(value = Book.class, rel = "comments", pathParameters = "${title}"),
		@LinkResource(value = Comment.class, pathParameters = {"${book.title}", "${id}"})
	})
	@GET
	@Path("book/{id}/comments")
	public Collection<Comment> getComments(@PathParam("id") String bookId);

	@AddLinks
	@LinkResource(pathParameters = {"${book.title}", "${id}"})
	@GET
	@Path("book/{id}/comment/{cid}")
	public Comment getComment(@PathParam("id") String bookId, @PathParam("cid") String commentId);

	@LinkResource(pathParameters = {"${book.title}", "${id}"})
	@POST
	@Path("book/{id}/comments")
	public void addComment(@PathParam("id") String bookId, Comment comment);

	@LinkResource(pathParameters = {"${book.title}", "${id}"})
	@PUT
	@Path("book/{id}/comment/{cid}")
	public void updateComment(@PathParam("id") String bookId, @PathParam("cid") String commentId, Comment comment);

	@LinkResource(Comment.class, pathParameters = {"${book.title}", "${id}"})
	@DELETE
	@Path("book/{id}/comment/{cid}")
	public void deleteComment(@PathParam("id") String bookId, @PathParam("cid") String commentId);

}]]></programlisting>
			</section>
		</section>
		<section>
			<title>Securing entities</title>
			<para>
			You can restrict which links are injected in the resource based on security restrictions for the client,
			so that if the current client doesn't have permission to delete a resource he will not be presented
			with the <constant>"delete"</constant> link relation.
			</para>
			<para>
			Security restrictions can either be specified on the <classname>@LinkResource</classname> annotation,
			or using RESTEasy and EJB's security annotation <classname>@RolesAllowed</classname> on the JAX-RS
			method.
			</para>
			<table>
				<caption><para><classname>@LinkResource</classname> security restrictions</para></caption>
				<thead>
					<tr>
						<th>Parameter</th>
						<th>Type</th>
						<th>Function</th>
						<th>Default</th>
					</tr>
				</thead>
				<tbody>
					<tr>
						<td>constraint</td>
						<td><classname>String</classname></td>
						<td>A UEL expression which must evaluate to true to inject this method's link in the
						response entity.</td>
						<td>Defaults to using <classname>@RolesAllowed</classname> from the JAX-RS method.</td>
					</tr>
				</tbody>
			</table>
		</section>
		<section>
			<title>Extending the UEL context</title>
			<para>
			We've seen that both the URI template values and the security constraints of <classname>@LinkResource</classname>
			use UEL to evaluate expressions, and we provide a basic UEL context with access only to the entity
			we're injecting links in, and nothing more.
			</para>
			<para>
			If you want to add more variables or functions in this
			context, you can by adding a <classname>@LinkELProvider</classname> annotation on the JAX-RS method,
			its class, or its package. This annotation's value should point to a class that implements the
			<classname>ELProvider</classname> interface, which wraps the default <classname>ELContext</classname>
			in order to add any missing functions.
			</para>
			<para>
			For example, if you want to support the Seam annotation <varname>s:hasPermission(target, permission)</varname>
			in your security constraints, you can add a <classname>package-info.java</classname> file like this:
			</para>
			<programlisting language="Java"><![CDATA[@LinkELProvider(SeamELProvider.class)
package org.jboss.resteasy.links.test;

import org.jboss.resteasy.links.*;]]></programlisting>
			<para>
			With the following provider implementation:
			</para>
			<programlisting language="Java"><![CDATA[package org.jboss.resteasy.links.test;

import javax.el.ELContext;
import javax.el.ELResolver;
import javax.el.FunctionMapper;
import javax.el.VariableMapper;

import org.jboss.seam.el.SeamFunctionMapper;

import org.jboss.resteasy.links.ELProvider;

public class SeamELProvider implements ELProvider {

	public ELContext getContext(final ELContext ctx) {
		return new ELContext() {

			private SeamFunctionMapper functionMapper;

			@Override
			public ELResolver getELResolver() {
				return ctx.getELResolver();
			}

			@Override
			public FunctionMapper getFunctionMapper() {
				if (functionMapper == null)
					functionMapper = new SeamFunctionMapper(ctx
							.getFunctionMapper());
				return functionMapper;
			}

			@Override
			public VariableMapper getVariableMapper() {
				return ctx.getVariableMapper();
			}
		};
	}

}]]></programlisting>
			<para>
			And then use it as such:
			</para>
				<programlisting language="Java"><![CDATA[@Path("/")
@Consumes({"application/xml", "application/json"})
@Produces({"application/xml", "application/json"})
public interface BookStore {

	@AddLinks
	@LinkResources({
		@LinkResource(value = Book.class, rel = "comments", constraint = "${s:hasPermission(this, 'add-comment')}"),
		@LinkResource(value = Comment.class, constraint = "${s:hasPermission(this, 'insert')}")
	})
	@GET
	@Path("book/{id}/comments")
	public Collection<Comment> getComments(@PathParam("id") String bookId);

	@AddLinks
	@LinkResource(constraint = "${s:hasPermission(this, 'read')}")
	@GET
	@Path("book/{id}/comment/{cid}")
	public Comment getComment(@PathParam("id") String bookId, @PathParam("cid") String commentId);

	@LinkResource(constraint = "${s:hasPermission(this, 'insert')}")
	@POST
	@Path("book/{id}/comments")
	public void addComment(@PathParam("id") String bookId, Comment comment);

	@LinkResource(constraint = "${s:hasPermission(this, 'update')}")
	@PUT
	@Path("book/{id}/comment/{cid}")
	public void updateComment(@PathParam("id") String bookId, @PathParam("cid") String commentId, Comment comment);

	@LinkResource(Comment.class, constraint = "${s:hasPermission(this, 'delete')}")
	@DELETE
	@Path("book/{id}/comment/{cid}")
	public void deleteComment(@PathParam("id") String bookId, @PathParam("cid") String commentId);

}]]></programlisting>
		</section>
		<section>
			<title>Resource facades</title>
			<para>
			Sometimes it is useful to add resources which are just containers or layers on other resources. For
			example if you want to represent a collection of <classname>Comment</classname> with a start index
			and a certain number of entries, in order to implement paging. Such a collection is not really an
			entity in your model, but it should obtain the <constant>"add"</constant> and <constant>"list"</constant>
			link relations for the <constant>Comment</constant> entity.
			</para>
			<para>
			This is possible using resource facades. A resource facade is a resource which implements the
			<classname>ResourceFacade&lt;T&gt;</classname> interface for the type <varname>T</varname>, and as
			such, should receive all links for that type.
			</para>
			<para>
			Since in most cases the instance of the <varname>T</varname> type is not directly available in the
			resource facade, we need another way to extract its URI template values, and this is done by calling
			the resource facade's <methodname>pathParameters()</methodname> method to obtain a map of URI template
			values by name. This map will be used to fill in the URI template values for any link generated for
			<varname>T</varname>, if there are enough values in the map.
			</para>
			<para>
			Here is an example of such a resource facade for a collection of <classname>Comment</classname>s:
			</para>
				<programlisting language="Java"><![CDATA[@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class ScrollableCollection implements ResourceFacade<Comment> {

	private String bookId;
	@XmlAttribute
	private int start;
	@XmlAttribute
	private int totalRecords;
	@XmlElement
	private List<Comment> comments = new ArrayList<Comment>();
	@XmlElementRef
	private RESTServiceDiscovery rest;

	public Class<Comment> facadeFor() {
		return Comment.class;
	}

	public Map<String, ? extends Object> pathParameters() {
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("id", bookId);
		return map;
	}
}]]></programlisting>
			<para>
			This will produce such an XML collection:
			</para>
<programlisting language="XML"><![CDATA[<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<collection xmlns:atom="http://www.w3.org/2005/Atom" totalRecords="2" start="0">
 <atom.link href="http://localhost:8081/book/foo/comments" rel="add"/>
 <atom.link href="http://localhost:8081/book/foo/comments" rel="list"/>
 <comment xmlid="0">
  <text>great book</text>
  <atom.link href="http://localhost:8081/book/foo/comment/0" rel="self"/>
  <atom.link href="http://localhost:8081/book/foo/comment/0" rel="update"/>
  <atom.link href="http://localhost:8081/book/foo/comment/0" rel="remove"/>
  <atom.link href="http://localhost:8081/book/foo/comments" rel="add"/>
  <atom.link href="http://localhost:8081/book/foo/comments" rel="list"/>
 </comment>
 <comment xmlid="1">
  <text>terrible book</text>
  <atom.link href="http://localhost:8081/book/foo/comment/1" rel="self"/>
  <atom.link href="http://localhost:8081/book/foo/comment/1" rel="update"/>
  <atom.link href="http://localhost:8081/book/foo/comment/1" rel="remove"/>
  <atom.link href="http://localhost:8081/book/foo/comments" rel="add"/>
  <atom.link href="http://localhost:8081/book/foo/comments" rel="list"/>
 </comment>
</collection>
]]></programlisting>
		</section>
	</section>
</chapter>
