0% found this document useful (0 votes)
10 views58 pages

Jax RS

The document provides an overview of SOAP and REST web services, detailing their communication methods, architectural principles, and implementation techniques. It explains the structure of SOAP messages, the use of JAX-RS for RESTful services, and the development of client applications for these services. Additionally, it covers best practices for designing URIs, handling requests and responses, and managing resources in a RESTful architecture.

Uploaded by

Harish R
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views58 pages

Jax RS

The document provides an overview of SOAP and REST web services, detailing their communication methods, architectural principles, and implementation techniques. It explains the structure of SOAP messages, the use of JAX-RS for RESTful services, and the development of client applications for these services. Additionally, it covers best practices for designing URIs, handling requests and responses, and managing resources in a RESTful architecture.

Uploaded by

Harish R
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 58

INTRODUCTION TO SOAP WS

Web Services
• A way for two machines to communicate with each other over a
network.
• A client and server applications that communicate over HTTP or
HTTPS
– A standard means of interoperating between software
applications running on a variety of platforms and frameworks.
– Can be combined in a loosely coupled way to achieve complex
operations.
Types of Web Services
• A service is a software component provided through a network-
accessible endpoint.
• The service consumer and provider use messages to exchange
request and response
– Done by a self-containing documents with very few assumptions about
the technological capabilities of the receiver.

• Can be implemented as

• “big” web services and “RESTful” web services.


“Big” Web Services

• Also known as SOAP Web Services

• Uses XML messages that follow the Simple Object Access Protocol

• JAX-WS provides the functionality

• Contains a machine-readable description of the operations offered


by the service
– Web Services Description Language (WSDL), an XML language for
defining interfaces syntactically.
XML MESSAGING-SOAP
Simple Example

<Envelope>
<Header>
<transId>1234</transId>
</Header>
<Body>
<Add>
c = Add(a, b)
<a>3</a>
<b>4</b>
</Add>
</Body>
</Envelope>
System Flow (HTTP)

<Envelope>
<Header>
<transId>1234</transId>
</Header>
<Body>
<Add>
<a>3</a>
<b>4</b>
</Add>
</Body>
</Envelope>

<Envelope>
<Header>
<transId>1234</transId>
</Header>
<Body>
<AddResponse>
<c>7</c>
</AddResponse>
</Body>
</Envelope>
Actual SOAP Request

<SOAP-ENV:Envelope
xmlns:SOAP-ENV=“http://schemas.xmlsoap.org/soap/envelope/”
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/”>
<SOAP-ENV:Header>
<t:transId xmlns:t=“http://a.com/trans”>1234</t:transId>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
<m:Add xmlns:m=“http://a.com/Calculator”>
<a xsi:type=“integer”>3</a>
<b xsi:type=“integer”>4</b>
</m:Add>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Actual SOAP Response

<SOAP-ENV:Envelope
xmlns:SOAP-ENV=“http://schemas.xmlsoap.org/soap/envelope/”
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/”>
<SOAP-ENV:Header>
<t:transId xmlns:t=“http://a.com/trans”>1234</t:transId>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
<m:AddResponse xmlns:m=“http://a.com/Calculator”>
<c xsi:type=“integer”>7</c>
</m:AddResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
REST WebService

Roy Thomas Fielding


REST
• Introduced and defined in 2000 by Roy Fielding

• Defines a set of architectural principles to design Web services


– Focusses system’s resources

– How resource states are addressed

– How its transferred over HTTP

– Clients written in different languages.

• A predominant Web service design model.

• Displaced SOAP- and WSDL-based interface design because of its


simpler style to use.
RESTful Web Service
• RESTful web services are services that are built to work best on the
web.
• Representational State Transfer (REST)

– Architectural style

– Specifies constraints, such as the uniform interface

– Has feature that enable services to work best on the Web.


REST Service
RESTful Web Service
• Data and functionality are considered resources

– Resources are accessed using Uniform Resource Identifiers


(URIs), typically links on the web.
• In the REST architecture style, clients and servers exchange
representations of resources using a standardized interface and
protocol.
• RESTful applications are simple, lightweight, and have high
performance.
• Service are mapped to the four main HTTP methods
– create, retrieve, update, and delete.
RESTful Principles
• RESTful applications are simple, lightweight, and fast

