52
RESTful WebServices in Java Chantal Taconet ASR/CSC5002 octobre 2015 Revision : 421

RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

Embed Size (px)

Citation preview

Page 1: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

# 1

RESTful WebServices in JavaChantal Taconet

ASR/CSC5002octobre 2015

Revision : 421

Page 2: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java

# 2

Outline

1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 Hyper Text Transfer Protocol: basics reminder. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .123 Representation of a Java object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184 Java RESTful service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .39

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 2/52

Page 3: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java

# 3

1 Introduction

1.1 What is REST . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41.2 REST: Representational State Transfer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61.3 REST resource . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71.4 Uniform interface: CRUD operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81.5 Are these operations sufficient to build an application ? . . . . . . . . . . . . . . . . . . . . . . . . . 91.6 Representation formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101.7 How to implement a RESTful service ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 3/52

Page 4: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 1 Introduction

# 4

1.1 What is REST

■ REST is a "URL friendly" way to retrieve distributed resources■ REST is built upon HTTP■ Examples of REST resources

♦ twitter API (https://dev.twitter.com/docs/api/1.1)

♦ google maps API(https://developers.google.com/maps/documentation/webservices/)

#Give a try on your webbrowser to discover where are those placeshttp://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=falsehttp://maps.googleapis.com/maps/api/geocode/json?latlng=48.858518, 2.294524&sensor=falsehttp://maps.googleapis.com/maps/api/geocode/json?latlng=48.625595, 2.443234&sensor=false

♦ youtube API (https://developers.google.com/youtube/v3/)♦ List of bike stations in Paris (create an account https://developer.jcdecaux.com)

#Give a try on your webbrowser to discover where are those placeshttps://api.jcdecaux.com/vls/v1/stations?contract=paris&apiKey=91f170cdabb4c3227116c3e871a63e8d3ad148ee

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 4/52

Page 5: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 1 Introduction

# 5

♦ Weatherhttp://api.openweathermap.org/data/2.5/weather?q=Paris

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 5/52

Page 6: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 1 Introduction

# 6

1.2 REST: Representational State Transfer

■ Architectural style defined by Fielding in 2000 [Fielding, 2000]■ Described by six identified constraints

♦ Client/server architecture: independance between the client and the server♦ Stateless: no client context on the server 7→ client requests include all the

necessary context♦ Cacheable: clients can cache responses♦ Layered system: clients and servers may be connected through intermediate

layers (e.g.. proxies)♦ Code on demand: the state may include code (e.g., javascript)♦ Uniform interface between clients and servers

■ World Wide Web conforms to the REST architectural style■ Applications that conform to this architectural style are called RESTful■ Main advantages: scalability, simplicity of interfaces

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 6/52

Page 7: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 1 Introduction

# 7

1.3 REST resource

■ Any (web) resource■ Identified by a global identifier (e.g. URI: Uniform Resource Identification)■ State of a resource may be transfered through a representation of this resource

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 7/52

Page 8: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 1 Introduction

# 8

1.4 Uniform interface: CRUD operations

■ Requests and responses are built around the transfer of representations ofresources

■ Requests are one of the four CRUD Operations:♦ Create 7→ POST http method♦ Read 7→ GET http method♦ Update 7→ PUT http method♦ Delete 7→ DELETE http method

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 8/52

Page 9: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 1 Introduction

# 9

1.5 Are these operations sufficient to build an application ?

Resource Create Read Update DeletePOST GET PUT DELETE

Collection Create entry List entries Replace collection Delete collection

Element / Get element Replace element Delete element

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 9/52

Page 10: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 1 Introduction

# 10

1.6 Representation formats

■ Resources are distinct from their possible representations■ Format of a representation (i.e. content type) is defined by an

Internet media type (previously known as a MIME type)■ Some common formats

♦ plain text: text/plain♦ html: text/html♦ xml: text/xml, application/xml♦ code: application/javascript♦ json: application/json♦ image: image/jpeg, image/png, image/*♦ video: video/mpeg

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 10/52

Page 11: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 1 Introduction

# 11

1.7 How to implement a RESTful service ?

■ Resource available through a web server■ Resource available through an application server (e.g. JEE)■ Resource maintained by light servers (e.g., home made http server with jersey

containers)■ Resources may be implemented with many languages

♦ PHP♦ C++♦ Java classes following the JAX-RS specification (several implementations, e.g.,

jersey)♦ . . .

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 11/52

Page 12: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java

# 12

2 Hyper Text Transfer Protocol: basics reminder

2.1 HTTP GET Request message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132.2 HTTP Response message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152.3 HTTP GET vs POST . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 12/52

Page 13: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 2 Hyper Text Transfer Protocol: basics reminder

# 13

2.1 HTTP GET Request message

GET /hello HTTP/1.1Accept: text/plain, text/html

%---empty line: end of header

■ Sent to a web server to access one of its web resource♦ Request message (message method, identification of the resource inside the

server, http version)▶ for example: GET /hello HTTP/1.1

♦ Request Headers▶ accepted content types (e.g. Accept: text/plain, text/html)▶ accepted charsets (e.g. Accept-Charset: utf-8)▶ cookie (e.g. Cookie: Version=1; Skin=new;)

♦ Request body (not necessary for a get)

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 13/52

Page 14: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 2 Hyper Text Transfer Protocol: basics reminder

# 14

■ Give it a try

telnet www-tp.tem-tsp.eu 80GET /~taconet/index.html HTTP 1.0

telnet www-inf.it-sudparis.euGET /COURS/CSC5002/Documents/HTML/index.htmlRETURN

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 14/52

Page 15: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 2 Hyper Text Transfer Protocol: basics reminder

# 15

2.2 HTTP Response messageHTTP/1.1 200 OK return codeDate: Mon, 11 Nov 2013 17:47:24 GMT header (begin)Server: Apachee/2.2.3 (Debian GNU/Linux)

Perl/v5.8.4 PHP/5.2.6Last-Modified: Wed, 28 Apr 2012 15:55:02 GMTContent-length: 327Content-type: text/html

empty line (end of header)<HTML> content... document HTML</HTML>

■ Return code♦ 100 - 199: Information message♦ 200 - 299: Success (e.g., 200 OK)♦ 300 - 399: Redirections♦ 400 - 499 : client-side errors (e.g., 404 Not Found, 403 Forbidden)♦ 500 - 599 : server-side errors (e.g., 500 Internal Server Error)

■ Header■ Resource content

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 15/52

Page 16: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 2 Hyper Text Transfer Protocol: basics reminder

# 16

2.3 HTTP GET vs POST

■ GET method, gets data, it has no input■ For input, use POST to create or PUT to update■ But, for HTML forms, which do have inputs, both GET and POST are used

Method GET POST

HTML <form method="GET" action="AfficheGET.php"> <form method="POST" action="AffichePOST.php">

URL http://www-inf/AfficheGET.php?Nom=Taconet&Prenom=Chantal http://www-inf/POSTForm.html

HTTP GET /AfficheGET.php?Nom=Taconet&Prenom=Chantal HTTP/1.1 POST AffichePOST.html HTTP/1.1Host: www-inf.it-sudparis.eu Host: www-inf.it-sudparis.eu

Content-Type: application/x-www-form-urlencodedContent-length: 27

Nom=Taconet&Prenom=Chantal

■ GET method easiest to test through WebBrowsers . . . but should not be used toupdate or create REST resources

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 16/52

Page 17: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 2 Hyper Text Transfer Protocol: basics reminder

# 17

■ Give it a trytelnet www-inf.it-sudparis.eu 80POST /COURS/CSC5002/Documents/HTML/AffichePOST.php HTTP/1.1Host: www-inf.it-sudparis.euContent-Type: application/x-www-form-urlencodedContent-length: 27

Nom=Taconet&Prenom=Chantal

telnet www-inf.it-sudparis.eu 80GET /COURS/CSC5002/Documents/HTML/AfficheGET.php?Nom=Taconet&Prenom=Chantal HTTP/1.1Host: www-inf.it-sudparis.eu

RETURN

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 17/52

Page 18: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java

# 18

3 Representation of a Java object

3.1 Java instance to State representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193.2 Serialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203.3 JAXB - Java Architecture for XML Binding. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .213.4 JAXB data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223.5 JAXB annotations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .243.6 JAXB annotations example file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .253.7 JAXB in action . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283.8 Handling specific marshalling/unmarshalling JAXB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313.9 Specific unmarshal example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323.10 Json (Javascript Object Notation) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333.11 Json in gson : a first example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343.12 Skier in json . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353.13 Gson custom marshalling/unmarshalling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 18/52

Page 19: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 3 Representation of a Java object

# 19

3.1 Java instance to State representation

■ Marshalling : Java instance to representation■ Unmarshalling : representation to Java instance■ Some possibilities

♦ Java serialization : binary representationclass MyClass implements Serializable {}

♦ JAXB : XML Document♦ Json : Javascript object representation

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 19/52

Page 20: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 3 Representation of a Java object

# 20

3.2 Serialization

Automatic serialization concerns♦ Loop: Object graph with cycles♦ Multiple references: Object graph with multiple reference paths to the same

object

Figure source: Javadoc DataSerialize

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 20/52

Page 21: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 3 Representation of a Java object

# 21

3.3 JAXB - Java Architecture for XML Binding

■ JAXB used to transfer complex java objects in XML structured strings♦ Marshalling: Convert a Java object into an XML document♦ Unmarshalling: Convert an XML document into a Java Object

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 21/52

Page 22: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 3 Representation of a Java object

# 22

3.4 JAXB data types

■ Java basic types have a representation in xs typesJava type xs type

java.lang.String xs:stringint xs:intdouble xs:doubleboolean xs:booleanjava.util.Date xs:dateTime

■ What about complex type ?

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 22/52

Page 23: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 3 Representation of a Java object

# 23

java Class

public class Person {private String name;private int age;private String gender;

...}

XSD schema<?xml version="1.0" ... ?><xs:schema version="1.0"...><xs:complexType name="person"><xs:sequence><xs:element name="age" type="xs:int"/><xs:element name="gender" type="xs:string" \

minOccurs="0"/><xs:element name="name" type="xs:string" \

minOccurs="0"/></xs:sequence>

</xs:complexType></xs:schema>

Java object

Person p=new Person("Bjoern Daehlie", 41, "Male");

XML document<?xml version="1.0" encoding="UTF-8" \

standalone="yes"?><person>

<name>Bjoern Daehlie</name><age>41</age><gender>Male</gender>

</person>

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 23/52

Page 24: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 3 Representation of a Java object

# 24

3.5 JAXB annotations

Annotation Description

@XmlRootElement(namespace ="namespace")

Root element for an XML tree

@XmlType(propOrder = "field2","field1",.. )

XSD Type, order of fields

@XmlAttribute Translated into an attribute (rather than anelement)

@XmlTransient Not translated into XML

@XmlAcces-sorType(XmlAccessType.FIELD)

all attributes translated (by default, onlypublic + getter/setter)

@XmlElementWrap-per(name="")

Add a wrapper XML element

@XmlElement(name ="newName")

Rename a field (element)

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 24/52

Page 25: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 3 Representation of a Java object

# 25

3.6 JAXB annotations example file

import javax.xml.bind.annotation.XmlRootElement;import javax.xml.bind.annotation.XmlElementWrapper;import javax.xml.bind.annotation.XmlElement;import javax.xml.bind.annotation.XmlAccessorType;import javax.xml.bind.annotation.XmlAccessType;import java.util.Collection;@XmlRootElement // XML Root@XmlAccessorType(XmlAccessType.FIELD) // All fields are translatedpublic class Skier extends Person {

private String nationalTeam;@XmlElementWrapper(name = "achievements") @XmlElement(name="achievement")private Collection<String> achievements;public Skier() { }public Skier (Person person, String nationalTeam, Collection<String> achievements) {

super(person);this.nationalTeam=nationalTeam;this.achievements=achievements;

}}

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 25/52

Page 26: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 3 Representation of a Java object

# 26

import javax.xml.bind.annotation.XmlType;import javax.xml.bind.annotation.XmlAccessorType;import javax.xml.bind.annotation.XmlAccessType;

// All the fields, even the private ones are in the XML@XmlAccessorType(XmlAccessType.FIELD)public class Person {

private String name;private int age;private String gender;

public Person() { }public Person(Person person) {this(person.name,person.age,person.gender);}public Person(String name, int age, String gender){

this.name=name;this.age=age;this.gender=gender;

}}

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 26/52

Page 27: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 3 Representation of a Java object

# 27

Example XML Document for a Skier object

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><skier>

<name>Bjoern Daehlie</name><age>41</age><gender>Male</gender><nationalTeam>Norway</nationalTeam><achievements>

<achievement>12 Olympic Medals</achievement><achievement>9 World Championships</achievement><achievement>Winningest Winter Olympian</achievement><achievement>Greatest Nordic Skier</achievement>

</achievements></skier>

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 27/52

Page 28: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 3 Representation of a Java object

# 28

3.7 JAXB in action

JDK commands

■ Java Class to XSD : schemagen■ XSD to java class : xjc

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 28/52

Page 29: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 3 Representation of a Java object

# 29

■ Using the JAXB API to marshall and unmarshallclass Marshal {

private static final String file_name = "bd.mar";

private Skier createSkier() {Person bjoern = new Person("Bjoern Daehlie", 41, "Male");List<String> listMajorAchievements = new ArrayList<String>();

listMajorAchievements.add("12 Olympic Medals");listMajorAchievements.add("9 World Championships");listMajorAchievements.add("Winningest Winter Olympian");listMajorAchievements.add("Greatest Nordic Skier");return new Skier(bjoern, "Norway", listMajorAchievements);

}

public static void main(String[ ] args) throws JAXBException,IOException {new Marshal().run_example();

}

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 29/52

Page 30: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 3 Representation of a Java object

# 30

private void run_example() throws JAXBException,IOException {JAXBContext ctx = JAXBContext.newInstance(Skier.class);Marshaller m = ctx.createMarshaller();m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);// Marshal a Skier object: 1st to stdout, 2nd to fileSkier skier = createSkier();m.marshal(skier, System.out);FileOutputStream out = new FileOutputStream(file_name);m.marshal(skier, out);out.close();// Unmarshal as proof of conceptUnmarshaller u = ctx.createUnmarshaller();Skier clone = (Skier) u.unmarshal(new File(file_name));System.out.println();m.marshal(clone, System.out);

}}

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 30/52

Page 31: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 3 Representation of a Java object

# 31

3.8 Handling specific marshalling/unmarshalling JAXB

■ @XmlTransient attribute not marshalled■ beforeMarshal and afterMarshal : callbacks called (when defined) before and after

marshalling■ beforeUnmarshal and afterUnmarshal : callbacks called (when defined) before and

after unmarshalling

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 31/52

Page 32: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 3 Representation of a Java object

# 32

3.9 Specific unmarshal example

@XmlRootElementclass Department {

@XmlAttribute String name;@XmlElement(name="employee") List<Employee> employees;

}class Employee {

@XmlTransient Department department; // parent pointer not marshalled@XmlAttribute String name;

public void afterUnmarshal(Unmarshaller u, Object parent) { // after JAXB unmarshallthis.department = (Department)parent;

}}

<department name="accounting"><employee name="Joe Chin" /><employee name="Adam Smith" />

</department>

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 32/52

Page 33: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 3 Representation of a Java object

# 33

3.10 Json (Javascript Object Notation)

■ “JSON is a lightweight data-interchange format. It is easy for humans to readand write. It is easy for machines to parse and generate.” (json.org)

■ Example in Json, object with an array membermyObject = {"first": "John","last": "Doe","age": 39,"sex": "M","salary": 70000,"registered": true,"interests": [ "Reading", "Mountain Biking", "Hacking" ]

}

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 33/52

Page 34: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 3 Representation of a Java object

# 34

3.11 Json in gson : a first example

■ Many libraries to serialize/deserialize Json strings, google json is one of them■ Example :

class BagOfPrimitives {private int attr1 = 1;private String attr2 = "abc";private transient int attr3 = 3; // not marshalledBagOfPrimitives() {}

}

//(Serialization)BagOfPrimitives obj = new BagOfPrimitives();Gson gson = new Gson();String json = gson.toJson(obj);//==> json is {"attr1":1,"attr2":"abc"}

//(Deserialization)BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);//==> obj2 is just like obj

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 34/52

Page 35: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 3 Representation of a Java object

# 35

3.12 Skier in jsonpublic class Person {

private String name;private int age;private String gender;public Person() { }public Person(Person person) {this(person.name, person.age, person.gender);}public Person(String name, int age, String gender){

this.name=name; this.age=age; this.gender=gender;}

}

public class Skier extends Person {private String nationalTeam;private Collection<String> achievements;public Skier() { }public Skier (Person person, String nationalTeam, Collection<String> achievements) {

super(person); this.nationalTeam=nationalTeam; this.achievements=achievements;}

}

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 35/52

Page 36: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 3 Representation of a Java object

# 36

private void run_example() {try {

Gson gson = new Gson();// Marshal a Skier object: 1st to stdout, 2nd to fileSkier skier = createSkier();String json = gson.toJson(skier);System.out.println("The initial skier: "+json);PrintWriter out = new PrintWriter(file_name);out.println(json);out.close();// Unmarshal as proof of conceptSkier clone = (Skier) gson.fromJson(json, Skier.class);json = gson.toJson(clone);System.out.println("His clone: "+json);

}catch(IOException e) { System.err.println(e);}}

1 {"nationalTeam":"Norway","achievements":["12 Olympic Medals","9 World \Championships","Winningest Winter Olympian","Greatest Nordic Skier"],"name":"Bjoern \Daehlie","age":41,"gender":"Male"}

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 36/52

Page 37: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 3 Representation of a Java object

# 37

3.13 Gson custom marshalling/unmarshalling

■ For specific purpose, one can customs serializerspublic class ProductJsonSerializer implements JsonSerializer<Product> {

@Overridepublic JsonElement serialize(final Product product, final Type typeOfSrc, final \

JsonSerializationContext context) {final JsonObject json = new JsonObject();json.addProperty("i", product.getId());json.addProperty("n", product.getName());json.addProperty("p", product.getPrice());final JsonArray categoriesArray = new JsonArray();json.add("c", categoriesArray);for (final Category category : product.getCategories()) {

categoriesArray.add(context.serialize(category));}return json;

}}

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 37/52

Page 38: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 3 Representation of a Java object

# 38

■ For specific purpose, one can custom deserializerspublic class ProductJsonDeserializer implements JsonDeserializer<Product> {

@Overridepublic Product deserialize(final JsonElement json, final Type typeOfT, final \

JsonDeserializationContext context) throws JsonParseException {Product product = new Product();// Parsing will be done here.return product;

}}

■ Register serializer/deserializerGsonBuilder gson = new GsonBuilder();gson.registerTypeAdapter(Product.class, new ProductJsonSerializer());gson.registerTypeAdapter(Product.class, new ProductJsonDeserializer());

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 38/52

Page 39: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java

# 39

4 Java RESTful service

4.1 REST JAX-RS architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404.2 @path annotation and resource URI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414.3 Input or output representation format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424.4 JAXB representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444.5 Path and template parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454.6 Hello World in REST . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464.7 Java Client example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474.8 Light server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484.9 Parameter annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494.10 REST Synthesis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504.11 Some links to be studied . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 39/52

Page 40: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 4 Java RESTful service

# 40

4.1 REST JAX-RS architectureHTTP

LightweightWeb server

JAX−RS

JAX−RS

Client Server

JEE container

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 40/52

Page 41: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 4 Java RESTful service

# 41

4.2 @path annotation and resource URI■ Each resource is identified by a URI defined by

♦ The server URLhttp://localhost:9999/MyServer/

♦ The root resource class▶ @path annotation for a RestFul java class@Path("/hello") // http://localhost:9999/MyServer/hellopublic class Hello {}

♦ Additionnally, a method may have a subidentification@Path("replace") //http://localhost:9999/MyServer/hello/replace

public String replace(...) {}

method SubPath CRUD http msg parameters presentation

replace replace update TBD TBD TBD

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 41/52

Page 42: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 4 Java RESTful service

# 42

4.3 Input or output representation format

■ Defined with @consumes for input (POST and PUT) and @produces for output(GET)

■ Defined for a class and/or overloaded on a method■ Client requirement and server representation offers should match

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 42/52

Page 43: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 4 Java RESTful service

# 43

♦ Client requirement defined in the GET requestGET /hello HTTP/1.1Host: localhostAccept: text/html, text/plain

♦ Service offeree@GET@Produces("text/html")public String readHTML() {

return "<html><body>"+msg + "</body></html>";}

method SubPath CRUD http msg parameters presentation

readHTML / read GET / HTML♦ Matching representation defined in the response header

HTTP/1.1 200 OKContent-Type: text/html

<html><body>Hello</body></html>

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 43/52

Page 44: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 4 Java RESTful service

# 44

4.4 JAXB representation

■ @produces("application/xml")■ Return type is a class annotated @XmlRootElement or @XmlType

@GET@Path("searchskier")//http://localhost:9999/MyServer/skiers/searchskier?name=xxx@produces("application/xml")public Skier getSkier(@QueryParam("name") String name){

...Skier foundSkier= lookup(name);return foundSkier; // marshalled in XML with JAXB

}

method SubPath CRUD http msg parameters presentation

getSkier searchskier?name= read GET name XML

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 44/52

Page 45: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 4 Java RESTful service

# 45

4.5 Path and template parameters

■ Parameters included in the URL♦ Requested URL

http://localhost:9999/MyServer/calc/add?a=3&b=4

♦ Method definition@Path("/calc")public class CalcRest {

@GET@Path("/add")@Produces(MediaType.TEXT_PLAIN)public String addPlainText(@QueryParam("a") double a, @QueryParam("b") double b) {

return (a + b) + "";}

method SubPath CRUD http msg parameters presentation

addPlainText add?a=&b= read GET a,b TEXT

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 45/52

Page 46: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 4 Java RESTful service

# 46

4.6 Hello World in REST@Path("/hello") public class HelloRest {

private static String msg = "Hello world";@GET @Produces("text/plain") public String read() {return msg + "\n"; }@GET @Produces("text/html") public String readHTML() {return "<html><body>"+msg +"</body></html>"; }@GET @Produces("text/plain") @Path("/{extra}") // http:..../hello/xxxpublic String personalized_read(@PathParam("extra") String cus) { return HelloRest.msg + ": " + cus + "\n";}@GET @Produces("text/plain") @Path("replace") // http:..../hello/replace?newmsg=xxxpublic String replaceAndRead(@DefaultValue("") @QueryParam("newmsg") String new_msg ) {

System.out.println("replaceAndRead new_msg="+new_msg);HelloRest.msg = new_msg;return HelloRest.msg + "\n";

}@PUT @Consumes("text/plain") @Path("replace") public void replace(String new_msg) {

System.out.println("replace new_msg="+new_msg);HelloRest.msg = new_msg;

}@DELETE @Path("/delete") public void delete() {

HelloRest.msg = "";System.out.println( "Message deleted.\n");

}}

method SubPath CRUD http msg parameters presentation

read / read GET / TEXTreadHTML / read GET / HTMLpersonalized_read {extra} read GET extra TEXTreplaceAndRead replace?newmsg= read :-( GET newmsg TEXTreplace replace update PUT newmsg TEXTdelete delete delete DELETE / /

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 46/52

Page 47: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 4 Java RESTful service

# 47

4.7 Java Client example

public class HelloRestClient {static final String REST_URI = "http://localhost:9999/MyServer/";

public static void main(String[] args) {Client client = Client.create(new DefaultClientConfig());URI uri=UriBuilder.fromUri(REST_URI).build();WebResource service = client.resource(uri);// Get plain textSystem.out.println(uri+"hello GET TEXT_PLAIN");System.out.println("hello output as plain text : "+service.path("hello").accept(MediaType.TEXT_PLAIN).get(String.class));System.out.println("---------------------------------------------------");System.out.println(uri+"hello/replace PUT coucou TEXT_PLAIN");service.path("hello").path("replace").put("coucou");System.out.println("---------------------------------------------------");System.out.println(uri+"hello/delete DELETE TEXT_PLAIN");service.path("hello").path("delete").delete();System.out.println("---------------------------------------------------");

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 47/52

Page 48: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 4 Java RESTful service

# 48

4.8 Light server

public class Publisher {

static final String BASE_URI = "http://localhost:9999/MyServer/";

public static void main(String[] args) {try {

HttpServer server = HttpServerFactory.create(BASE_URI);// The root resources in the java path will be automatically detectedserver.start();System.out.println("Browse the available operations with this URL : "+BASE_URI+"application.wadl");System.out.println("Press Enter to stop the server. ");System.in.read();System.out.println("Server stopped.");server.stop(0);

} catch (IllegalArgumentException e) {e.printStackTrace();

} catch (IOException e) {e.printStackTrace();

}}

}

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 48/52

Page 49: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 4 Java RESTful service

# 49

4.9 Parameter annotations

■ @pathparam: in the path (hello/coucou)■ @queryparam: in the URL (hello?newmsg=coucou)■ @FormParam: input from a form through a POST■ @HeaderParam: in the http header■ @CookieParam: in a cookie

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 49/52

Page 50: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 4 Java RESTful service

# 50

4.10 REST Synthesis

■ Easy to write and easy to test RESTful WebServices♦ As a consequence, a high percentage of deployed web services are RESTful

services

■ No service interface language (except wadl): Interface of services have to be welldocumented

■ Not so natural to write java REST clients (one has to construct the method call)

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 50/52

Page 51: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java 4 Java RESTful service

# 51

4.11 Some links to be studied

■ Webbrowser REST Client plugin, URL(chrome://restclient/content/restclient.html)

■ REST with glassfish URL(http://www.andygibson.net/blog/article/simple-restful-web-services-with-glassfish/)

■ json 2 java URL (http://www.jsonschema2pojo.org/)■ retrofit annotations to write REST client URL

(http://square.github.io/retrofit/)■ swagger language-agnostic interface to REST APIs URL

(http://swagger.io/getting-started/)

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 51/52

Page 52: RESTful WebServices in Java - taconet/LibreService/Cassiopee/rest... · Any (web) resource ... 1.4 Uniform interface: CRUD operations Requests and responses are built around the transfer

RESTful WebServices in Java

# 52

References

[Burke, 2010] Burke, B. (2010). RESTful Java. O’Reilly.

[Fielding, 2000] Fielding, R. T. (2000). REST Architectural Styles and the Design of Network-based SoftwareArchitectures. Doctoral dissertation, University of California, Irvine.

[Kalin, 2010] Kalin, M. (2010). Java Web Services, Up and Running. O’Reilly.

Télécom SudParis — INF — octobre 2015 — ASR/CSC5002 52/52