Web Services REST Avec Java
Web Services REST Avec Java
Creative Commons
Contrat Paternité
Partage des Conditions Initiales à l'Identique
2.0 France
[Link]
2
Plan du cours
Généralités JAX-RS
Premier service Web JAX-RS
Développement Serveur
Chemin de ressource @Path
Déploiement
Développement Client
Outils
3
Déroulement du cours
Pédagogie du cours
Illustration avec de nombreux exemples qui sont disponibles à
l’adresse [Link]
Des bulles d’aide tout au long du cours
Survol des principaux concepts en évitant une présentation exhaustive
Logiciels utilisés
Navigateur Web, Eclipse 3.6, Tomcat 6, Maven 3
Exemples « Mavenisés » indépendant de l’environnement de dév.
Pré-requis
Ceci est une astuce
Schema XML, JAXB, Introduction Services Web
Djug 4
Ressources
Articles
[Link]/technetwork/articles/javase/[Link]
[Link]/display/Jersey/Overview+of+JAX-RS+1.0+Features
[Link]/nonav/releases/1.1/[Link]
[Link]/wiki/JAX-RS
[Link]/Java/Article/42873
[Link]/en/jsr/summary?id=311
[Link]/articles/REST/[Link]
[Link]/articles/rest-introduction
[Link]/javaee/6/tutorial/doc/[Link]
[Link]/app/docs/doc/820-4867/820-4867 5
Ressources (suite)
Articles (suite)
[Link]/nonav/documentation/latest/[Link]
[Link]/developer/technicalArticles/WebServices/jax-rs/[Link]
[Link]/documentation/[Link]
[Link]/documentation/[Link]
[Link]/documentation/[Link]
Présentations
[Link]/caroljmcdonald/td09restcarol
[Link]/linkedin/building-consistent-restful-apis-in-a-highperformance-environment
[Link]/jugtoulouse/rest-nicolas-zozol-jug-toulouse-20100615
[Link]/learning/javaoneonline/2008/pdf/[Link]
Cours
[Link]/nonav/documentation/latest/[Link]
6
Ressources : Bibliothèque
RESTful Java
Auteur : Bill Burke
Éditeur : Oreilly
Edition : Nov. 2009 - 320 pages - ISBN : 0596158041
7
Généralités - Développement de Services Web REST
Développement de
Description du Service Web permettant
clients dans des
de générer la partie cliente
langages différents
WADL
.NET
Servlet JAX-RS
PHP HTTP
Approche Bottom / Up
JAVA Serveur
Web Conteneur Java
Classes JAVA annotées
implémentant le
Différentes APIs service web
possibles pour la gestion
du client en Java
Utilisation du Service
Web par envoie /
Couche Cliente Couche Serveur
réception de contenu
HTTP 12
Généralités JAX-RS : Développement
Java annotées
Lecture de la ressource
HelloWorld via une requête HTTP
@Path("/hello")
de type GET
public class HelloWorldResource {
@GET
@Produces("text/plain")
public String getHelloWorld() {
return "Hello World from text/plain";
}
}
Le type MIME de la réponse est
de type text/plain
[Link] du projet
HelloWorldRestWebService
15
Le Premier Service Web JAX-RS
16
Le Premier Service Web JAX-RS
WEB-INF [Link]
[Link]
classes [Link]
[Link]
[Link]
lib
[Link]
…
17
Le Premier Service Web JAX-RS
Description de l’exemple
Une bibliothèque dispose de livres
Client WEB
20
Protocole HTTP : requête
Différentes informations
concernant le navigateur, Le corps de la requête uniquement si la méthode
l’utilisateur, ... est de type POST. Sont fournis les valeurs des
paramètres envoyées par un formulaire
21
Protocole HTTP : en-têtes de requête
... 22
Protocole HTTP : type de méthodes
HTTP/<Version><Status><Commentaire Status>
Content-Type:<Type MIME du contenu>
[<Champ d’en-tête>:<Valeur>]
... La ligne blanche
Ligne blanche est obligatoire
Document
24
Protocole HTTP : en-têtes de réponse
ETag = …
Location = …
…
25
Protocole HTTP : statuts des réponses
Une classe Java doit être annotée par @path pour qu’elle
puisse être traitée par des requêtes HTTP
L’annotation @path sur une classe définit des ressources
appelées racines (Root Resource Class)
La valeur donnée à @path correspond à une expression URI
relative au contexte de l’application Web
[Link]
/books/borrowed @GET
@Path("/borrowed")
public String getBorrowedBooks() {
...
Serveur Web }
}
@GET
@Path("{id}")
public String getBookById(@PathParam("id") int id) {
return "Java For Life " + id;
}
@GET
@Path("name-{name}-editor-{editor}")
public String getBookByNameAndEditor(@PathParam("name") String name,
@PathParam("editor") String editor)
return "Starcraft 2 for Dummies (Name:" + name + " - Editor:" + editor + ")";
}
}
/books/name-sc2-editor-oreilly
[Link] du projet
LibraryRestWebService
30
@Path : Template Parameters
@Path("/books")
public class BookResource {
...
@GET
@Path("{id : .+}/editor")
public String getBookEditorById(@PathParam("id") String id) {
return "OReilly";
}
@GET
@Path("original/{id : .+}")
public String getOriginalBookById(@PathParam("id") String id) {
return "Java For Life 2";
}
}
/books/original/123/path1/path2
[Link] du projet
LibraryRestWebService
31
@Path : Sub-resource locator
@Path("/books")
public class BookResource {
...
@Path("specific")
public SpecificBookResource getSpecificBook() {
return new SpecificBookResource();
}
}
35
@GET, @POST, @PUT, @DELETE : Méthodes HTTP
[Link] du projet
LibraryRestWebService 36
Paramètres de requêtes
[Link] du projet
LibraryRestWebService 39
Paramètres de requêtes : @QueryParam
Exemple
/books/queryparameters?name=harry&isbn=1-111111-11&isExtended=true
@Path("/books")
public class BookResource { Injection de valeurs par défaut
... si les valeurs des paramètres
@GET ne sont pas fournies
@Path("queryparameters")
public String getQueryParameterBook(
@DefaultValue("all") @QueryParam("name") String name,
@DefaultValue("?-???????-?") @QueryParam("isbn") String isbn,
@DefaultValue("false") @QueryParam("isExtended") boolean isExtented) {
[Link] du projet
LibraryRestWebService 40
Paramètres de requêtes : @FormParam
return name;
}
}
[Link] du projet
LibraryRestWebService 41
Paramètres de requêtes : @HeaderParam
Exemple
@Path("/books")
public class BookResource {
...
@GET
@Path("headerparameters")
public String getHeaderParameterBook(
@DefaultValue("all") @HeaderParam("name") String name,
@DefaultValue("?-???????-?") @HeaderParam("isbn") String isbn,
@DefaultValue("false") @HeaderParam("isExtended") boolean isExtented) {
return name + " " + isbn + " " + isExtented;
}
}
[Link] du projet
LibraryRestWebService 42
Paramètres de requêtes : @Context
contexte de l’application
45
Paramètres de requêtes : @Context / HttpHeaders
@Path("/books")
public class BookResource {
...
@GET
@Path("informationfromhttpheaders/{name}")
public String getInformationFromHttpHeaders(@Context HttpHeaders httpheaders) {
Map<String, Cookie> cookies = [Link]();
Set<String> currentKeySet = [Link]();
for (String currentCookie : currentKeySet) {
[Link](currentCookie);
}
[Link] du projet
LibraryRestWebService 47
Représentations : @Consumes, @Produces
Réponse
HTTP/1.1 200 OK
Date: Wed, 05 January 2010 [Link] GMT
Server: Jetty(6.1.14)
Content-Type: text/html
49
Représentations : @Consumes, @Produces
50
Gestion du contenu
@Path("inputstream")
@GET
@Produces(MediaType.TEXT_XML)
public InputStream getContentBooksWithInputStream() throws FileNotFoundException {
return new FileInputStream("c:\\[Link]");
}
}
[Link] du projet
LibraryContentRestWebService 52
Gestion du contenu : File
@Path("/contentbooks")
public class BookResource {
@Path("file")
@PUT
public void updateContentBooksWithFile(File file) throws IOException {
byte[] bytes = readFromStream(new FileInputStream(file));
String input = new String(bytes);
[Link](input);
} JAX-RS crée un fichier temporaire
@Path("file")
à partir du fichier donné
@GET
@Produces(MediaType.TEXT_XML)
public File getContentBooksWithFile() {
File file = new File("c:\\[Link]");
return file;
}
...
}
[Link] du projet
LibraryContentRestWebService
53
Gestion du contenu : String
@Path("/contentbooks")
public class BookResource {
@Path("string")
@PUT
public void updateContentBooksWithString(String current) throws IOException {
[Link](current);
}
@Path("string")
@GET
@Produces(MediaType.TEXT_XML)
public String getContentBooksWithString() {
return "<?xml version=\"1.0\"?>" + "<details>Ce livre est une introduction sur la vie" +
"</details>";
}
...
}
[Link] du projet
LibraryContentRestWebService
54
Gestion du contenu : types personnalisés
57
Gestion du contenu : types personnalisés
@Path("jaxbxml")
@GET
@Produces("application/xml")
public Book getContentBooksWithJAXBXML() {
Book current = new Book();
[Link]("123-456-789");
Le type MIME retourné par le
[Link]("Harry Toper"); service ce qui permet au client de
connaître le format à traiter
return current;
}
...
}
[Link] du projet
LibraryContentRestWebService 58
Gestion du contenu : types personnalisés
@Path("/contentbooks")
public class BookResource {
Utilisation d’un objet JAXBElement pour
... envelopper le type Book
@Path("jaxbxml")
@Consumes("application/xml")
@POST
public void updateContentBooksWithJAXBElementXML(JAXBElement<Book> currentJAXBElemnt) {
Book current = [Link]();
59
Gestion du contenu : statuts des réponses
@Path("/contentbooks")
public class BookResource { Statut à OK
...
@Path("response")
@GET
public Response getBooks() {
return Response
.status([Link]) Trois paramètres
.header("param1", "Bonjour")
.header("param2", "Hello")
.header("server", "keulkeul")
.entity("Ceci est le message du coprs de la réponse")
.build();
}
}
Un contenu String
dans le coprs
Finalisation en appelant
la méthode build()
63
Response
@Path("/contentbooks")
public class BookResource {
...
@Path("response")
@GET
public Response getBooks() {
return Response
.serverError()
.build();
}
}
[Link] du projet
LibraryContentRestWebService
64
Response
@Path("/contentbooks")
public class BookResource {
...
@Consumes("application/xml")
@POST
@Path("response")
public Response createBooks(Book newBook, @Context UriInfo uri) {
URI absolutePath = [Link]();
return [Link](absolutePath).build();
}
}
65
UriBuilder
… 67
UriBuilder
[Link] du projet
LibraryContentRestWebService
@Path("/contentbooks")
public class BookResource {
...
@Consumes("application/xml")
@POST
@Path("uribuilder1")
public Response createBooksFromURI(Book newBook, @Context UriInfo uri) {
URI absolutePath = uri
.getAbsolutePathBuilder() Création d’une URI
.queryParam("param1", [Link]()) à partir du chemin
.path([Link]())
.build();
fourni de la requête
return [Link](absolutePath).build();
}
} Ajouter un paramètre
68
UriBuilder
[Link] du projet
LibraryContentRestWebService
@Path("/contentbooks")
public class BookResource {
...
@Consumes("application/xml")
@POST
@Path("uribuilder2")
public Response createURIBooks(Book newBook, @Context UriInfo uri) {
URI build = UriBuilder
.fromUri("[Link]
.path("path1")
.path("path2")
[Link] du projet
.build(); LibraryContentRestWebService
return [Link](build).build();
}
69
Déploiement
[Link] du projet
HelloWorldRestWebService
71
Déploiement
[Link] du projet
LibraryRestWebService 72
Web Service Rest avec Java6
Usages
Fournir des Services Web à une application type client lourd
Pour les tests unitaires, fournir des Mock de Services Web
@GET
@Produces("text/plain")
public String getHelloWorld() {
return "Hello World from text/plain";
}
}
[Link] du projet
HelloWorldRestWebServiceFromJavaSE
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> classes = new HashSet<Class<?>>();
[Link]([Link]);
return classes;
}
}
[Link] du projet
HelloWorldRestWebServiceFromJavaSE
74
Web Service Rest avec Java6
@After
public void tearDown() {
if (st != null) [Link]();
Création d’une instance de la
} sous classe Application
@Test
public void testDoGetWithApplication() throws ... {
Application app = new HelloWorldRestWebServiceApplication(); Création d’un point d’entrée pour
accéder aux classes ressources
RuntimeDelegate rd = [Link]();
Adapter a = [Link](app, [Link]);
st = [Link]([Link]("[Link] a);
[Link] du projet
HelloWorldRestWebServiceFromJavaSE
75
Développement Client
Initialisation du client
Client c = [Link]();
Configuration du client
[Link]().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true);
Ou
[Link](true);
Ou
ClientConfig cc = new DefaultClientConfig();
[Link]().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true);
Client c = [Link](cc);
@Test
public void testGetDetailsBookId() {
ClientConfig config = new DefaultClientConfig();
Client client = [Link](config);
WebResource service = [Link](getBaseURI());
// Get TEXT for application
[Link]("Ce livre est une introduction sur la vie",
[Link]("books").path("details").path("12")
.accept(MediaType.TEXT_PLAIN).get([Link]));
// Get XML for application
[Link]("<?xml version=\"1.0\"?><details>Ce livre est une introduction sur la
vie</details>",
[Link]("books").path("details").path("12")
.accept(MediaType.TEXT_XML).get([Link]));
// Get HTML for application
[Link]("<html><title>Details</title><body><h1>Ce livre est une introduction sur la
vie</h1></body></html>",
[Link]("books").path("details").path("12")
.accept(MediaType.TEXT_HTML).get([Link]));
}
[Link] du projet
LibraryRestWebService
80
Développement Client
@Test
public void testUpdateContentBooksWithJAXBXMLService() throws IOException {
ClientConfig config = new DefaultClientConfig();
Client client = [Link](config);
WebResource service = [Link](getBaseURI());
[Link](current);
}
[Link] du projet
LibraryContentRestWebService
81
Développement Client
@Test
public void testGetBooksService() {
ClientConfig config = new DefaultClientConfig();
Client client = [Link](config);
WebResource service = [Link](getBaseURI());
[Link] du projet
LibraryContentRestWebService
82
Outils : Environnements de développement / Outils
MessageBodyReader et MessageBodyWriter
…
84