Thursday, March 21, 2019

Server-side Development II


Message-Oriented Communication

Message-oriented communication is a way of communicating between processes. Messages, which correspond to events, are the basic units of data delivered. Tanenbaum and Steen classified message-oriented communication according to two factors---synchronous or asynchronous communication, and transient or persistent communication. In synchronous communication, the sender blocks waiting for the receiver to engage in the exchange. Asynchronous communication does not require both the sender and the receiver to execute simultaneously. So, the sender and recipient are loosely-coupled. The amount of time messages are stored determines whether the communication is transient or persistent. Transient communication stores the message only while both partners in the communication are executing. If the next router or receiver is not available, then the message is discarded. Persistent communication, on the other hand, stores the message until the recipient receives it.


________________________________________________________________________________

Representational State Transfer


Representations in REST style

Representations are how resources get manipulated and presented. Part of the resource state is transferred between client and server

Suppose a client makes a GET request to /programmers/Namespacinator and gets back this JSON response:

{
    "nickname": "Namespacinator",
    "powerLevel": 5
}
This is just a representation of the programmer resource. It happens to be in JSON, but the server could have represented the programmer in other ways, like in XML, HTML or even in JSON with a different format.


Constraints

Client-server
• The REST is for explicitly for networked distributed systems, which are based on the client-server style.


Layered System
• A client doesn’t need to know whether it is connected directly to the end server, or to an intermediary along the way.
• Intermediary servers may improve system scalability by enabling load-balancing and by providing shared caches.
• Layers may also enforce security policies.


Stateless
• One client can send multiple requests to the server.
• Each request is independent.
• Every request must contain all the necessary information so that the server can understand it and process it accordingly.
• The server must not hold any information about the client state.
• Any state information must stay on client – such as sessions.


Cacheable
• As many clients access the same server, often they may request the same resources.
• it is necessary that these responses might be cached, avoiding unnecessary processing, which may affect performance.


Code-On-Demand (Optional)
• This allows the customer to run some code on demand, that is, extend part of server logic to the client, either through an applet or scripts.


Uniform Interface
•Defines the interface between clients and servers.
• It simplifies and decouples the architecture, which enables each part to evolve independently
• REST is defined by four interface constraints:
                                             • identification of resources
                                             • manipulation of resources through representations
                                             • self-descriptive messages
                                             • hypermedia as the engine of application state


ELEMENTS OF REST STYLE


Components

•Software that interacts with one another.
•Communicate by transferring representations of resources through a standard interface rather than operating directly upon there source itself.
•Used to access, provide access to, or mediate access to resources.






Connector

• represent activities involved in accessing resources and transferring representations.
•REST encapsulates different activities of accessing and transferring representations into different connector types.
•connectors are abstract interfaces for component communication, enhancing simplicity by hiding
the underlying implementation of resources and communication mechanisms.






Data
• key aspect of REST is the state of the data elements, its components communicate by transferring
representations of the current or desired state of data elements.
•REST manages data in the following ways:
                        • render the data(traditional client-server style) where it is
                          located and send a fixed-format image to the recipient,
                        • encapsulate the data(mobile object style) with a rendering
                          engine and send both to the recipient or,
                        • send the raw data to the recipient along with metadata
                          that describes the data type, so that the recipient can
                          choose their own rendering engine.













RESTful API


A RESTful API is an application program interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data.

A RESTful API -- also referred to as a RESTful web service -- is based on representational state transfer (REST) technology, an architectural style and approach to communications often used in web services development.


REST technology is generally preferred to the more robust Simple Object Access Protocol (SOAP) technology because REST leverages less bandwidth, making it more suitable for internet usage. An API for a website is code that allows two software programs to communicate with each another . The API spells out the proper way for a developer to write a program requesting services from an operating system or other application.


The REST used by browsers can be thought of as the language of the internet. With cloud use on the rise, APIs are emerging to expose web services. REST is a logical choice for building APIs that allow users to connect and interact with cloud services. RESTful APIs are used by such sites as Amazon, Google, LinkedIn and Twitter.
How RESTful APIs work

