Upload
duongkhanh
View
221
Download
0
Embed Size (px)
RESTful Web Services mit JAX-RS
Markus Boese & Mark Bonnekessel
9. Dezember 2014
Motivation REST JAX-RS Praktikum
Inhaltsverzeichnis
1 Motivation
2 REST
3 JAX-RS
4 Praktikum
Motivation REST JAX-RS Praktikum
Was ist JAX-RS?
• Java API for RESTful Web Services• GET http://api.example.com/students
[{
matrikelnummer: 1,name: "Hugo"
},{
matrikelnummer: 2,name: "Frank"
},{
matrikelnummer: 3,name: "Martin"
}]
Markus Boese, Mark Bonnekessel JAX-RS 3
Motivation REST JAX-RS Praktikum
Einfaches Beispiel
@Path("students")public class StudentsRessource {
@GET@Produces(MediaType.APPLICATION_JSON)public List<Student> getStudents() {
List<Student> students = new ArrayList<Student>();
students.add(new Student(1,"Hugo"));students.add(new Student(2,"Frank"));students.add(new Student(3,"Martin"));
return students;}
}
Markus Boese, Mark Bonnekessel JAX-RS 4
Motivation REST JAX-RS Praktikum
REST – Representational State Transfer
• REST 6= HTTP• Architekturstil fur verteilte Hypermedia-Systeme• RESTful Webservice• Gehort folgender Aufruf zu einer RESTful-API?
POSThttp://api.example.com/student/update?id=1&name=Max
Markus Boese, Mark Bonnekessel JAX-RS 5
Motivation REST JAX-RS Praktikum
REST – Prinzipien
• Einteilung in Ressourcen• Einheitliche Operationen• Verschiedene Reprasentationen• Hypermedia as the Engine of Application State
(HATEOAS)• Stateless
Abbildung: Verknupfung von REST-Ressourcen (Eigene Darstellung).
Markus Boese, Mark Bonnekessel JAX-RS 6
Motivation REST JAX-RS Praktikum
REST-Beispiel: HTTP
• Identifikation uber URIs:http://www.example.com/students
http://www.example.com/students?category=science
http://www.example.com/students/12345678
• Einheitlicher Operationen-Satz = HTTP-Methoden• Safe – Informationen empfangen, keine Seiteneffekte• Idempotent• HTTP-Statuscode
Markus Boese, Mark Bonnekessel JAX-RS 7
Motivation REST JAX-RS Praktikum
HTTP-Methoden
Method Safe IdempotentOPTIONS X XGET X XHEAD X XPOSTDELETE XPUT X...
• Ressource ...• Anzeigen• Erstellen• Andern• Loschen
Markus Boese, Mark Bonnekessel JAX-RS 8
Motivation REST JAX-RS Praktikum
REST – So nicht!
Abbildung: Twitters “REST” API(https://dev.twitter.com/rest/reference/post/statuses/destroy/%3Aid)
Markus Boese, Mark Bonnekessel JAX-RS 9
Motivation REST JAX-RS Praktikum
JAX-RS
• Standard - JCP JSR 339 v2.0https://jcp.org/en/jsr/detail?id=339
• Jeresy 2.13 - JAX-RS Implementierung + Magic• https://github.com/jersey/jersey• Feb 2012 - Dec 2014 ca. 2.076 commits
Markus Boese, Mark Bonnekessel JAX-RS 10
Motivation REST JAX-RS Praktikum
Annotation-Feuerwerk
• 28 Annotations• @GET, @POST, @DELETE, @PUT, @OPTIONS• @Path• @Produces, @Consumes• @Provider
Markus Boese, Mark Bonnekessel JAX-RS 11
Motivation REST JAX-RS Praktikum
Jersey API - @GET I
@Path("students")public class StudentsRessource {
@GETpublic String getStudents() {
return "Homer Simpson, Gordon Freeman, LukeSkywalker"
}
@Postpublic String addStudent(...) {...
}
Markus Boese, Mark Bonnekessel JAX-RS 12
Motivation REST JAX-RS Praktikum
Jersey API - @GET II
@Path("students")public class StudentsRessource {
@GETpublic Response getStudents() {
return Response.ok().entity("Homer Simpson,...").build()
}
@Postpublic String addStudent(...) {...
}
Markus Boese, Mark Bonnekessel JAX-RS 13
Motivation REST JAX-RS Praktikum
Jersey API - @GET III
@Path("students")public class StudentsRessource {
@GET@Produces(MediaType.APPLICATION_JSON)public Response getStudents() {
String json = <Erzeuge Json z. B. GSON oderJackson>
return Response.ok().entity(json).build()}
@Postpublic String addStudent(...) {...
}
Markus Boese, Mark Bonnekessel JAX-RS 14
Motivation REST JAX-RS Praktikum
Jersey API
• jersey-media-moxy• Jackson• JAXB
Markus Boese, Mark Bonnekessel JAX-RS 15
Motivation REST JAX-RS Praktikum
Jersey API - Bean config
@XmlRootElement@XmlAccessorType(XmlAccessType.FIELD)public class Student {
private String name;
private int matrikelnummer;
public Student(){}
/* Getter / Setter */}
Markus Boese, Mark Bonnekessel JAX-RS 16
Motivation REST JAX-RS Praktikum
Jersey API - @Produces I
@Path("students")public class StudentsRessource {
@GET@Produces({MediaType.APPLICATION_JSON,
MediaType.APPLICATION_XML})public Response getStudents() {
Student student = new Student("Max Musterman",12345);
return Response.ok().entity(student).build()}
@Postpublic String addStudent(...) {...
}
Markus Boese, Mark Bonnekessel JAX-RS 17
Motivation REST JAX-RS Praktikum
Jersey API - @Produces II
@Path("students")public class StudentsRessource {
@GET@Produces({MediaType.APPLICATION_JSON,
MediaType.APPLICATION_XML})public List<Student> getStudents() {
List<Student> students = new ArrayList<Student>();
students.add(new Student(1,"Hugo"));students.add(new Student(2,"Frank"));students.add(new Student(3,"Martin"));
return students;}
}
Markus Boese, Mark Bonnekessel JAX-RS 18
Motivation REST JAX-RS Praktikum
Grizzly Intern
Abbildung: https://grizzly.java.net/
Markus Boese, Mark Bonnekessel JAX-RS 19
Motivation REST JAX-RS Praktikum
Fehlerbehandlung
@Providerpublic class ExceptionMapper implements
ExceptionMapper<Throwable>{
@Overridepublic Response toResponse(Throwable throwable){
// Log ExceptionHttpError error = new HttpError(500,
throwable.getMessage());return Response.status(error.getStatus()).
type(MediaType.APPLICATION_JSON).entity(error).build();
}}
Markus Boese, Mark Bonnekessel JAX-RS 20
Motivation REST JAX-RS Praktikum
Jersey API - exception handling
@Path("students")public class StudentsRessource {
@GET@Produces({MediaType.APPLICATION_JSON,
MediaType.APPLICATION_XML})public List<Student> getStudents() {
try {List<Student> students =
StudentDao.ladeStudenten(...);...return students;
} catch (Exception e) {throw new
WebApplicationException(Response.(...).build());}
}}
Markus Boese, Mark Bonnekessel JAX-RS 21
Motivation REST JAX-RS Praktikum
Jersey API
@Path("students")public class StudentsRessource {
@GET@Produces({MediaType.APPLICATION_JSON,
MediaType.APPLICATION_XML})public List<Student> getStudents() {
...}
@GET@Produces({MediaType.APPLICATION_JSON,
MediaType.APPLICATION_XML})public Student getStudents(String name) {
...}
}
Markus Boese, Mark Bonnekessel JAX-RS 22
Motivation REST JAX-RS Praktikum
Validierung
• Regulare Ausdrucke innerhalb einiger Annotations• Third Party Frameworks: Hibernate Validator - JSR 303
• Definition von weiteren Annotations• jersey-bean-validation
Markus Boese, Mark Bonnekessel JAX-RS 23
Motivation REST JAX-RS Praktikum
Jersey API
@Path("Sub-Path/{variable: Regex Pattern}")
@Path("1/{name: [A-Za-zaous_]+}")<domain>/students/1/homer_simpson
@Path("{name: [A-Za-zaous_]+}")<domain>/students/homer_simpson
@Path("{id: [0-9]+}")<domain>/students/1234
Markus Boese, Mark Bonnekessel JAX-RS 24
Motivation REST JAX-RS Praktikum
Jersey API
@Path("students")public class StudentsRessource {
@GET....
@GET@Path("{name: [A-Za-zaous]+}")@Produces({MediaType.APPLICATION_JSON,
MediaType.APPLICATION_XML})public Student getStudents(String name) {
...}
}
Markus Boese, Mark Bonnekessel JAX-RS 25
Motivation REST JAX-RS Praktikum
Jersey API
@Path("students")public class StudentsRessource {
@GET....
@GET@Path("1")@Produces({MediaType.APPLICATION_JSON,
MediaType.APPLICATION_XML})public Student getStudents(@QueryParam("name") String
name) {...
}}
Markus Boese, Mark Bonnekessel JAX-RS 26
Motivation REST JAX-RS Praktikum
Jersey API - @Consumes
@Path("students")public class StudentsRessource {
@PUT@Path("{id}")@Consumes(MediaType.APPLICATION_JSON)@Produces(MediaType.APPLICATION_JSON)public Response updateArticle(
@PathParam("id") String id,Article article) {...
}}
Markus Boese, Mark Bonnekessel JAX-RS 27
Motivation REST JAX-RS Praktikum
Cross-Origin Resource Sharing (CORS)
Nicht verletzt wenn Protokoll, Host und Port gleich sind.
Markus Boese, Mark Bonnekessel JAX-RS 28
Motivation REST JAX-RS Praktikum
CORS - Server
Access-Control-Allow-Origin:http://localhost:8181
Access-Control-Allow-Headers:origin, content-type, accept, authorization
Access-Control-Allow-Credentials:true
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS, HEAD
Access-Control-Max-Age:120
Markus Boese, Mark Bonnekessel JAX-RS 29
Motivation REST JAX-RS Praktikum
CORS - Client
Origin:http://localhost:8181
Markus Boese, Mark Bonnekessel JAX-RS 30
Motivation REST JAX-RS Praktikum
Client-API
Client client = ClientBuilder.newClient();target = client.target("http://www.localhost:8080/");
Response response = target.path("students").get();
Assert.assertEquals(Response.Status.OK.getStatusCode(),response.getStatus());
Markus Boese, Mark Bonnekessel JAX-RS 31
Motivation REST JAX-RS Praktikum
MediaType
Client client = ClientBuilder.newClient();target = client.target("http://www.localhost:8080/");
Response response = target.path("students").request(MediaType.APPLICATION_JSON).get();
Assert.assertEquals(MediaType.APPLICATION_JSON,response.getMediaType().toString());
Markus Boese, Mark Bonnekessel JAX-RS 32
Motivation REST JAX-RS Praktikum
JSON
Client client = ClientBuilder.newClient();target = client.target("http://www.localhost:8080/");
Response response = target.path("student").path("123").request(MediaType.APPLICATION_JSON).get();
Student student = response.readEntity(Student.class);
Markus Boese, Mark Bonnekessel JAX-RS 33
Motivation REST JAX-RS Praktikum
Liste von JSON-Elementen
Client client = ClientBuilder.newClient();target = client.target("http://www.localhost:8080/");
Response response = target.path("students").request(MediaType.APPLICATION_JSON).get();
List<Article> students = response.readEntity(newGenericType<List<Article>>() {});
Assert.assertEquals(10, students.size());
Markus Boese, Mark Bonnekessel JAX-RS 34
Motivation REST JAX-RS Praktikum
PUT
Student student = new Student();
response = target.path("students").path("123").request(MediaType.APPLICATION_JSON).put(Entity.entity(student,
MediaType.APPLICATION_JSON));
Assert.assertEquals(Response.Status.OK.getStatusCode(),response.getStatus());
Markus Boese, Mark Bonnekessel JAX-RS 35
Motivation REST JAX-RS Praktikum
Praktikum
Demo
Markus Boese, Mark Bonnekessel JAX-RS 36
LiteraturStefan Tilkov : REST und HTTP.Dpunkt-Verlag, Heidelberg, 2009
Online Quellen
• http://www.w3.org/Protocols/rfc2616/rfc2616.html• http://www.ics.uci.edu/˜fielding/pubs/
dissertation/rest_arch_style.htm• https://jersey.java.net/• https://grizzly.java.net/• https://developer.mozilla.org/en-US/docs/Web/
HTTP/Access_control_CORS• http://docs.oracle.com/javase/8/docs/api/