• Resource identification through URI

– A RESTful web service exposes a set of resources that identify


the targets of the interaction with its clients.
– Resources are identified by URIs, which provide a global
addressing space for resource and service discovery.
– A URI is of the following format
• http://localhost:8080/hotelmanagement/rest/hotels
Designing a URI
• Use Plural Noun
– Use plural noun to define resources.

• Avoid using spaces


– Use underscore (_) or hyphen (-) when using a long resource name.

• Use lowercase letters


– Good practice to keep the url in lower case letters only.

• Use HTTP Verb


– HTTP Verb like GET, PUT and DELETE to do the operations on the
resource.
– It is not good to use operations name in the URI.
RESTful Principles

• Uniform interface:

– Resources are manipulated using a fixed set of four create,

read, update, delete operations:

– PUT, GET, POST, and DELETE.

– GET retrieves the current state of a resource in some

representation.

– POST transfers a new state onto a resource.


RESTful Principles
• Self-descriptive messages

– Resources are decoupled from their representation

– Resource content can be accessed in a variety of formats, such


as HTML, XML, plain text, PDF, JPEG, JSON, and others.
– Metadata about the resource is made available and used

• Caching, Errors, negotiate the appropriate representation


format, and perform authentication or access control.
RESTful Principles
• Stateful interactions through hyperlinks

– Every interaction with a resource is stateless

– Request messages are self-contained.

– Stateful interactions are based on the concept of explicit state


transfer.
– Several techniques exist to exchange state, such as URI
rewriting, cookies, and hidden form fields.
– State can be embedded in response messages to point to valid
future states of the interaction.
JAX-RS
• JAVA API for RESTful Web Services.
– JAVA based programming language API and specification
– Provides support for creating RESTful Web Services.
– Uses annotations to simplify the development and deployment.
– Provides Supports for creating clients for RESTful Web Services.
– Coordinates with the web server or container to make resources available via URLs
– Convert the HTTP requests into Java objects, and to convert Java object resource
representations into HTTP responses.
• Marshalling and unmarshalling requests and responses,
Jersey
• Jersey is the open source, production quality, JAX-RS

• Reference Implementation for building RESTful Web services.

• Can be integrated with a number of different containers and HTTP


servers.
• Can be combined with the Project Grizzly HTTP server.

– Can also be integrated Tomcat, WebLogic, or WebSphere.


JERSEY
• Provides both server-side and Client side API and implementation

• Includes support for XML serialization of JAXB bean

• Can use JSON as a wire format for request and response entities.

• It is hosted in a Maven repository but can be used without using


Maven.

• Jersey and Grizzly are under active development, so you will


probably find newer versions of these jars available
Grizzly HTTP Server
• A multi-protocol framework built on top of Java NIO.

• Simplifies the development of robust and scalable servers.

• Jersey enables support for using Grizzly as a plain vanilla HTTP


container
• Starting a Grizzly server is one of the most lightweight and easy
ways how to expose a functional RESTful services application.
DEVELOPING JAX-RS
APPLICATION
Resource
• Resource are classes , simple POJOs annotated with @Path

– Can also have method annotated with @Path

• The annotation's value is a relative URI path.

• Resource methods

– Methods of a resource class annotated with a resource method


designator.
– Method designator with annotation such
as @GET, @PUT, @POST, @DELETE
Maven Project
• Create a New Maven Project
• In the Filter type jersey-quickstart-grizzly
• Fill in the required details and a project is created
• In the pom.xml uncomment the jersey-media support dependency
• Can Execute as a Stand alone Java Application
• Can also use the maven goal exec:java
Main Class
public class Main {

public static HttpServer startServer() {


public static final String BASE_URI =
"http://localhost:8080/";

ResourceConfig rc = new
ResourceConfig().packages("com.example.demo.");

GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);
}
public static void main(String[] args) throws IOException {
HttpServer server = startServer();
System.in.read();
server.stop();
}
}
Send a JSON Response
• import javax.json.Json;
• import javax.json.JsonObject;

@GET

@Path("/user")

@Produces(MediaType.APPLICATION_JSON)

public String getMessage(){

JsonObject map =
Json.createObjectBuilder().add("ram",40).build();

return map.toString();

}
Send Image
@GET @Produces("image/jpeg")

