Jax RS
Jax RS
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
• Uses XML messages that follow the Simple Object Access Protocol
<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
– Architectural style
• Uniform interface:
representation.
• Can use JSON as a wire format for request and response entities.
• Resource methods
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)
JsonObject map =
Json.createObjectBuilder().add("ram",40).build();
return map.toString();
}
Send Image
@GET @Produces("image/jpeg")
@Path("/menus/image")
• 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.
30
@PathParam
• Annotation is used to access Value of the variable on request method as a
parameter
• Its invoked as
• http://localhost:2020/RestExample/webapi/customer/101
@Produces Annotation
• @Produces(MediaType.TEXT_PLAIN[, more-types])
• 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.
33
The @Consumes Annotation
• @Consumes(type[, more-types])
• Class level
– All the response methods accept the specified MIME types by
default.
• Method level
– overrides @Consumes annotations applied at the class level.
34
Model
public class Menu {
}
Menu Service
public class MenuService {
private MenuService() {
menus = new HashSet<>();
menus.add(new Menu(1L, "Menu One"));
}
}
throw new Exception("Object not found");
}
Resource
@Path("/rest")
@GET
@Path("/menus")
@Produces("application/json")
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.
WebTarget webTarget =
client.target("http://localhost:8080/user")
.path("guest");
Invoking HTTP Request
• InvocationBuilder
Invocation.Builder invocationBuilder =
webTarget.request(MediaType.APPLICATION_JSON);
Invocation.Builder invocationBuilder =
webTarget.request(MediaType.APPLICATION_JSON);
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);
System.out.println(response.getStatus());
System.out.println(response.readEntity(String.class));
API
Application Programming Interface
• Application Programming Interface
• APIs can be exposed through local files (such as a JAR file in a Java
program, .H file in C/C++ programs, etc.)
– API glues the digital world with its dynamic nature, but it also
allows companies to become more agile by automating
workflows.
• Integration
• Statelessness: