/
Links.xml
executable file
·619 lines (577 loc) · 23.6 KB
/
Links.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
<!--
<!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 Jettison 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>3.6.0-SNAPSHOT</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<T></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>