@Path("/menus/image")

public File getImageRepresentation() {

return new File( “e://Pictures//menu.jpg");

• Jersey takes the returned File object and uses its contents as the
response entity which it marks as image/jpeg.

• Don't have to write code to read the contents of files and return
them as byte arrays or strings.
Response Builder
• Used to build Response instances that contain metadata instead of
or in addition to an entity.

• Obtained via static methods of the Response class,

• public abstract Response build()

– Create a Response instance from the current ResponseBuilder.

– The builder is reset to a blank state equivalent to calling the ok method.

30
@PathParam
• Annotation is used to access Value of the variable on request method as a
parameter

• Binds the value of a path segment to a resource method parameter.

• Used to inject values from the URL into a method parameter.

• getCustomerById(@PathParam("customerId") int id)

• Its invoked as

• http://localhost:2020/RestExample/webapi/customer/101
@Produces Annotation
• @Produces(MediaType.TEXT_PLAIN[, more-types])

– Used to specify the MIME media types or representations a


resource can produce and send back to the client.
– Can be Applied Both at the Class and Method Level

• Class level
– All the methods in a resource can produce the specified MIME
types by default.
• Method Level
– Overrides any @Produces annotations applied at the class
level.

• 406 Not Acceptable


– Returned when methods matching MIME type is not found in a
client request,
32
Server Response
• A server response in REST can be one of the following

• JSON (JavaScript Object Notation).


– Easy to parse in JavaScript clients and in other languages, too).
• CSV (comma-separated values)
– CSV is more compact;
• XML
– XML is easy to expand (clients should ignore unfamiliar fields)
and is type-safe;
• HTML
– Response is a human-readable document;

33
The @Consumes Annotation
• @Consumes(type[, more-types])

– used to specify which MIME media types of representations a


resource can accept, or consume, from the client.

• Class level
– All the response methods accept the specified MIME types by
default.

• Method level
– overrides @Consumes annotations applied at the class level.

• HTTP 415 (“Unsupported Media Type”) .


– Returned when methods can not respond to the requested
MIME type

34
Model
public class Menu {

private Long id;

private String name;

}
Menu Service
public class MenuService {

private static MenuService instance = new


MenuService();
private static HashSet menus;

private MenuService() {
menus = new HashSet<>();
menus.add(new Menu(1L, "Menu One"));
}

public static MenuService getInstance() {


return instance;
}
Add and Find All
public void add(Menu menu) {
menus.add(menu);
}

public List getAll() {


return new ArrayList(menus);
}
Read
public Menu get(Long id) throws Exception {
Iterator it = menus.iterator();
while (it.hasNext()) {
Menu curr = (Menu) it.next();
if (curr.getId() == id)
return curr;
}
throw new Exception("Object not found");
}
Delete
public boolean delete(Long id) throws Exception {
Iterator it = menus.iterator();
while (it.hasNext()) {
Menu curr = (Menu) it.next();
if (curr.getId() == id) {
it.remove();
return true;
}
}
throw new Exception("Object not found");
}
Update
public Menu update(Long id, String update) throws
Exception {
Iterator it = menus.iterator();
while (it.hasNext()) {
Menu curr = (Menu) it.next();
if (curr.getId() == id) {
curr.setName(update);
return curr;
}

}
throw new Exception("Object not found");
}
Resource
@Path("/rest")

public class MenuResource {

MenuService service = MenuService.getInstance();

@GET

@Path("/menus")

@Produces("application/json")

public List<Menu> getMenus() {

return service.getAll();

}
Read
@GET
@Path("/menus/{menu_Id}")
@Produces("application/json")
public Response getMenu(@PathParam("menu_Id") Long
menuId) {
try {
return Response.ok(service.get(menuId)).build();
} catch (Exception e) {
return
Response.serverError().status(HttpStatus.BAD_REQUEST_40
0.getStatusCode(), e.getMessage()).build();
}
}
Save
@POST
@Path("/menus")
@Produces("application/json")
public Response add(Menu entity) {
service.add(entity);
return
Response.ok(entity).status(HttpStatus.CREATED_201.getStatu
sCode(), "Created").build();
}
Update
@PUT
@Path("/menus/{menu_Id}")
@Produces("application/json")
public Response update(@PathParam("menu_ID") Long menuId,
Menu entity) {
try {
return
Response.ok(service.update(menuId,entity.getName())).build();
} catch (Exception e) {
return
Response.serverError().status(HttpStatus.BAD_REQUEST_400.ge
tStatusCode(), e.getMessage()).build();
}
}
Delete
@DELETE
@Path("/menus/{menu_Id}")
@Produces("application/json")
public Response delete(@PathParam("menu_Id") Long menuId) {
try {
service.delete(menuId);
return
Response.ok().status(HttpStatus.OK_200.getStatusCode()).build();
} catch (Exception e) {
return
Response.serverError().status(HttpStatus.BAD_REQUEST_400.getSta
tusCode(), e.getMessage()).build();
}
}
DEVELOPING CLIENT FOR
JAX-RS APPLICATION
Jax-RS Client Module
• Client Builder
– Main entry point to the client API used to bootstrap Client instances.

• Client
– Client is the main entry point to the fluent API used to build and execute
client requests in order to consume
– Object that Manage the client-side communication infrastructure.

Client client = ClientBuilder.newClient();


Web Target
• Obtained through the reference of the Client
– Its represents a resource target identified by the resource URI.

• Client Object contains overloaded target(...) methods

– These methods are used for creation of WebTarget instance.


– Takes the uri of the target web resource passed as a String

WebTarget webTarget =

client.target("http://localhost:8080/user")

.path("guest");
Invoking HTTP Request
• InvocationBuilder

– Used to start building a new HTTP request invocation

– Created using one of the request(...) methods that are available


on WebTarget.
– It can define the media type of the requested resource.

– Takes the request specific parameters.

– Can also setup headers

Invocation.Builder invocationBuilder =
webTarget.request(MediaType.APPLICATION_JSON);

Response response = invocationBuilder.get();


Get From REST API
Client client = ClientBuilder.newClient();
WebTarget webTarget =
client.target("http://localhost:8080/user").path("guest");

Invocation.Builder invocationBuilder =
webTarget.request(MediaType.APPLICATION_JSON);

Response response = invocationBuilder.get();

User user = response.readEntity(User.class);

System.out.println(user);
Posting To Rest API
Client client = ClientBuilder.newClient();

WebTarget webTarget =
client.target("http://localhost:8080/users").path(“guest");

Invocation.Builder invocationBuilder =
webTarget.request(MediaType.APPLICATION_JSON);

User user = new User(1, "Darshan");

Response response = invocationBuilder.post(Entity.entity(user,


MediaType.APPLICATION_JSON));

System.out.println(response.getStatus());
System.out.println(response.readEntity(String.class));
API
Application Programming Interface
• Application Programming Interface

– Set of definitions and protocols that allow one application to


communicate with another application.

• APIs can be exposed through local files (such as a JAR file in a Java
program, .H file in C/C++ programs, etc.)

– Two local applications can communicate with each other.

– May not require a network as the two applications are


communicating within a single device.
Need for API
• Automation

– Automation accelerates API testing, Increases efficiency.

– API glues the digital world with its dynamic nature, but it also
allows companies to become more agile by automating
workflows.
• Integration

– Integration of platforms and applications can be done using API


to leverage seamless communication.
– Movement of data, facilitating companies to automate workflows
and improve workplace collaboration.
Need for API
• Efficiency

– Efficiency increases with decreasing human intervention.

– Providing API access prevents duplication of content,

– Greater flexibility for companies to spend time in quality


innovation.
• Security

– Security is an additional benefit because API supplements an


extra layer of protection between your data and server.
– Can strengthen their security by using tokens, signatures, and
transport layer security (TLS) encryption.
Rest API
REST API
• REST APIs are a standardized architecture abides by the following rules:

• Statelessness:

– Systems aligning with the REST paradigm are bound to become


stateless.
• Cacheable:

– Cache helps servers to mitigate some constraints of


statelessness.
– Caching enhances the performance on the client-side but also
scales significant results on the server-side.
REST API
• Decoupled:

– Client and server applications are decoupled from each other.

– Client application just need to know URI of the requested


resource.
• Layered:

– A Layered system makes a REST architecture scalable.

– Neither Client nor Server identifies its communication with end


applications or an intermediary.

You might also like