SlideShare uma empresa Scribd logo
1 de 37
© 2010 VMware Inc. All rights reserved
Building RESTful Web Services with Java
Vassil Popovski (vpopovski@vmware.com)
Staff Engineer, R&D
VMware, Inc.
10/07/2010
2
Agenda
 REST Principles and examples
 Java (JAX-RS) and REST
 Live Demo
 JAX-RS Advanced concepts
3
What is REST?
4
5
What is REST ? (now seriously)
 Representational State Transfer
 Introduced in 2000 by Roy Fielding:
• in his PhD thesis (chapter 5)
http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm
• Captured his interpretation of the WWW architecture
 Architectural style for distributed system such as World Wide Web
• Note: REST is *not* a standard, just a set of principles
 Positioned as an alternative to WS-* implementations
6
What is REST ? (now seriously)
7
REST Principles (RESTful systems)
Everything is a resource
• Examples: Customer, Locations, Item, List of users
Resources have identifiers
• Examples: URIs for web
Uniform interfaces to access the resources
• Examples: HTTP methods (GET, POST, PUT, DELETE, HEAD)
Resources have representations
• Examples: XML, JSON, Binary
Link resources together
• Hypermedia as the Engine of Application State (HATEOAS)
• Examples: Hyperlinks
1
2
3
4
5
9
Real life example
 Bug tracking system (over simplified)
• Bugs (summary, priority, user who reported it)
• Notes (description, user who created the note)
• Users (user name)
UML Notation:
“whole-part” relationship (composition)
“part” is exclusively owned by “whole”
UML Notation:
One-way association
UML Notation:
Generalization / inheritance
10
Real life example – resources and identifies
 Resources:
• User, Bug, Note,
• All users, All bugs, All notes for a particular bug
 Identifiers
Identifiers Note
http://<host>/users All users
http://<host>/users/{userId} A particular user
http://<host>/bugs All bugs
http://<host>/bugs/{bugId} A particular bug
http://<host>/bugs/{bugId}/notes All notes for a particular bug
http://<host>/bugs/{bugId}/notes/{noteId} A particular note for a particular bug
1 Everything is a resource
2 Resources have identifiers
11
Uniform interfaces (in the context of REST)
 HTTP verbs (CRUD interfaces)
HTTP verb Meaning Safe? Idempotent? Cacheable?
POST Create*
GET Retrieve
PUT Update*
DELETE Delete
f(f(x)) = f(x)
Does not cause
side effects
(*) POST and PUT may also have other meanings
POST – can be used for partial updates and also to add something to a
resource (PASTE AFTER)
PUT – can be used to create if sending the full content of the specified
resource and you know the URI of the resource (PASTE OVER)
12
Real life example – uniform interfaces
Operation Description
GET http://<host>/users List all users
POST http://<host>/users Creates a new user
GET http://<host>/users/345 Retrieves a particular user
PUT http://<host>/users/345 Modifies a particular user
DELETE http://<host>/users/345 Deletes a particular user
Operation Description
GET http://<host>/bugs/234/notes List all notes for bug 234
POST http://<host>/bugs/234/notes Creates a new note for bug 234
[GET | PUT | DELETE] .../bugs/234/notes/34 [retrieves | modifies | deletes]
note 34 in bug 234
3 Uniform interfaces to access the resources
13
Real life example – representations and linking resources
 XML representation for note:
 JSON representation for bug:
GET http://localhost:9000/bugs/1/notes/1
Content-type: application/xml
<Note href=“http://localhost:9000/bugs/1/notes/1">
<description>It is really broken</description>
<owner>http://localhost:9000/users/1</owner>
</Note>
POST http://localhost:9000/bugs
Content-type: application/json
{
"Bug" : {
"priority" : "P1",
"reporter" : "http://localhost:9000/users/1",
"summary" : "Something is wrong"
}
}
4 Resources have representations
5 Link resources together
Note: the client can request
different representations
using “Accept” http header
Note: the client declares what
representation it sends to
server with “Content-type”
http header
14
Java and REST
15
JAX-RS: Java API for RESTful Web Services
 JSR 311 (https://jsr311.dev.java.net/)
• Current version of JAX-RS spec is 1.1
• The spec is “readable”!
• Roy Fielding is an expert group member for this JSR
• javax.ws.rs.*
 JAX-RS in 1 sentence:
• JAX-RS = POJOs + Annotations
 JAX-RS capabilities:
• Dispatch URIs to specific classes and methods that can handle requests
• Methods deal with POJOs (nicely integrates with JAXB)
• Allows to map HTTP requests to method invocations
• URI manipulation functionality
16
JAX-RS implementations
 Jersey (reference implementation)
 Apache CXF (the one used in the demo)
 Apache Wink
 eXo
 RESTEasy
 Restlet
 Triaxrs
17
JAX-RS key concepts
 Resource classes
• Java classes that have at least one method annotated with @Path or a request method designator
(@GET, @PUT, @POST, @DELETE)
• Lifecycle:
• By default a new resource class instance is created for each request
• The JSR does not restrict other implementation specific lifecycles
 Resource methods
• A public method of a resource class annotated with a request method designator (@GET, @PUT,
@POST, @DELETE, @OPTIONS, @HEAD)
 Provider classes
• Classes annotated with @Provider and implementing one or more JAX-RS interfaces:
• MessageBodyReader/MessageBodyWriter
• ExceptionMapper
• ContextResolver
• Lifecycle:
• By default single instance of each provider class is instantiated for each JAX-RS application
• The JSR does not restrict other implementation specific lifecycles
18
JAX-RS annotations (most commonly used)
Annotation Target Description
@Path Class or Method Relative path for a resource
@Consumes
@Produces
Class or Method List of media types that can be consumed /
produced
@GET
@POST
@PUT
@DELETE
@OPTIONS
@HEAD
Method HTTP verb handled by the annotated method
@PathParam Parameter (also
field, POJO method)
Value that can be extracted from URI
@Context Parameter (also
field, POJO method)
Inject contextual information – UriInfo,
HttpHeaders, Request, ContextResolver, etc.
19
JAX-RS complete example
@Path("/users")
public class UserHandler {
@GET
@Path("{id}")
@Produces("application/xml”)
public JaxbUser getUser(@PathParam("id") long id) {
...
}
20
JAX-RS complete example
@Path("/users")
public class UserHandler {
@GET
@Path("{id}")
@Produces("application/xml”)
public JaxbUser getUser(@PathParam("id") long id) {
...
}
Base URI path to resource
21
JAX-RS complete example
@Path("/users")
public class UserHandler {
@GET
@Path("{id}")
@Produces("application/xml”)
public JaxbUser getUser(@PathParam("id") long id) {
...
}
The HTTP method for
getUser() method
22
JAX-RS complete example
@Path("/users")
public class UserHandler {
@GET
@Path("{id}")
@Produces("application/xml”)
public JaxbUser getUser(@PathParam("id") long id) {
...
}
URI path
segment/parameter
23
JAX-RS complete example
@Path("/users")
public class UserHandler {
@GET
@Path("{id}")
@Produces("application/xml”)
public JaxbUser getUser(@PathParam("id") long id) {
...
}
GET …/users/{id}
24
JAX-RS complete example
@Path("/users")
public class UserHandler {
@GET
@Path("{id}")
@Produces("application/xml”)
public JaxbUser getUser(@PathParam("id") long id) {
...
}
Returned Content-Type
25
JAX-RS complete example
@Path("/users")
public class UserHandler {
@GET
@Path("{id}")
@Produces("application/xml”)
public JaxbUser getUser(@PathParam("id") long id) {
...
}
Injects the value of URI
segment into the id
parameter
26
JAX-RS complete example
@Path("/users")
public class UserHandler {
@GET
@Path("{id}")
@Produces("application/xml”)
public JaxbUser getUser(@PathParam("id") long id) {
...
}
GET http://localhost:9000/users/2
Content-Type: application/xml
<?xml version="1.0" encoding="UTF-8"?>
<User> … </User>
27
28
Demo
to wake you up…
29
Advanced topics
 Regular expressions in @Path
 @*Params
 ExceptionMapper
 MessageBodyReader/MessageBodyWriter
30
@Path and regular expression mappings
 @Path(path-expression)
"{" variable-name [ ":" regular-expression ] "}“
 Examples
• @Path("example2/{var:.+}") matches following:
• …/example2/a
• …/example2/a/b/c
• @Path("example3/{var:d+}") matches following:
• …/example3/345
• …/example3/23
• @Path(“example4/{name}-{id}”) matches following:
• …/example4/a-1
• …/example4/a----1
31
@[Query|Header|Matrix|Cookie|Form]Param
 @QueryParam
• For example …/query?sorted=true
@GET
@Path("query")
public String queryParamExample(@QueryParam(“sorted") String var) {
return var;
}
 @MartixParam
• For example …/users;sorted=true
 @HeaderParam
• For example “Date” header
 @CookieParam / @FormParam
 @DefaultValue – can be used with any @*Param to specify the default
value
32
Exception Mappers
package javax.ws.rs.ext
public interface ExceptionMapper<E extends Throwable> {
Response toResponse(E exception);
}
33
MessageBodyReader
 MessageBodyReader
 MessageBodyWriter
package javax.ws.rs.ext
public interface MessageBodyReader<T> {
boolean isReadable(Class<?> type, Type genericType,
Annotation annotations[], MediaType mediaType);
T readFrom(Class<T> type, Type genericType,
Annotation annotations[], MediaType mediaType,
MultivaluedMap<String, String> httpHeaders,
InputStream entityStream) throws IOException, WebApplicationException;
}
34
MessageBodyWriter
package javax.ws.rs.ext
public interface MessageBodyWriter<T> {
boolean isWriteable(Class<?> type, Type genericType,
Annotation annotations[], MediaType mediaType);
long getSize(T t, Class<?> type, Type genericType, Annotation annotations[],
MediaType mediaType);
void writeTo(T t, Class<?> type, Type genericType, Annotation annotations[],
MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream) throws IOException, WebApplicationException;
}
35
JAX-RS features that were not covered
 PathSegment
 @Encoded
 @ApplicationPath
 Cookies
 Complex negotiation / Variant processing (javax.ws.rs.core.Variant):
 @OPTIONS, @HEAD, @HttpMethod
 SecurityContext
 CacheControl (+ Etags, conditional GET/PUT)
 Application (+ how to deploy in servlet container, EE6, EJB)
 Integration with Spring
 Security
36
Several other topics not covered
 Restful java clients
 WADL
 REST support in Spring 3.0
37
Additional materials
 Apache CXF (JAX-RS part): http://cxf.apache.org/docs/jax-rs.html
 RESTEasy users guide:
http://docs.jboss.org/resteasy/docs/1.1.GA/userguide/pdf/RESTEas
y_Reference_Guide.pdf
 WizTools REST Client: http://code.google.com/p/rest-client/
38

Mais conteúdo relacionado

Mais procurados

Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output ConceptsVicter Paul
 
I/O in java Part 1
I/O in java Part 1I/O in java Part 1
I/O in java Part 1ashishspace
 
04 darwino concepts and utility classes
04   darwino concepts and utility classes04   darwino concepts and utility classes
04 darwino concepts and utility classesdarwinodb
 
14 file handling
14 file handling14 file handling
14 file handlingAPU
 
Session 23 - JDBC
Session 23 - JDBCSession 23 - JDBC
Session 23 - JDBCPawanMM
 
Session 22 - Java IO, Serialization
Session 22 - Java IO, SerializationSession 22 - Java IO, Serialization
Session 22 - Java IO, SerializationPawanMM
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streamsShahjahan Samoon
 
Various io stream classes .47
Various io stream classes .47Various io stream classes .47
Various io stream classes .47myrajendra
 
Files & IO in Java
Files & IO in JavaFiles & IO in Java
Files & IO in JavaCIB Egypt
 
input/ output in java
input/ output  in javainput/ output  in java
input/ output in javasharma230399
 
Character stream classes introd .51
Character stream classes introd  .51Character stream classes introd  .51
Character stream classes introd .51myrajendra
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and OutputEduardo Bergavera
 

Mais procurados (20)

Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
 
I/O in java Part 1
I/O in java Part 1I/O in java Part 1
I/O in java Part 1
 
Files in java
Files in javaFiles in java
Files in java
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Java file
Java fileJava file
Java file
 
04 darwino concepts and utility classes
04   darwino concepts and utility classes04   darwino concepts and utility classes
04 darwino concepts and utility classes
 
14 file handling
14 file handling14 file handling
14 file handling
 
Session 23 - JDBC
Session 23 - JDBCSession 23 - JDBC
Session 23 - JDBC
 
Session 22 - Java IO, Serialization
Session 22 - Java IO, SerializationSession 22 - Java IO, Serialization
Session 22 - Java IO, Serialization
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
 
Input output streams
Input output streamsInput output streams
Input output streams
 
Java stream
Java streamJava stream
Java stream
 
Java IO
Java IOJava IO
Java IO
 
Handling I/O in Java
Handling I/O in JavaHandling I/O in Java
Handling I/O in Java
 
Various io stream classes .47
Various io stream classes .47Various io stream classes .47
Various io stream classes .47
 
Files & IO in Java
Files & IO in JavaFiles & IO in Java
Files & IO in Java
 
input/ output in java
input/ output  in javainput/ output  in java
input/ output in java
 
32.java input-output
32.java input-output32.java input-output
32.java input-output
 
Character stream classes introd .51
Character stream classes introd  .51Character stream classes introd  .51
Character stream classes introd .51
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and Output
 

Semelhante a Building Restful Web Services with Java

JAX-RS Creating RESTFul services
JAX-RS Creating RESTFul servicesJAX-RS Creating RESTFul services
JAX-RS Creating RESTFul servicesLudovic Champenois
 
Spark IT 2011 - Developing RESTful Web services with JAX-RS
Spark IT 2011 - Developing RESTful Web services with JAX-RSSpark IT 2011 - Developing RESTful Web services with JAX-RS
Spark IT 2011 - Developing RESTful Web services with JAX-RSArun Gupta
 
CDI, Seam & RESTEasy: You haven't seen REST yet!
CDI, Seam & RESTEasy: You haven't seen REST yet!CDI, Seam & RESTEasy: You haven't seen REST yet!
CDI, Seam & RESTEasy: You haven't seen REST yet!Dan Allen
 
RESTful Web services using JAX-RS
RESTful Web services using JAX-RSRESTful Web services using JAX-RS
RESTful Web services using JAX-RSArun Gupta
 
JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011Shreedhar Ganapathy
 
JSUG - RESTful Web Services by Florian Motlik
JSUG - RESTful Web Services by Florian MotlikJSUG - RESTful Web Services by Florian Motlik
JSUG - RESTful Web Services by Florian MotlikChristoph Pickl
 
Using Java to implement RESTful Web Services: JAX-RS
Using Java to implement RESTful Web Services: JAX-RSUsing Java to implement RESTful Web Services: JAX-RS
Using Java to implement RESTful Web Services: JAX-RSKatrien Verbert
 
RESTful Web Services with Jersey
RESTful Web Services with JerseyRESTful Web Services with Jersey
RESTful Web Services with JerseyScott Leberknight
 
Java colombo-deep-dive-into-jax-rs
Java colombo-deep-dive-into-jax-rsJava colombo-deep-dive-into-jax-rs
Java colombo-deep-dive-into-jax-rsSagara Gunathunga
 
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy ClarksonMulti Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy ClarksonJoshua Long
 
Developing RESTful WebServices using Jersey
Developing RESTful WebServices using JerseyDeveloping RESTful WebServices using Jersey
Developing RESTful WebServices using Jerseyb_kathir
 
RESTful application with JAX-RS and how to expose and test them
RESTful application with JAX-RS and how to expose and test themRESTful application with JAX-RS and how to expose and test them
RESTful application with JAX-RS and how to expose and test themKumaraswamy M
 
Making Java REST with JAX-RS 2.0
Making Java REST with JAX-RS 2.0Making Java REST with JAX-RS 2.0
Making Java REST with JAX-RS 2.0Dmytro Chyzhykov
 
Restful webservices
Restful webservicesRestful webservices
Restful webservicesKong King
 
Overview of RESTful web services
Overview of RESTful web servicesOverview of RESTful web services
Overview of RESTful web servicesnbuddharaju
 
Eclipse Day India 2015 - Rest with Java (jax rs) and jersey
Eclipse Day India 2015 - Rest with Java (jax rs) and jerseyEclipse Day India 2015 - Rest with Java (jax rs) and jersey
Eclipse Day India 2015 - Rest with Java (jax rs) and jerseyEclipse Day India
 
Rest with java (jax rs) and jersey and swagger
Rest with java (jax rs) and jersey and swaggerRest with java (jax rs) and jersey and swagger
Rest with java (jax rs) and jersey and swaggerKumaraswamy M
 
S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010
S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010
S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010Arun Gupta
 
Native REST Web Services with Oracle 11g
Native REST Web Services with Oracle 11gNative REST Web Services with Oracle 11g
Native REST Web Services with Oracle 11gMarcelo Ochoa
 

Semelhante a Building Restful Web Services with Java (20)

JAX-RS Creating RESTFul services
JAX-RS Creating RESTFul servicesJAX-RS Creating RESTFul services
JAX-RS Creating RESTFul services
 
Spark IT 2011 - Developing RESTful Web services with JAX-RS
Spark IT 2011 - Developing RESTful Web services with JAX-RSSpark IT 2011 - Developing RESTful Web services with JAX-RS
Spark IT 2011 - Developing RESTful Web services with JAX-RS
 
CDI, Seam & RESTEasy: You haven't seen REST yet!
CDI, Seam & RESTEasy: You haven't seen REST yet!CDI, Seam & RESTEasy: You haven't seen REST yet!
CDI, Seam & RESTEasy: You haven't seen REST yet!
 
RESTful Web services using JAX-RS
RESTful Web services using JAX-RSRESTful Web services using JAX-RS
RESTful Web services using JAX-RS
 
JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011
 
JSUG - RESTful Web Services by Florian Motlik
JSUG - RESTful Web Services by Florian MotlikJSUG - RESTful Web Services by Florian Motlik
JSUG - RESTful Web Services by Florian Motlik
 
Using Java to implement RESTful Web Services: JAX-RS
Using Java to implement RESTful Web Services: JAX-RSUsing Java to implement RESTful Web Services: JAX-RS
Using Java to implement RESTful Web Services: JAX-RS
 
RESTful Web Services with Jersey
RESTful Web Services with JerseyRESTful Web Services with Jersey
RESTful Web Services with Jersey
 
Java colombo-deep-dive-into-jax-rs
Java colombo-deep-dive-into-jax-rsJava colombo-deep-dive-into-jax-rs
Java colombo-deep-dive-into-jax-rs
 
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy ClarksonMulti Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
 
Developing RESTful WebServices using Jersey
Developing RESTful WebServices using JerseyDeveloping RESTful WebServices using Jersey
Developing RESTful WebServices using Jersey
 
RESTful application with JAX-RS and how to expose and test them
RESTful application with JAX-RS and how to expose and test themRESTful application with JAX-RS and how to expose and test them
RESTful application with JAX-RS and how to expose and test them
 
Power tools in Java
Power tools in JavaPower tools in Java
Power tools in Java
 
Making Java REST with JAX-RS 2.0
Making Java REST with JAX-RS 2.0Making Java REST with JAX-RS 2.0
Making Java REST with JAX-RS 2.0
 
Restful webservices
Restful webservicesRestful webservices
Restful webservices
 
Overview of RESTful web services
Overview of RESTful web servicesOverview of RESTful web services
Overview of RESTful web services
 
Eclipse Day India 2015 - Rest with Java (jax rs) and jersey
Eclipse Day India 2015 - Rest with Java (jax rs) and jerseyEclipse Day India 2015 - Rest with Java (jax rs) and jersey
Eclipse Day India 2015 - Rest with Java (jax rs) and jersey
 
Rest with java (jax rs) and jersey and swagger
Rest with java (jax rs) and jersey and swaggerRest with java (jax rs) and jersey and swagger
Rest with java (jax rs) and jersey and swagger
 
S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010
S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010
S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010
 
Native REST Web Services with Oracle 11g
Native REST Web Services with Oracle 11gNative REST Web Services with Oracle 11g
Native REST Web Services with Oracle 11g
 

Mais de Vassil Popovski

Why Teams and Culture Matter: Leadership lessons
Why Teams and Culture Matter: Leadership lessonsWhy Teams and Culture Matter: Leadership lessons
Why Teams and Culture Matter: Leadership lessonsVassil Popovski
 
ISTA 2017: Practical Chatbots - Technology Overview with Real-Life Stories
ISTA 2017: Practical Chatbots - Technology Overview with Real-Life StoriesISTA 2017: Practical Chatbots - Technology Overview with Real-Life Stories
ISTA 2017: Practical Chatbots - Technology Overview with Real-Life StoriesVassil Popovski
 
Testing Multithreaded Java Applications for Synchronization Problems, ISTA 2011
Testing Multithreaded Java Applications for Synchronization Problems, ISTA 2011Testing Multithreaded Java Applications for Synchronization Problems, ISTA 2011
Testing Multithreaded Java Applications for Synchronization Problems, ISTA 2011Vassil Popovski
 
Automated Unit Test Generation - ISTA 2013
Automated Unit Test Generation - ISTA 2013Automated Unit Test Generation - ISTA 2013
Automated Unit Test Generation - ISTA 2013Vassil Popovski
 
Automated unit test generation presentation - Java2ays 2013
Automated unit test generation presentation  -  Java2ays 2013Automated unit test generation presentation  -  Java2ays 2013
Automated unit test generation presentation - Java2ays 2013Vassil Popovski
 
Testing multithreaded java applications for synchronization problems
Testing multithreaded java applications for synchronization problemsTesting multithreaded java applications for synchronization problems
Testing multithreaded java applications for synchronization problemsVassil Popovski
 

Mais de Vassil Popovski (6)

Why Teams and Culture Matter: Leadership lessons
Why Teams and Culture Matter: Leadership lessonsWhy Teams and Culture Matter: Leadership lessons
Why Teams and Culture Matter: Leadership lessons
 
ISTA 2017: Practical Chatbots - Technology Overview with Real-Life Stories
ISTA 2017: Practical Chatbots - Technology Overview with Real-Life StoriesISTA 2017: Practical Chatbots - Technology Overview with Real-Life Stories
ISTA 2017: Practical Chatbots - Technology Overview with Real-Life Stories
 
Testing Multithreaded Java Applications for Synchronization Problems, ISTA 2011
Testing Multithreaded Java Applications for Synchronization Problems, ISTA 2011Testing Multithreaded Java Applications for Synchronization Problems, ISTA 2011
Testing Multithreaded Java Applications for Synchronization Problems, ISTA 2011
 
Automated Unit Test Generation - ISTA 2013
Automated Unit Test Generation - ISTA 2013Automated Unit Test Generation - ISTA 2013
Automated Unit Test Generation - ISTA 2013
 
Automated unit test generation presentation - Java2ays 2013
Automated unit test generation presentation  -  Java2ays 2013Automated unit test generation presentation  -  Java2ays 2013
Automated unit test generation presentation - Java2ays 2013
 
Testing multithreaded java applications for synchronization problems
Testing multithreaded java applications for synchronization problemsTesting multithreaded java applications for synchronization problems
Testing multithreaded java applications for synchronization problems
 

Último

WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...masabamasaba
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024VictoriaMetrics
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyviewmasabamasaba
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfkalichargn70th171
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Bert Jan Schrijver
 

Último (20)

WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 

Building Restful Web Services with Java

  • 1. © 2010 VMware Inc. All rights reserved Building RESTful Web Services with Java Vassil Popovski (vpopovski@vmware.com) Staff Engineer, R&D VMware, Inc. 10/07/2010
  • 2. 2 Agenda  REST Principles and examples  Java (JAX-RS) and REST  Live Demo  JAX-RS Advanced concepts
  • 4. 4
  • 5. 5 What is REST ? (now seriously)  Representational State Transfer  Introduced in 2000 by Roy Fielding: • in his PhD thesis (chapter 5) http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm • Captured his interpretation of the WWW architecture  Architectural style for distributed system such as World Wide Web • Note: REST is *not* a standard, just a set of principles  Positioned as an alternative to WS-* implementations
  • 6. 6 What is REST ? (now seriously)
  • 7. 7 REST Principles (RESTful systems) Everything is a resource • Examples: Customer, Locations, Item, List of users Resources have identifiers • Examples: URIs for web Uniform interfaces to access the resources • Examples: HTTP methods (GET, POST, PUT, DELETE, HEAD) Resources have representations • Examples: XML, JSON, Binary Link resources together • Hypermedia as the Engine of Application State (HATEOAS) • Examples: Hyperlinks 1 2 3 4 5
  • 8. 9 Real life example  Bug tracking system (over simplified) • Bugs (summary, priority, user who reported it) • Notes (description, user who created the note) • Users (user name) UML Notation: “whole-part” relationship (composition) “part” is exclusively owned by “whole” UML Notation: One-way association UML Notation: Generalization / inheritance
  • 9. 10 Real life example – resources and identifies  Resources: • User, Bug, Note, • All users, All bugs, All notes for a particular bug  Identifiers Identifiers Note http://<host>/users All users http://<host>/users/{userId} A particular user http://<host>/bugs All bugs http://<host>/bugs/{bugId} A particular bug http://<host>/bugs/{bugId}/notes All notes for a particular bug http://<host>/bugs/{bugId}/notes/{noteId} A particular note for a particular bug 1 Everything is a resource 2 Resources have identifiers
  • 10. 11 Uniform interfaces (in the context of REST)  HTTP verbs (CRUD interfaces) HTTP verb Meaning Safe? Idempotent? Cacheable? POST Create* GET Retrieve PUT Update* DELETE Delete f(f(x)) = f(x) Does not cause side effects (*) POST and PUT may also have other meanings POST – can be used for partial updates and also to add something to a resource (PASTE AFTER) PUT – can be used to create if sending the full content of the specified resource and you know the URI of the resource (PASTE OVER)
  • 11. 12 Real life example – uniform interfaces Operation Description GET http://<host>/users List all users POST http://<host>/users Creates a new user GET http://<host>/users/345 Retrieves a particular user PUT http://<host>/users/345 Modifies a particular user DELETE http://<host>/users/345 Deletes a particular user Operation Description GET http://<host>/bugs/234/notes List all notes for bug 234 POST http://<host>/bugs/234/notes Creates a new note for bug 234 [GET | PUT | DELETE] .../bugs/234/notes/34 [retrieves | modifies | deletes] note 34 in bug 234 3 Uniform interfaces to access the resources
  • 12. 13 Real life example – representations and linking resources  XML representation for note:  JSON representation for bug: GET http://localhost:9000/bugs/1/notes/1 Content-type: application/xml <Note href=“http://localhost:9000/bugs/1/notes/1"> <description>It is really broken</description> <owner>http://localhost:9000/users/1</owner> </Note> POST http://localhost:9000/bugs Content-type: application/json { "Bug" : { "priority" : "P1", "reporter" : "http://localhost:9000/users/1", "summary" : "Something is wrong" } } 4 Resources have representations 5 Link resources together Note: the client can request different representations using “Accept” http header Note: the client declares what representation it sends to server with “Content-type” http header
  • 14. 15 JAX-RS: Java API for RESTful Web Services  JSR 311 (https://jsr311.dev.java.net/) • Current version of JAX-RS spec is 1.1 • The spec is “readable”! • Roy Fielding is an expert group member for this JSR • javax.ws.rs.*  JAX-RS in 1 sentence: • JAX-RS = POJOs + Annotations  JAX-RS capabilities: • Dispatch URIs to specific classes and methods that can handle requests • Methods deal with POJOs (nicely integrates with JAXB) • Allows to map HTTP requests to method invocations • URI manipulation functionality
  • 15. 16 JAX-RS implementations  Jersey (reference implementation)  Apache CXF (the one used in the demo)  Apache Wink  eXo  RESTEasy  Restlet  Triaxrs
  • 16. 17 JAX-RS key concepts  Resource classes • Java classes that have at least one method annotated with @Path or a request method designator (@GET, @PUT, @POST, @DELETE) • Lifecycle: • By default a new resource class instance is created for each request • The JSR does not restrict other implementation specific lifecycles  Resource methods • A public method of a resource class annotated with a request method designator (@GET, @PUT, @POST, @DELETE, @OPTIONS, @HEAD)  Provider classes • Classes annotated with @Provider and implementing one or more JAX-RS interfaces: • MessageBodyReader/MessageBodyWriter • ExceptionMapper • ContextResolver • Lifecycle: • By default single instance of each provider class is instantiated for each JAX-RS application • The JSR does not restrict other implementation specific lifecycles
  • 17. 18 JAX-RS annotations (most commonly used) Annotation Target Description @Path Class or Method Relative path for a resource @Consumes @Produces Class or Method List of media types that can be consumed / produced @GET @POST @PUT @DELETE @OPTIONS @HEAD Method HTTP verb handled by the annotated method @PathParam Parameter (also field, POJO method) Value that can be extracted from URI @Context Parameter (also field, POJO method) Inject contextual information – UriInfo, HttpHeaders, Request, ContextResolver, etc.
  • 18. 19 JAX-RS complete example @Path("/users") public class UserHandler { @GET @Path("{id}") @Produces("application/xml”) public JaxbUser getUser(@PathParam("id") long id) { ... }
  • 19. 20 JAX-RS complete example @Path("/users") public class UserHandler { @GET @Path("{id}") @Produces("application/xml”) public JaxbUser getUser(@PathParam("id") long id) { ... } Base URI path to resource
  • 20. 21 JAX-RS complete example @Path("/users") public class UserHandler { @GET @Path("{id}") @Produces("application/xml”) public JaxbUser getUser(@PathParam("id") long id) { ... } The HTTP method for getUser() method
  • 21. 22 JAX-RS complete example @Path("/users") public class UserHandler { @GET @Path("{id}") @Produces("application/xml”) public JaxbUser getUser(@PathParam("id") long id) { ... } URI path segment/parameter
  • 22. 23 JAX-RS complete example @Path("/users") public class UserHandler { @GET @Path("{id}") @Produces("application/xml”) public JaxbUser getUser(@PathParam("id") long id) { ... } GET …/users/{id}
  • 23. 24 JAX-RS complete example @Path("/users") public class UserHandler { @GET @Path("{id}") @Produces("application/xml”) public JaxbUser getUser(@PathParam("id") long id) { ... } Returned Content-Type
  • 24. 25 JAX-RS complete example @Path("/users") public class UserHandler { @GET @Path("{id}") @Produces("application/xml”) public JaxbUser getUser(@PathParam("id") long id) { ... } Injects the value of URI segment into the id parameter
  • 25. 26 JAX-RS complete example @Path("/users") public class UserHandler { @GET @Path("{id}") @Produces("application/xml”) public JaxbUser getUser(@PathParam("id") long id) { ... } GET http://localhost:9000/users/2 Content-Type: application/xml <?xml version="1.0" encoding="UTF-8"?> <User> … </User>
  • 26. 27
  • 28. 29 Advanced topics  Regular expressions in @Path  @*Params  ExceptionMapper  MessageBodyReader/MessageBodyWriter
  • 29. 30 @Path and regular expression mappings  @Path(path-expression) "{" variable-name [ ":" regular-expression ] "}“  Examples • @Path("example2/{var:.+}") matches following: • …/example2/a • …/example2/a/b/c • @Path("example3/{var:d+}") matches following: • …/example3/345 • …/example3/23 • @Path(“example4/{name}-{id}”) matches following: • …/example4/a-1 • …/example4/a----1
  • 30. 31 @[Query|Header|Matrix|Cookie|Form]Param  @QueryParam • For example …/query?sorted=true @GET @Path("query") public String queryParamExample(@QueryParam(“sorted") String var) { return var; }  @MartixParam • For example …/users;sorted=true  @HeaderParam • For example “Date” header  @CookieParam / @FormParam  @DefaultValue – can be used with any @*Param to specify the default value
  • 31. 32 Exception Mappers package javax.ws.rs.ext public interface ExceptionMapper<E extends Throwable> { Response toResponse(E exception); }
  • 32. 33 MessageBodyReader  MessageBodyReader  MessageBodyWriter package javax.ws.rs.ext public interface MessageBodyReader<T> { boolean isReadable(Class<?> type, Type genericType, Annotation annotations[], MediaType mediaType); T readFrom(Class<T> type, Type genericType, Annotation annotations[], MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException; }
  • 33. 34 MessageBodyWriter package javax.ws.rs.ext public interface MessageBodyWriter<T> { boolean isWriteable(Class<?> type, Type genericType, Annotation annotations[], MediaType mediaType); long getSize(T t, Class<?> type, Type genericType, Annotation annotations[], MediaType mediaType); void writeTo(T t, Class<?> type, Type genericType, Annotation annotations[], MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException; }
  • 34. 35 JAX-RS features that were not covered  PathSegment  @Encoded  @ApplicationPath  Cookies  Complex negotiation / Variant processing (javax.ws.rs.core.Variant):  @OPTIONS, @HEAD, @HttpMethod  SecurityContext  CacheControl (+ Etags, conditional GET/PUT)  Application (+ how to deploy in servlet container, EE6, EJB)  Integration with Spring  Security
  • 35. 36 Several other topics not covered  Restful java clients  WADL  REST support in Spring 3.0
  • 36. 37 Additional materials  Apache CXF (JAX-RS part): http://cxf.apache.org/docs/jax-rs.html  RESTEasy users guide: http://docs.jboss.org/resteasy/docs/1.1.GA/userguide/pdf/RESTEas y_Reference_Guide.pdf  WizTools REST Client: http://code.google.com/p/rest-client/
  • 37. 38