A RESTful API breaks down a transaction to create a series of small modules. Each module addresses a particular underlying part of the transaction. This modularity provides developers with a lot of flexibility, but it can be challenging for developers to design from scratch. Currently, the models provided by Amazon Simple Storage Service, Cloud Data Management Interface and OpenStack Swift are the most popular.

A RESTful API explicitly takes advantage of HTTP methodologies defined by the RFC 2616 protocol. They use GET to retrieve a resource; PUT to change the state of or update a resource, which can be an object, file or block; POST to create that resource ; and DELETE to remove it.


Request = URL + HTTP Verbs (GET,POST,PUT,DELETE)
• URL is the key technique in RESTful communication
• The API of the RESTful service is a set of URLs
• The resource is determined by the URL segments
• The CRUD operations are determined by the HTTP verb


Operation = Read , Verb = GET
•Collection
•SLIIT.com/students/
•SLIIT.com/students/DS
•SLIIT.com/students/DS/IT123456/posts

•Single item
•SLIIT.com/students/IT123456
•Blog.com/posts/pid15948

•Multiple items
•SLIIT.com/students/IT123456;IT456456;IT998877


Operation = Create , Verb = POST
•Single item (single item in the payload)
•SLIIT.com/students/
•SLIIT.com/students/DS
•SLIIT.com/students/DS/IT123456/posts

•Multiple items
•Same URL, items will be in the payload


Operation = Update , Verb = PUT
•Collection (data in the payload)
•SLIIT.com/students/
•SLIIT.com/students/DS
•SLIIT.com/students/DS/IT123456/posts

•Single item
•SLIIT.com/students/IT123456
•Blog.com/posts/pid15948

•Multiple items
•SLIIT.com/students/IT123456;IT456456;IT998877


Operation = Delete , Verb = DELETE
•Collection
•SLIIT.com/students/
•SLIIT.com/students/DS
•SLIIT.com/students/DS/IT123456/posts

•Single item
•SLIIT.com/students/IT123456
•Blog.com/posts/pid15948

•Multiple items
•SLIIT.com/students/IT123456;IT456456;IT998877


With REST, networked components are a resource you request access to -- a black box whose implementation details are unclear. The presumption is that all calls are stateless; nothing can be retained by the RESTful service between executions.

Because the calls are stateless, REST is useful in cloud applications. Stateless components can be freely redeployed if something fails, and they can scale to accommodate loadchanges. This is because any request can be directed to any instance of a component; there can be nothing saved that has to be remembered by the next transaction. That makes REST preferred for web use, but the RESTful model is also helpful in cloud services because binding to a service through an API is a matter of controlling how the URL is decoded. Cloud computing and microservices are almost certain to make RESTful API design the rule in the future.


When you are designing REST API services, you have to pay attention to resources, those are defined by URIs.

Each resource in a service or services you are building will have at least one URI identifying it. It's best when that URI makes sense and adequately describes the resource. URIs should follow a predictable, hierarchical structure to enhance understandability and, therefore, usability: predictable in the sense that they're consistent, hierarchical in the sense that data has structure—relationships.



MVC with RESTful web service Development


























________________________________________________________________________________

JAX-RS




JAX-RS is nothing more than a specification, a set of interfaces and annotations offered by Java EE. And then, of course, we have the implementations; some of the more well known are RESTEasy and Jersey.

Also, if you ever decide to build a JEE-compliant application server, the guys from Oracle will tell you that, among many other things, your server should provide a JAX-RS implementation for the deployed apps to use. That’s why it’s called Java Enterprise Edition Platform.

Deployables can and should be very thin, letting the application server provide the needed libraries. This applies when developing a RESTful API as well: the final artifact should not contain any information about the used JAX-RS implementation.



