SlideShare ist ein Scribd-Unternehmen logo
1 von 59
Downloaden Sie, um offline zu lesen
Design REST Services with CXF JAX-
RS implementation: best practices
and lessons learned
Andrei Shakirin, Talend
ashakirin@talend.com
ashakirin.blogspot.com
Agenda
• REST architectural style
• Design of REST API for Syncope domain
• Practical aspects of using CXF JAX-RS
About Me
• Software architect in Talend Team
• PMC and committer in Apache CXF and
commiter in Apache Syncope projects
• Speaker for Java conferences
Representational State Transfer
• Set of principals and restrictions
• HTTP is one instantiation of the REST
• The scope of REST architectural style: loosely
coupled application
REST Principles
1. Everything has an ID
2. Using IDs to link things together: hypermedia
and HATEOAS
3. Uniform interface
4. Interaction with resources through the
representation
5. Communication is stateless
JAX-RS
• Specification and Java API
• Support in exposing a resource Java class (a
POJO) as a web resource
• Versions: 1.0, 1.1, 2.0 (client API,
asynchronous API, filters and interceptors)
• Implementations: Jersey, Apache CXF,
Resteasy, …
REST API Design
Apache Syncope
Syncope Domain Model
• Users (name, password, dates, attributes)
• Roles (name, owners, attributes)
• Entitlements (TASK_DELETE, ROLE_CREATE)
• Connectors (ConnID bundle: DatabaseTable,
SOAP)
• External Resources (name, connector, mode,
mapping)
• Tasks (user/role template, resource, action,
status)
Resources and URIs: Rules
• Resource is anything to be referenced
• Normally resources are the nouns
• Resources are coarse grained
• URIs: descriptive and well structured
• URIs: scoping information
Design Attempt
/users/addUser
/users/a1b2c3/verifyPassword
/roles/s8g3j8/updateRole
/tasks/submitTask
Don‘t do it!
Resources Types
1. Predefined top-level resources
2. Resource for collection of objects
3. Resource for every exposed objects
4. Resource representing results of algorithms
Top Level Resources
• Entry point to the API
• Home page or list of root entities (collections)
URIs:
http(s)://api.syncope.org/administration
vs
http(s)://api.syncope.org/administration/rest/jaxrs/c
xf
Collection Resources
/users
/roles
/connectors
/policies
/resources
/tasks
Instance Resources
No Hierarchy?
/relationships/user123,roleA
/color-blends/red;blue
/users/user123
/users/user123/status
/roles/roleA
/roles/roleA/parent
/connectors/ldap
/connectors/ldap/bundles
Algorithm Resources
FIQL (Feed Item Query Language):
/tasks?_s=date=lt=2014-10-31;date=gt=2014-
10-01;(type==sync)
/users?failedLogin=true
/tasks?type=propagation&status=success
Subset of Uniform Interface
Will the client will fetch resource of this type?
GET /users
GET /users/a1b2c3
Subset of Uniform Interface
Will the client delete resource of this type?
DELETE /users/a1b2c3
Subset of Uniform Interface
Will the client modify resource of this type?
PUT /users/a1b2c3
Subset of Uniform Interface
Will the client create resource of this type?
Who is in charge to determine URI: server /
client?
Server:
POST /users
201 Created, Location=/users/a1b2c3
Client:
PUT /users/myuser
Resource API: UserService
Representations: Media Types
Data Format + Parsing rules
Representations: Media Types
• Standard:
text/html
application/json
application/xml
application/xhtml+xml
application/x-www-form-urlencoded
• Custom:
application/user+json
application/vnd.mycompany-myformat
• Versioned:
application/user+json&v2
Representations: JAX-RS
@Path("users")
@Consumes("application/json", "application/xml")
@Produces("application/json", "application/xml")
public interface UserService {
@GET
@Produces("application/json;qs=1.0", "application/xml;qs=0.75")
Collection<UserTO> list();
@POST
@Consumes("application/json;q=1.0", "application/xml;q=0.25")
Response create(UserTO userTO);
…
}
CXF: Entity Providers
• XML: JAXBElementProvider, Source
application/xml, application/*+xml, text/xml
• JSON: JSONProvider(Jettison), Jenkins
application/json, application/*+json
• Multipart: Attachments, MultipartBody
multipart/mixed, multipart/related, …
• BinaryData
application/octet-stream, …
• XSLTJaxb, Atom, Dom4J, XMLBeans, …
JSON: Jettison vs Jackson
CXF JSONProvider (based on Jettison)
• Adopt XML structures to JSON (mapped,
BadgerFish)
• STaX API (XMLStreamWriter, XMLStreamReader)
• Flexible and simple (prefixes, root elements, array
serialization, unwrapping, XSLT transformations)
• Using: for small payloads, if flexibility required
<root><child>test</child><child>test</child></root>
{ "root" : { child : [ "test", "test" ] } }
JSON: Jettison vs Jackson
Jackson
• Not XML oriented
• Supports streaming, tree and data binding
models
• Supports Jackson specific annotations
• Using: middle and large payloads, sophisticated
class hierarchy
@JsonTypeInfo(use=Id.CLASS, include=As.PROPERTY,
property="class")
Representation: Links
• HTML/XHTML
<a href="http://mysyncope.com">Syncope</a>
• XML
<element
xlink:href="http://mysyncope.com">Syncope</element>
• JSON: ?
Links in JSON
• JSON HAL (Mike Kelly, IETF draft)
• Siren (Kevin Swiber)
• Collection + JSON (Mike Amudsen)
• Custom format
JSON HAL
GET /tasks
Relations: Many To Many
RoleUser
role 1
role 2
role N
user 1
user 2
user N
Relations as Resources
Membership
user 1
role 2
createdBy
timestamp
User Role
Errors
• Choose appropriate HTTP status code
• Set short error code for automatic processing
• Provide informative and descriptive entity-
bodies
• Use JAX-RS ExceptionMappers
Errors: Code Mapping
1. Decide is it client or server problem (4xx/5xx)
2. Look into HTTP status code spec and select
approprite one:
• Entity Not Found -> 404 Not Found
• Entity Already Exist -> 409 Conflict
• IllegalArgumentException -> 400 Bad Request
Errors: HTTP Response
404 Not found
X-Application-Error-Code: EntityNotFound
X-Application-Error-Info: entity=user,id=a1b2c3
{
A user ‘a1b2c3‘ is not found in Syncope storage. Check if
user name is correct. Refer following link for the details:
https://cwiki.apache.org/confluence/pages/viewpage.acti
on?pageId=30751185/
}
Errors: Batch Operations
207 Multi-Status
X-Application-Error-Code: Composite
{
“message“: “Multiple errors detected“
“errors“: [
{
“statusCode“: 409
“errorCode“: “EntityExists“
“ errorMessage “ : “User ‘a1b2c3‘ already exists“
}
{
“statusCode“: 404
“errorCode“: “NotFound“
“errorMessage“: “User ‘d4e5f6‘ not found“
}
…
]
}
Errors: ExceptionMappers
@Provider
public class RestServiceExceptionMapper implements
ExceptionMapper<SyncopeClientException> {
@Override
public Response toResponse(final SyncopeClientException ex) {
LOG.error("SyncopeClientException thrown by REST method: " +
ex.getMessage(), ex);
builder = ex.isComposite() ?
getSyncopeClientCompositeExceptionResponse(ex.asComposite())
: getSyncopeClientExceptionResponse(ex);
return builder.build();
}
}
Asynchronous Processing
• Model operations taking a long time
• Provide non-blocking calls on the client side
• Provide suspended responses on the server
side
Asynchronous: Long Operations
202 Accepted
Location: /tasks/x7h3b4
POST /tasks HTTP/1.1
{
"propagationMode": "TWO_PHASES",
"resource": { "href": "/resources/98712" }
"status": "NONE",
…
}
GET tasks/x7h3b4
{
"propagationMode": "TWO_PHASES",
"resource": { "href": "/resources/98712" }
"status": "IN_PROGRESS",
…
}
Asynchronous: Client API
InvocationCallback<Response> callback =
new InvocationCallback {
public void completed(Response res) {
System.out.println("Request success!");
}
public void failed(ClientException e) {
System.out.println("Request failed!");
}
};
client.target("http://mysyncope.org/tasks")
.request()
.async()
.post(myEntity, callback);
Asynchronous: Server API
@Path("/connectors")
public class AsyncResource {
@GET
public void asyncGet(@Suspended final AsyncResponse asyncResponse) {
new Thread(new Runnable() {
@Override
public void run() {
String result = readConnectors();
asyncResponse.resume(result);
}
private String readConnectors() {
// ... very expensive operation
}
}).start();
}
}
Transactions
/tasks/f3g4n5
{
“userFilter“: “age<=16“
}
/tasks/l8b3n7
{
“userFilter“: “age>16“
}
Requirement: update age to 18 in both tasks in transaction
Transactional View
1. Create transaction:
POST /transactions/tasks-update
201 Created
Location: /transactions/tasks-update/89d3
2. Update transaction resources:
PUT /transactions/tasks-update/89d3/tasks/f3g4n5
{
“userFilter“: “age<=18“
…
}
PUT /transactions/tasks-update/l8b3n7/tasks/f3g4n5
{
“userFilter“: “age>18“
…
}
Committed Transaction
3. Commit transaction:
PUT /transactions/tasks-update/89d3
committed = true
200 OK
{
“tasks“: [
{“ref“:“/tasks/f3g4n5“}
{“ref“:“/tasks/l8b3n7“}
]
}
GET /tasks/f3g4n5
{
“userFilter“: “age<=18“
…
}
GET /tasks/l8b3n7
{
“userFilter“: “age>18“
…
}
Bean Validation: JAX-RS
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
…
@Path("users")
@Consumes("application/json", "application/xml")
@Produces("application/json", "application/xml")
public interface UserService {
@GET
PagedResult<UserTO> list(
@NotNull @Min(1) @QueryParam(PARAM_PAGE) Integer page,
@NotNull @Min(1) @QueryParam(PARAM_SIZE) Integer size);
@GET
@Path("{email}")
@Valid UserTO getUser(@Email @PathParam("email") String email);
…
}
Conclusion
• Try to follow REST and RESTful HTTP principles
by design your application
• Consider using JAX-RS 2.0 implementation for
Java applications
• CXF is nice alternative with active, responsive
and cooperative community
Links
• Apache CXF :
http://cxf.apache.org/
http://cxf.apache.org/docs/jax-rs.html
• Apache Syncope:
http://syncope.apache.org/
• Blogs:
http://sberyozkin.blogspot.com
http://ashakirin.blogspot.de/
http://aredko.blogspot.de/
Validation
• JAX-RS 2.0: Bean Validation 1.1 Specification
• Implementation: Hibernate Validator (or
Apache BVal)
• Exception mapper maps:
a) Input parameter validation violation -> 400
Bad Request
b) Return value validation violation -> 500
Internal Server Error
Relations as Resources
GET users/a1b2c3
HTTP/1.1 200 OK
Content Type: application/linked+json
{
"href": "/users/a1b2c3",
"name": "testUser",
…
"memberships": {
"href": "/memberships?userId=a1b2c3"
}
}
OPTIONS
Returns communication options of target
resource
OPTIONS /users
Response:
200 OK
Allow: OPTIONS,GET,POST
Algorithm Resources
FIQL (Feed Item Query Language):
/tasks?_s=date=lt=2014-10-31;date=gt=2014-
10-01;(type==sync)
/users?failedLogin=true
/tasks?type=propagation&status=success
/role;name=myRole/entitlements;name=ROLE_
CREATE/
Bean Validation: CXF
<jaxrs:server address="/">
<jaxrs:inInterceptors>
<ref bean="validationInInterceptor" />
</jaxrs:inInterceptors>
<jaxrs:outInterceptors>
<ref bean="validationOutInterceptor" />
</jaxrs:outInterceptors>
<jaxrs:serviceBeans>
...
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean="exceptionMapper"/>
</jaxrs:providers>
</jaxrs:server>
<bean id="exceptionMapper"
class="org.apache.cxf.jaxrs.validation.ValidationExceptionMapper"/>
<bean id="validationProvider" class="org.apache.cxf.validation.BeanValidationProvider" />
<bean id="validationInInterceptor"
class="org.apache.cxf.jaxrs.validation.JAXRSBeanValidationInInterceptor">
<property name="provider" ref="validationProvider" />
</bean>
<bean id="validationOutInterceptor"
class="org.apache.cxf.jaxrs.validation.JAXRSBeanValidationOutInterceptor">
<property name="provider" ref="validationProvider" />
</bean>
GET, HEAD
• READ semantic
• Must be safe and idempotent
• Cacheable
• Can be conditional or partional
GET /users/a1b2c3
DELETE
• DELETE semantic
• Not safe, Idempotent
• Resource doesn‘t have to removed
immediately
• Can return the resource representation or
other payload
DELETE /users/a1b2c3
PUT
• Can be used for UPDATE and for CREATE
• Not safe, idempotent
• Not for partial updates
PUT /users/a1b2c3
{
“username“:“testUser“
“status“:“active“
…
}
POST
• Can be used to do anything (normally create or
update)
• Neither safe, no idempotent
POST /users
{
“username“:“testUser“
“status“:“active“
…
}
Response:
201 Created, Location=/users/a1b2c3
Resources and URIs: Rules
• Resource is anything to be referenced
• Normally resources are the nouns
• Resources are coarse grained
• URIs: descriptive and well structured
• URIs: scoping information
Representations: Media Types
Data Format + Parsing rules
Representations
Extension Mappings:
• /users/a1b2c3
• /users/a1b2c3.json
• /users/a1b2c3.xml

Weitere ähnliche Inhalte

Was ist angesagt?

REST - Representational state transfer
REST - Representational state transferREST - Representational state transfer
REST - Representational state transfer
Tricode (part of Dept)
 
Enterprise Java Web Application Frameworks Sample Stack Implementation
Enterprise Java Web Application Frameworks   Sample Stack ImplementationEnterprise Java Web Application Frameworks   Sample Stack Implementation
Enterprise Java Web Application Frameworks Sample Stack Implementation
Mert Çalışkan
 
WebLogic Developer Webcast 1: JPA 2.0
WebLogic Developer Webcast 1: JPA 2.0WebLogic Developer Webcast 1: JPA 2.0
WebLogic Developer Webcast 1: JPA 2.0
Jeffrey West
 

Was ist angesagt? (19)

Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
 
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
 
Lecture #6. automation testing (andrey oleynik)
Lecture #6. automation testing (andrey oleynik)Lecture #6. automation testing (andrey oleynik)
Lecture #6. automation testing (andrey oleynik)
 
REST - Representational state transfer
REST - Representational state transferREST - Representational state transfer
REST - Representational state transfer
 
Spring HATEOAS
Spring HATEOASSpring HATEOAS
Spring HATEOAS
 
RESTful Web APIs – Mike Amundsen, Principal API Architect, Layer 7
RESTful Web APIs – Mike Amundsen, Principal API Architect, Layer 7RESTful Web APIs – Mike Amundsen, Principal API Architect, Layer 7
RESTful Web APIs – Mike Amundsen, Principal API Architect, Layer 7
 
JAX-RS 2.0: RESTful Web Services
JAX-RS 2.0: RESTful Web ServicesJAX-RS 2.0: RESTful Web Services
JAX-RS 2.0: RESTful Web Services
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web api
 
Enterprise Java Web Application Frameworks Sample Stack Implementation
Enterprise Java Web Application Frameworks   Sample Stack ImplementationEnterprise Java Web Application Frameworks   Sample Stack Implementation
Enterprise Java Web Application Frameworks Sample Stack Implementation
 
Survey of restful web services frameworks
Survey of restful web services frameworksSurvey of restful web services frameworks
Survey of restful web services frameworks
 
Web services - A Practical Approach
Web services - A Practical ApproachWeb services - A Practical Approach
Web services - A Practical Approach
 
Amis conference soa deployment. the dirty tricks using bamboo, nexus and xl ...
Amis conference soa deployment. the dirty tricks using  bamboo, nexus and xl ...Amis conference soa deployment. the dirty tricks using  bamboo, nexus and xl ...
Amis conference soa deployment. the dirty tricks using bamboo, nexus and xl ...
 
ASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP FundamentalsASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP Fundamentals
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
 
Rest - Representational State Transfer (EMC BRDC Internal Tech talk)
Rest - Representational State Transfer (EMC BRDC Internal Tech talk)Rest - Representational State Transfer (EMC BRDC Internal Tech talk)
Rest - Representational State Transfer (EMC BRDC Internal Tech talk)
 
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
 
Oracle soa online training
Oracle soa online trainingOracle soa online training
Oracle soa online training
 
Hypermedia APIs
Hypermedia APIsHypermedia APIs
Hypermedia APIs
 
WebLogic Developer Webcast 1: JPA 2.0
WebLogic Developer Webcast 1: JPA 2.0WebLogic Developer Webcast 1: JPA 2.0
WebLogic Developer Webcast 1: JPA 2.0
 

Andere mochten auch

Andere mochten auch (18)

Sqlite tutorial
Sqlite tutorialSqlite tutorial
Sqlite tutorial
 
Net framework
Net frameworkNet framework
Net framework
 
0321146182
03211461820321146182
0321146182
 
B14200
B14200B14200
B14200
 
Culbert recommender systems
Culbert recommender systemsCulbert recommender systems
Culbert recommender systems
 
13 pv-do es-18-bigdata-v3
13 pv-do es-18-bigdata-v313 pv-do es-18-bigdata-v3
13 pv-do es-18-bigdata-v3
 
Agent technology for e commerce-recommendation systems
Agent technology for e commerce-recommendation systemsAgent technology for e commerce-recommendation systems
Agent technology for e commerce-recommendation systems
 
Httpclient tutorial
Httpclient tutorialHttpclient tutorial
Httpclient tutorial
 
Vortrag ralph behrens_ibm-data
Vortrag ralph behrens_ibm-dataVortrag ralph behrens_ibm-data
Vortrag ralph behrens_ibm-data
 
Chapter 02 collaborative recommendation
Chapter 02   collaborative recommendationChapter 02   collaborative recommendation
Chapter 02 collaborative recommendation
 
Big data tutorial_part4
Big data tutorial_part4Big data tutorial_part4
Big data tutorial_part4
 
Recommender systems session b
Recommender systems session bRecommender systems session b
Recommender systems session b
 
Android+ax+app+wcf
Android+ax+app+wcfAndroid+ax+app+wcf
Android+ax+app+wcf
 
Soap toolkits
Soap toolkitsSoap toolkits
Soap toolkits
 
Soap pt1
Soap pt1Soap pt1
Soap pt1
 
Show loader to open url in web view
Show loader to open url in web viewShow loader to open url in web view
Show loader to open url in web view
 
Introduction to visual studio and c sharp
Introduction to visual studio and c sharpIntroduction to visual studio and c sharp
Introduction to visual studio and c sharp
 
Json generation
Json generationJson generation
Json generation
 

Ähnlich wie Andrei shakirin rest_cxf

JUDCON India 2014 Java EE 7 talk
JUDCON India 2014 Java EE 7 talkJUDCON India 2014 Java EE 7 talk
JUDCON India 2014 Java EE 7 talk
Vijay Nair
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.js
Carol McDonald
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
WalaSidhom1
 
Rapid API Development ArangoDB Foxx
Rapid API Development ArangoDB FoxxRapid API Development ArangoDB Foxx
Rapid API Development ArangoDB Foxx
Michael Hackstein
 

Ähnlich wie Andrei shakirin rest_cxf (20)

WebCamp: Developer Day: Архитектура Web-приложений: обзор современных решений...
WebCamp: Developer Day: Архитектура Web-приложений: обзор современных решений...WebCamp: Developer Day: Архитектура Web-приложений: обзор современных решений...
WebCamp: Developer Day: Архитектура Web-приложений: обзор современных решений...
 
RESTing with JAX-RS
RESTing with JAX-RSRESTing with JAX-RS
RESTing with JAX-RS
 
Building APIs in an easy way using API Platform
Building APIs in an easy way using API PlatformBuilding APIs in an easy way using API Platform
Building APIs in an easy way using API Platform
 
Test-Driven Documentation for your REST(ful) service
Test-Driven Documentation for your REST(ful) serviceTest-Driven Documentation for your REST(ful) service
Test-Driven Documentation for your REST(ful) service
 
Building APIs in an easy way using API Platform
Building APIs in an easy way using API PlatformBuilding APIs in an easy way using API Platform
Building APIs in an easy way using API Platform
 
ITB2016 - Building ColdFusion RESTFul Services
ITB2016 - Building ColdFusion RESTFul ServicesITB2016 - Building ColdFusion RESTFul Services
ITB2016 - Building ColdFusion RESTFul Services
 
JAX-RS Creating RESTFul services
JAX-RS Creating RESTFul servicesJAX-RS Creating RESTFul services
JAX-RS Creating RESTFul services
 
JUDCON India 2014 Java EE 7 talk
JUDCON India 2014 Java EE 7 talkJUDCON India 2014 Java EE 7 talk
JUDCON India 2014 Java EE 7 talk
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.js
 
Rest
RestRest
Rest
 
Creating Restful Web Services with restish
Creating Restful Web Services with restishCreating Restful Web Services with restish
Creating Restful Web Services with restish
 
JSF 2.0 Preview
JSF 2.0 PreviewJSF 2.0 Preview
JSF 2.0 Preview
 
Entity provider selection confusion attacks in JAX-RS applications
Entity provider selection confusion attacks in JAX-RS applicationsEntity provider selection confusion attacks in JAX-RS applications
Entity provider selection confusion attacks in JAX-RS applications
 
Reactive Java Programming: A new Asynchronous Database Access API by Kuassi M...
Reactive Java Programming: A new Asynchronous Database Access API by Kuassi M...Reactive Java Programming: A new Asynchronous Database Access API by Kuassi M...
Reactive Java Programming: A new Asynchronous Database Access API by Kuassi M...
 
Rest And Rails
Rest And RailsRest And Rails
Rest And Rails
 
Prairie DevCon 2015 - Crafting Evolvable API Responses
Prairie DevCon 2015 - Crafting Evolvable API ResponsesPrairie DevCon 2015 - Crafting Evolvable API Responses
Prairie DevCon 2015 - Crafting Evolvable API Responses
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
 
Rapid API Development ArangoDB Foxx
Rapid API Development ArangoDB FoxxRapid API Development ArangoDB Foxx
Rapid API Development ArangoDB Foxx
 
Android and REST
Android and RESTAndroid and REST
Android and REST
 
Service approach for development Rest API in Symfony2
Service approach for development Rest API in Symfony2Service approach for development Rest API in Symfony2
Service approach for development Rest API in Symfony2
 

KĂźrzlich hochgeladen

Dombivli Call Girls, 9892124323, Kharghar Call Girls, chembur Call Girls, Vas...
Dombivli Call Girls, 9892124323, Kharghar Call Girls, chembur Call Girls, Vas...Dombivli Call Girls, 9892124323, Kharghar Call Girls, chembur Call Girls, Vas...
Dombivli Call Girls, 9892124323, Kharghar Call Girls, chembur Call Girls, Vas...
Pooja Nehwal
 
Call Girls Btm Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Btm Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...Call Girls Btm Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Btm Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
amitlee9823
 
Call Girls Devanahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Devanahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service B...Call Girls Devanahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Devanahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
amitlee9823
 
Call Girls Hosur Road Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hosur Road Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...Call Girls Hosur Road Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hosur Road Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
amitlee9823
 
Chikkabanavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
Chikkabanavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...Chikkabanavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
Chikkabanavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
amitlee9823
 
Call Girls In Kengeri Satellite Town ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Kengeri Satellite Town ☎ 7737669865 🥵 Book Your One night StandCall Girls In Kengeri Satellite Town ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Kengeri Satellite Town ☎ 7737669865 🥵 Book Your One night Stand
amitlee9823
 
Internship Report].pdf iiwmoosmsosmshkssmk
Internship Report].pdf iiwmoosmsosmshkssmkInternship Report].pdf iiwmoosmsosmshkssmk
Internship Report].pdf iiwmoosmsosmshkssmk
SujalTamhane
 
Call Girls Bommanahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service ...
Call Girls Bommanahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service ...Call Girls Bommanahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service ...
Call Girls Bommanahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service ...
amitlee9823
 
Call Girls Hoodi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hoodi Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Hoodi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hoodi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
amitlee9823
 
Call Girls Hosur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hosur Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Hosur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hosur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
amitlee9823
 

KĂźrzlich hochgeladen (20)

Dombivli Call Girls, 9892124323, Kharghar Call Girls, chembur Call Girls, Vas...
Dombivli Call Girls, 9892124323, Kharghar Call Girls, chembur Call Girls, Vas...Dombivli Call Girls, 9892124323, Kharghar Call Girls, chembur Call Girls, Vas...
Dombivli Call Girls, 9892124323, Kharghar Call Girls, chembur Call Girls, Vas...
 
TEST BANK For Evidence-Based Practice for Nurses Appraisal and Application of...
TEST BANK For Evidence-Based Practice for Nurses Appraisal and Application of...TEST BANK For Evidence-Based Practice for Nurses Appraisal and Application of...
TEST BANK For Evidence-Based Practice for Nurses Appraisal and Application of...
 
Call Girls Btm Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Btm Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...Call Girls Btm Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Btm Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
 
RĂŠsumĂŠ (2 pager - 12 ft standard syntax)
RĂŠsumĂŠ (2 pager -  12 ft standard syntax)RĂŠsumĂŠ (2 pager -  12 ft standard syntax)
RĂŠsumĂŠ (2 pager - 12 ft standard syntax)
 
Hot Call Girls |Delhi |Janakpuri ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Janakpuri ☎ 9711199171 Book Your One night StandHot Call Girls |Delhi |Janakpuri ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Janakpuri ☎ 9711199171 Book Your One night Stand
 
Brand Analysis for reggaeton artist Jahzel.
Brand Analysis for reggaeton artist Jahzel.Brand Analysis for reggaeton artist Jahzel.
Brand Analysis for reggaeton artist Jahzel.
 
Guide to a Winning Interview May 2024 for MCWN
Guide to a Winning Interview May 2024 for MCWNGuide to a Winning Interview May 2024 for MCWN
Guide to a Winning Interview May 2024 for MCWN
 
Call Girls Devanahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Devanahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service B...Call Girls Devanahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Devanahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
 
Call Girls Hosur Road Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hosur Road Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...Call Girls Hosur Road Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hosur Road Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
 
Chikkabanavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
Chikkabanavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...Chikkabanavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
Chikkabanavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
 
Call Girls In Kengeri Satellite Town ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Kengeri Satellite Town ☎ 7737669865 🥵 Book Your One night StandCall Girls In Kengeri Satellite Town ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Kengeri Satellite Town ☎ 7737669865 🥵 Book Your One night Stand
 
Internship Report].pdf iiwmoosmsosmshkssmk
Internship Report].pdf iiwmoosmsosmshkssmkInternship Report].pdf iiwmoosmsosmshkssmk
Internship Report].pdf iiwmoosmsosmshkssmk
 
Pooja 9892124323, Call girls Services and Mumbai Escort Service Near Hotel Sa...
Pooja 9892124323, Call girls Services and Mumbai Escort Service Near Hotel Sa...Pooja 9892124323, Call girls Services and Mumbai Escort Service Near Hotel Sa...
Pooja 9892124323, Call girls Services and Mumbai Escort Service Near Hotel Sa...
 
Call Girls Bommanahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service ...
Call Girls Bommanahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service ...Call Girls Bommanahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service ...
Call Girls Bommanahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service ...
 
TEST BANK For An Introduction to Brain and Behavior, 7th Edition by Bryan Kol...
TEST BANK For An Introduction to Brain and Behavior, 7th Edition by Bryan Kol...TEST BANK For An Introduction to Brain and Behavior, 7th Edition by Bryan Kol...
TEST BANK For An Introduction to Brain and Behavior, 7th Edition by Bryan Kol...
 
Resumes, Cover Letters, and Applying Online
Resumes, Cover Letters, and Applying OnlineResumes, Cover Letters, and Applying Online
Resumes, Cover Letters, and Applying Online
 
CFO_SB_Career History_Multi Sector Experience
CFO_SB_Career History_Multi Sector ExperienceCFO_SB_Career History_Multi Sector Experience
CFO_SB_Career History_Multi Sector Experience
 
Call Girls Hoodi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hoodi Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Hoodi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hoodi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
 
Call Girls Alandi Road Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Alandi Road Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Alandi Road Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Alandi Road Call Me 7737669865 Budget Friendly No Advance Booking
 
Call Girls Hosur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hosur Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Hosur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hosur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
 

Andrei shakirin rest_cxf

  • 1. Design REST Services with CXF JAX- RS implementation: best practices and lessons learned Andrei Shakirin, Talend ashakirin@talend.com ashakirin.blogspot.com
  • 2. Agenda • REST architectural style • Design of REST API for Syncope domain • Practical aspects of using CXF JAX-RS
  • 3. About Me • Software architect in Talend Team • PMC and committer in Apache CXF and commiter in Apache Syncope projects • Speaker for Java conferences
  • 4. Representational State Transfer • Set of principals and restrictions • HTTP is one instantiation of the REST • The scope of REST architectural style: loosely coupled application
  • 5. REST Principles 1. Everything has an ID 2. Using IDs to link things together: hypermedia and HATEOAS 3. Uniform interface 4. Interaction with resources through the representation 5. Communication is stateless
  • 6. JAX-RS • Specification and Java API • Support in exposing a resource Java class (a POJO) as a web resource • Versions: 1.0, 1.1, 2.0 (client API, asynchronous API, filters and interceptors) • Implementations: Jersey, Apache CXF, Resteasy, …
  • 9. Syncope Domain Model • Users (name, password, dates, attributes) • Roles (name, owners, attributes) • Entitlements (TASK_DELETE, ROLE_CREATE) • Connectors (ConnID bundle: DatabaseTable, SOAP) • External Resources (name, connector, mode, mapping) • Tasks (user/role template, resource, action, status)
  • 10. Resources and URIs: Rules • Resource is anything to be referenced • Normally resources are the nouns • Resources are coarse grained • URIs: descriptive and well structured • URIs: scoping information
  • 12. Resources Types 1. Predefined top-level resources 2. Resource for collection of objects 3. Resource for every exposed objects 4. Resource representing results of algorithms
  • 13. Top Level Resources • Entry point to the API • Home page or list of root entities (collections) URIs: http(s)://api.syncope.org/administration vs http(s)://api.syncope.org/administration/rest/jaxrs/c xf
  • 16. Algorithm Resources FIQL (Feed Item Query Language): /tasks?_s=date=lt=2014-10-31;date=gt=2014- 10-01;(type==sync) /users?failedLogin=true /tasks?type=propagation&status=success
  • 17. Subset of Uniform Interface Will the client will fetch resource of this type? GET /users GET /users/a1b2c3
  • 18. Subset of Uniform Interface Will the client delete resource of this type? DELETE /users/a1b2c3
  • 19. Subset of Uniform Interface Will the client modify resource of this type? PUT /users/a1b2c3
  • 20. Subset of Uniform Interface Will the client create resource of this type? Who is in charge to determine URI: server / client? Server: POST /users 201 Created, Location=/users/a1b2c3 Client: PUT /users/myuser
  • 22. Representations: Media Types Data Format + Parsing rules
  • 23. Representations: Media Types • Standard: text/html application/json application/xml application/xhtml+xml application/x-www-form-urlencoded • Custom: application/user+json application/vnd.mycompany-myformat • Versioned: application/user+json&v2
  • 24. Representations: JAX-RS @Path("users") @Consumes("application/json", "application/xml") @Produces("application/json", "application/xml") public interface UserService { @GET @Produces("application/json;qs=1.0", "application/xml;qs=0.75") Collection<UserTO> list(); @POST @Consumes("application/json;q=1.0", "application/xml;q=0.25") Response create(UserTO userTO); … }
  • 25. CXF: Entity Providers • XML: JAXBElementProvider, Source application/xml, application/*+xml, text/xml • JSON: JSONProvider(Jettison), Jenkins application/json, application/*+json • Multipart: Attachments, MultipartBody multipart/mixed, multipart/related, … • BinaryData application/octet-stream, … • XSLTJaxb, Atom, Dom4J, XMLBeans, …
  • 26. JSON: Jettison vs Jackson CXF JSONProvider (based on Jettison) • Adopt XML structures to JSON (mapped, BadgerFish) • STaX API (XMLStreamWriter, XMLStreamReader) • Flexible and simple (prefixes, root elements, array serialization, unwrapping, XSLT transformations) • Using: for small payloads, if flexibility required <root><child>test</child><child>test</child></root> { "root" : { child : [ "test", "test" ] } }
  • 27. JSON: Jettison vs Jackson Jackson • Not XML oriented • Supports streaming, tree and data binding models • Supports Jackson specific annotations • Using: middle and large payloads, sophisticated class hierarchy @JsonTypeInfo(use=Id.CLASS, include=As.PROPERTY, property="class")
  • 28. Representation: Links • HTML/XHTML <a href="http://mysyncope.com">Syncope</a> • XML <element xlink:href="http://mysyncope.com">Syncope</element> • JSON: ?
  • 29. Links in JSON • JSON HAL (Mike Kelly, IETF draft) • Siren (Kevin Swiber) • Collection + JSON (Mike Amudsen) • Custom format
  • 31. Relations: Many To Many RoleUser role 1 role 2 role N user 1 user 2 user N
  • 32. Relations as Resources Membership user 1 role 2 createdBy timestamp User Role
  • 33. Errors • Choose appropriate HTTP status code • Set short error code for automatic processing • Provide informative and descriptive entity- bodies • Use JAX-RS ExceptionMappers
  • 34. Errors: Code Mapping 1. Decide is it client or server problem (4xx/5xx) 2. Look into HTTP status code spec and select approprite one: • Entity Not Found -> 404 Not Found • Entity Already Exist -> 409 Conflict • IllegalArgumentException -> 400 Bad Request
  • 35. Errors: HTTP Response 404 Not found X-Application-Error-Code: EntityNotFound X-Application-Error-Info: entity=user,id=a1b2c3 { A user ‘a1b2c3‘ is not found in Syncope storage. Check if user name is correct. Refer following link for the details: https://cwiki.apache.org/confluence/pages/viewpage.acti on?pageId=30751185/ }
  • 36. Errors: Batch Operations 207 Multi-Status X-Application-Error-Code: Composite { “message“: “Multiple errors detected“ “errors“: [ { “statusCode“: 409 “errorCode“: “EntityExists“ “ errorMessage “ : “User ‘a1b2c3‘ already exists“ } { “statusCode“: 404 “errorCode“: “NotFound“ “errorMessage“: “User ‘d4e5f6‘ not found“ } … ] }
  • 37. Errors: ExceptionMappers @Provider public class RestServiceExceptionMapper implements ExceptionMapper<SyncopeClientException> { @Override public Response toResponse(final SyncopeClientException ex) { LOG.error("SyncopeClientException thrown by REST method: " + ex.getMessage(), ex); builder = ex.isComposite() ? getSyncopeClientCompositeExceptionResponse(ex.asComposite()) : getSyncopeClientExceptionResponse(ex); return builder.build(); } }
  • 38. Asynchronous Processing • Model operations taking a long time • Provide non-blocking calls on the client side • Provide suspended responses on the server side
  • 39. Asynchronous: Long Operations 202 Accepted Location: /tasks/x7h3b4 POST /tasks HTTP/1.1 { "propagationMode": "TWO_PHASES", "resource": { "href": "/resources/98712" } "status": "NONE", … } GET tasks/x7h3b4 { "propagationMode": "TWO_PHASES", "resource": { "href": "/resources/98712" } "status": "IN_PROGRESS", … }
  • 40. Asynchronous: Client API InvocationCallback<Response> callback = new InvocationCallback { public void completed(Response res) { System.out.println("Request success!"); } public void failed(ClientException e) { System.out.println("Request failed!"); } }; client.target("http://mysyncope.org/tasks") .request() .async() .post(myEntity, callback);
  • 41. Asynchronous: Server API @Path("/connectors") public class AsyncResource { @GET public void asyncGet(@Suspended final AsyncResponse asyncResponse) { new Thread(new Runnable() { @Override public void run() { String result = readConnectors(); asyncResponse.resume(result); } private String readConnectors() { // ... very expensive operation } }).start(); } }
  • 43. Transactional View 1. Create transaction: POST /transactions/tasks-update 201 Created Location: /transactions/tasks-update/89d3 2. Update transaction resources: PUT /transactions/tasks-update/89d3/tasks/f3g4n5 { “userFilter“: “age<=18“ … } PUT /transactions/tasks-update/l8b3n7/tasks/f3g4n5 { “userFilter“: “age>18“ … }
  • 44. Committed Transaction 3. Commit transaction: PUT /transactions/tasks-update/89d3 committed = true 200 OK { “tasks“: [ {“ref“:“/tasks/f3g4n5“} {“ref“:“/tasks/l8b3n7“} ] } GET /tasks/f3g4n5 { “userFilter“: “age<=18“ … } GET /tasks/l8b3n7 { “userFilter“: “age>18“ … }
  • 45. Bean Validation: JAX-RS import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; … @Path("users") @Consumes("application/json", "application/xml") @Produces("application/json", "application/xml") public interface UserService { @GET PagedResult<UserTO> list( @NotNull @Min(1) @QueryParam(PARAM_PAGE) Integer page, @NotNull @Min(1) @QueryParam(PARAM_SIZE) Integer size); @GET @Path("{email}") @Valid UserTO getUser(@Email @PathParam("email") String email); … }
  • 46. Conclusion • Try to follow REST and RESTful HTTP principles by design your application • Consider using JAX-RS 2.0 implementation for Java applications • CXF is nice alternative with active, responsive and cooperative community
  • 47. Links • Apache CXF : http://cxf.apache.org/ http://cxf.apache.org/docs/jax-rs.html • Apache Syncope: http://syncope.apache.org/ • Blogs: http://sberyozkin.blogspot.com http://ashakirin.blogspot.de/ http://aredko.blogspot.de/
  • 48. Validation • JAX-RS 2.0: Bean Validation 1.1 Specification • Implementation: Hibernate Validator (or Apache BVal) • Exception mapper maps: a) Input parameter validation violation -> 400 Bad Request b) Return value validation violation -> 500 Internal Server Error
  • 49. Relations as Resources GET users/a1b2c3 HTTP/1.1 200 OK Content Type: application/linked+json { "href": "/users/a1b2c3", "name": "testUser", … "memberships": { "href": "/memberships?userId=a1b2c3" } }
  • 50. OPTIONS Returns communication options of target resource OPTIONS /users Response: 200 OK Allow: OPTIONS,GET,POST
  • 51. Algorithm Resources FIQL (Feed Item Query Language): /tasks?_s=date=lt=2014-10-31;date=gt=2014- 10-01;(type==sync) /users?failedLogin=true /tasks?type=propagation&status=success /role;name=myRole/entitlements;name=ROLE_ CREATE/
  • 52. Bean Validation: CXF <jaxrs:server address="/"> <jaxrs:inInterceptors> <ref bean="validationInInterceptor" /> </jaxrs:inInterceptors> <jaxrs:outInterceptors> <ref bean="validationOutInterceptor" /> </jaxrs:outInterceptors> <jaxrs:serviceBeans> ... </jaxrs:serviceBeans> <jaxrs:providers> <ref bean="exceptionMapper"/> </jaxrs:providers> </jaxrs:server> <bean id="exceptionMapper" class="org.apache.cxf.jaxrs.validation.ValidationExceptionMapper"/> <bean id="validationProvider" class="org.apache.cxf.validation.BeanValidationProvider" /> <bean id="validationInInterceptor" class="org.apache.cxf.jaxrs.validation.JAXRSBeanValidationInInterceptor"> <property name="provider" ref="validationProvider" /> </bean> <bean id="validationOutInterceptor" class="org.apache.cxf.jaxrs.validation.JAXRSBeanValidationOutInterceptor"> <property name="provider" ref="validationProvider" /> </bean>
  • 53. GET, HEAD • READ semantic • Must be safe and idempotent • Cacheable • Can be conditional or partional GET /users/a1b2c3
  • 54. DELETE • DELETE semantic • Not safe, Idempotent • Resource doesn‘t have to removed immediately • Can return the resource representation or other payload DELETE /users/a1b2c3
  • 55. PUT • Can be used for UPDATE and for CREATE • Not safe, idempotent • Not for partial updates PUT /users/a1b2c3 { “username“:“testUser“ “status“:“active“ … }
  • 56. POST • Can be used to do anything (normally create or update) • Neither safe, no idempotent POST /users { “username“:“testUser“ “status“:“active“ … } Response: 201 Created, Location=/users/a1b2c3
  • 57. Resources and URIs: Rules • Resource is anything to be referenced • Normally resources are the nouns • Resources are coarse grained • URIs: descriptive and well structured • URIs: scoping information
  • 58. Representations: Media Types Data Format + Parsing rules
  • 59. Representations Extension Mappings: • /users/a1b2c3 • /users/a1b2c3.json • /users/a1b2c3.xml