If you want to start playing with JAX-RS, the shortest path is: have a Maven webapp project with the following dependency in the pom.xml:
1
2
3
4
5
6
<dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>7.0</version>
    <scope>provided</scope>
</dependency>
We’re using JavaEE 7 since there are already plenty of application servers implementing it. That API jar contains the annotations that you need to use, located in package javax.ws.rs. Why is the scope “provided”? Because this jar doesn’t need to be in the final build either – we need it at compile time and it is provided by the server for the run time.
After the dependency is added, we first have to write the entry class: an empty class which extends javax.ws.rs.core.Application and is annotated with javax.ws.rs.ApplicationPath:
1
2
3
@ApplicationPath("/api")
public class RestApplication extends Application {
}
We defined the entry path as being /api. Whatever other paths we declare for our resources, they will be prefixed with /api.
Next, let’s see a resource:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@Path("/notifications")
public class NotificationsResource {
    @GET
    @Path("/ping")
    public Response ping() {
        return Response.ok().entity("Service online").build();
    }
    @GET
    @Path("/get/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getNotification(@PathParam("id") int id) {
        return Response.ok()
          .entity(new Notification(id, "john", "test notification"))
          .build();
    }
    @POST
    @Path("/post/")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response postNotification(Notification notification) {
        return Response.status(201).entity(notification).build();
    }
}
We have a simple ping endpoint to call and check if our app is running, a GET and a POST for a Notification (this is just a POJO with attributes plus getters and setters).
Deploy this war on any application server implementing JEE7 and the following commands will work:
1
2
3
4
5
6
7
curl http://localhost:8080/simple-jaxrs-ex/api/notifications/ping/
curl http://localhost:8080/simple-jaxrs-ex/api/notifications/get/1
curl -X POST -d '{"id":23,"text":"lorem ipsum","username":"johana"}'
  http://localhost:8080/simple-jaxrs-ex/api/notifications/post/
  --header "Content-Type:application/json"
Where simple-jaxrs-ex is the context-root of the webapp.
This was tested with Glassfish 4.1.0 and Wildfly 9.0.1.Final. Please note that the last two commands won’t work with Glassfish 4.1.1, because of this bug. It is apparently a known issue in this Glassfish version, regarding the serialization of JSON (if you have to use this server version, you’ll have to manage JSON marshaling on your own)

Just keep in mind that JAX-RS is a powerful API and most (if not all) of the stuff that you need is already implemented by your web server. No need to turn your deployable into an unmanageable pile of libraries.
This write-up presents a simple example and things might get more complicated. For instance, you might want to write your own marshalers. When that’s needed, look for tutorials that solve your problem with JAX-RS, not with Jersey, Resteasy or other concrete implementation. It’s very likely that your problem can be solved with one or two annotations.


Annotations in JAX-RS





@GET  :-   The @GET annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP GET requests.

@Produces :-  specifies the type of output this method (or web service) will produce.

@Path :-  specify the URL path on which this method will be invoked.

@PathParam :-  Bind REST-style URL parameters to method arguments.

@QueryParam  :-  Request parameters in query string can be accessed.

@POST :-  The @POST annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP POST requests.

@Consumes :-  used to specify the MIME media types a REST resource can consume.

@FormParam :-  read parameters sent in POST requests directly.

@PUT :-  The @PUT annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP PUT requests.

@DELETE  :-  The @DELETE annotation is a request method designator and corresponds to the similarly named HTTP method. The Java method annotated with this request method designator will process HTTP DELETE requests.


________________________________________________________________________________


References

https://symfonycasts.com/screencast/rest/rest

http://www.techferry.com/articles/RESTful-web-services-JAX-RS-annotations.html

https://www.baeldung.com/jax-rs-spec-and-implementations

https://searchmicroservices.techtarget.com/definition/RESTful-API



No comments:

Post a Comment

Client - side Development II - RiWAs

Key features of RiWAs Direct interaction:  In RiWAs, users can interact directly with page elements through editing or drag-and-drop too...