Friday, March 22, 2019

Tutorial 06 – RESTful Web services

PROGRAMMING APPLICATIONS AND FRAMEWORKS                                              
Tutorial 06

1. Compare and contrast Message oriented communication with resource oriented communication 

Message oriented communication is a way of communicating between processes. Messages which correspond to events,are hr basic units of data delivered.
Message oriented communication classify into two parts,

  • synchronous asynchronous
  • Transient or persistent

Synchronous communication - sender block until the request is known to be accepted.
Asynchronous communication - Sender continues immediately after the message sent.
Transient communication - Stores the message until the recipient receives it.
Persistent communication - Messages are stored as long as sending and receiving applications are executing


Resource oriented Communication, uses existing low-level communication libraries to interface networking hardware. As a new intermediate-level communication library it offers a novel approach to system programmers to facilitate the development of a higher-level programming environment that supports the resource-oriented computation paradigm of CoR. RoCL is a communication library that aims to exploit the low-level communication facilities of today’s cluster networking hardware and to merge, via the resource-oriented paradigm, those facilities and the high-level degree of parallelism achieved on SMP systems through multi-threading. The communication model defines three major entities – contexts, resources and buffers – which permit the design of high-level solutions.

2. Discuss the resource based nature of the REST style 


The fundamental concept in any RESTful API is the resource. A resource is an object with a type, associated data, relationships to other resources, and a set of methods that operate on it. It is similar to an object instance in an object-oriented programming language, with the important difference that only a few standard methods are defined for the resource (corresponding to the standard HTTP GET, POST, PUT and DELETE methods), while an object instance typically has many methods.

3. Explain the meaning of “representations” in REST style 

A resource in REST is a similar Object in Object Oriented Programming or it is like an Entity in a Database.Once a resource is identified then its representation is to be decided using a standard format so that the server can send the resource in the above-said format and the client can understand the same format. For example, in RESTful Web Services - First Application a user is a resource which is represented using the following XML format 


<user>
   <id>1</id>
   <name>yas</name>
   <profession>student</profession>
</user>


The same resource can be represented in JSON format as follows

{
   "id":1,
   "name":"yas",
   "profession":"student"
}

REST does not impose any restriction on the format of a resource representation. A client can ask for JSON representation whereas another client may ask for the XML representation of the same resource to the server and so on. It is the responsibility of the REST server to pass the client the resource in the format that the client understands. These are some important points to consider for representation formats,
  • Understandability
  • Completeness
  • Linkability
4. Discuss the constraints of REST, indicating their use in the domain of web 
There are 6 constraints,

1.   Uniform interface : The uniform interface constraint defines the interface between clients and servers. It simplifies and decouples the architecture, which enables each part to evolve independently.

2. Stateless : One client can send multiple requests to the server; however, each of them must be independent, that is, every request must contain all the necessary information so that the server can understand it and process it accordingly. In this case, the server must not hold any information about the client state. Any information status must stay on the client – such as sessions.

3. Cacheable : Because many clients access the same server, and often requesting the same resources, it is necessary that these responses might be cached, avoiding unnecessary processing and significantly increasing performance.

4. Client-Server :The uniform interface separates clients from servers. This separation of concerns means that, for example, clients are not concerned with data storage, which remains internal to each server, so that the portability of client code is improved. Servers are not concerned with the user interface or user state so that servers can be simpler and more scalable. Servers and clients may also be replaced and developed independently, as long as the interface is not altered.

5. Layered system :

6. code on demand :


5. Identify contemporary examples of different types of implementations for the elements of REST style 

The Representational State Transfer (REST) style is an abstraction of the architectural elements within a distributed hypermedia system. REST distinguishes three classes of architectural elements, they are:
  • Connectors : Connectors represent the activities involved in accessing resources and transferring representations. Roles provide an interface for components to implement.
        Type & Ex:-
    • Client - HTTP library
    • Server - Web Server API
    • Cache - Browser cache
    • Resolver - bind (DNS lookup library)
    • Tunnel - SOCKS, SSL after HTTP CONNECT
  • Components :  In REST, the various software that interacts with one another are called components.
        Types & Ex:-
    • Origin Server - Apache httpd, Microsoft IIS
    • User Agent - Browser like Netscape Navigator etc
    • Gateway - Squid, CGI, Reverse Proxy
    • Proxy - CERN Proxy, Netscape Proxy, Gauntlet
  • Data Elements :The 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.
        Types & Ex:-
    • Resource - Title of a movie from IMDb, A Flash movie from YouTube, Images from Flickr etc
    • Resource Identifier - Standardized format of URI:scheme://host:port/path?
    • Resource metadata - Source link, vary
    • Representation - Sequence of bytes, HTML document, archive document, image document
    • Representation metadata - Headers (media-type)
    • Control data - If-Modified-Since, If-Match

6. Explain how to define the API of RESTful web services using RESTful URLs 


Under REST principles, a URL identifies a resource. The following URL design patterns are considered REST best practices,


  • URLs should include nouns, not verbs.
  • Use plural nouns only for consistency.
  • Use HTTP methods to operate on these resources.
  • Use HTTP response status code to represent the outcome of operations on resources.

7. Discuss the pros and cons of using MVC for RESTful web service development, indicating the application of MVC in RESTful web service design 


  • In Spring MVC, a controller can handle the requests for all HTTP methods, which is a backbone of RESTful web services. For example, you can handle a GET method to perform read operations, POST methods to create resources, PUT methods to update resources, and DELETE methods to remove resources from the server.
  • Another key aspect of RESTful web services is Representation, meaning the same resource can be represented in different formats, i.e. JSON, XML, HTML, etc. Thankfully, Spring provides several view implementations and views resolvers to render data as JSON, XML, and HTML.
Advantages:-
  • Faster development process
  • Support for asynchronous technique
  • Modification does not affect the entire model
  • MVC model returns the data without formatting
  • SEO friendly Development platform
Disadvantages:-
  • Increased complexity
  • Need multiple programmers
  • Knowledge on multiple technologies is required.
8. Discuss the JAX-RS API and its implementations 

JAX-RS stands for JAVA API for RESTful Web Services. JAX-RS is a JAVA based programming language API and specification to provide support for created RESTful Web Services. Its 2.0 version was released on the 24th May 2013. JAX-RS uses annotations available from Java SE 5 to simplify the development of JAVA based web services creation and deployment. It also provides supports for creating clients for RESTful Web Services.

Hello.Java

  1. package com.javatpoint.rest;  
  2. import javax.ws.rs.GET;  
  3. import javax.ws.rs.Path;  
  4. import javax.ws.rs.Produces;  
  5. import javax.ws.rs.core.MediaType;  
  6. @Path("/hello" 
  7. public class Hello {  
  8.   // This method is called if HTML and XML is not requested  
  9.   @GET  
  10.   @Produces(MediaType.TEXT_PLAIN)  
  11.   public String sayPlainTextHello() {  
  12.     return "Hello Jersey Plain";  
  13.   }  
  14.   // This method is called if XML is requested  
  15.   @GET  
  16.   @Produces(MediaType.TEXT_XML)  
  17.   public String sayXMLHello() {  
  18.     return "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>";  
  19.   }  
  20.   
  21.   // This method is called if HTML is requested  
  22.   @GET  
  23.   @Produces(MediaType.TEXT_HTML)  
  24.   public String sayHtmlHello() {  
  25.     return "<html> " + "<title>" + "Hello Jersey" + "</title>"  
  26.         + "<body><h1>" + "Hello Jersey HTML" + "</h1></body>" + "</html> ";  
  27.   }  
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  3. xmlns="http://java.sun.com/xml/ns/javaee"   
  4. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  5. http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"   
  6. id="WebApp_ID" version="3.0">  
  7.  <servlet>  
  8.     <servlet-name>Jersey REST Service</servlet-name>  
  9.     <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>  
  10.     <init-param>  
  11.         <param-name>jersey.config.server.provider.packages</param-name>  
  12.         <param-value>com.javatpoint.rest</param-value>  
  13.     </init-param>  
  14.     <load-on-startup>1</load-on-startup>  
  15.   </servlet>  
  16.   <servlet-mapping>  
  17.     <servlet-name>Jersey REST Service</servlet-name>  
  18.     <url-pattern>/rest/*</url-pattern>  
  19.   </servlet-mapping>  
  20. </web-app>
9. Identify the annotations in JAX-RS, explaining their use 

  • @GET - Annotate your Get request methods with @GET.
    @GET
    public String getHTML() {
      ...
    }

    @Produces - @Produces annotation specifies the type of output this method (or web service) will produce.
    @GET
    @Produces("application/json")
    public Contact getJSON() {
      ...
    }

    @Path - annotation specify the URL path on which this method will be invoked.
    @GET
    @Produces("application/xml")
    @Path("xml/{firstName}")
    public Contact getXML() {
      ...
    }

    @PathParam - We can bind REST-style URL parameters to method arguments using @PathParam annotation as shown below.
    @GET
    @Produces("application/json")
    @Path("json/{firstName}")
    public Contact getJSON(@PathParam("firstName") String firstName) {
      Contact contact = contactService.findByFirstName(firstName);
      return contact;
    }

    @QueryParam - Request parameters in query string can be accessed using @QueryParam annotation as shown below.
    @GET
    @Produces("application/json")
    @Path("json/companyList")
    public CompanyList getJSON(@QueryParam("start") int start, @QueryParam("limit") int limit) {
      CompanyList list = new CompanyList(companyService.listCompanies(start, limit));
      return list;
    }

    @POST - Annotate POST request methods with @POST.
    @POST
    @Consumes("application/json")
    @Produces("application/json")
    public RestResponse<Contact> create(Contact contact) {
    ...
    }

10. Explain the use and importance of “media type” in JAX-RS 

Resources have representations. A resource representation is the content in the HTTP message that is sent to, or returned from the resource using the URI. Each representation that a resource supports has a corresponding media type. For example, if a resource is going to return content formatted as XML, you can use application/xml as the associated media type in the HTTP message.

JAX-RS provides @Consumes and @Produces annotations to declare the media types that are acceptable for a resource method to read and write.

In the retrieveSpecificBookInformation method example that follows, there is no request entity that is read. However, there is a response object that is returned. This object wraps a JAXB object that contains the entity information. Adding the @Produces annotation on the resource method with a media type of application/xml indicates that the resource method always returns an XML representation with a media type of application/xml.



package com.javapapers.webservices.rest.jersey; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Path("/helloworld") public class HelloWorld { @GET @Produces(MediaType.TEXT_PLAIN) public String sayPlainTextHello() { return "Hello World RESTful Jersey!"; } @GET @Produces(MediaType.TEXT_XML) public String sayXMLHello() { return "<?xml version=\"1.0\"?>" + "<hello> Hello World RESTful Jersey" + "</hello>"; } @GET @Produces(MediaType.TEXT_HTML) public String sayHtmlHello() { return "<html> " + "<title>" + "Hello World RESTful Jersey" + "</title>" + "<body><h1>" + "Hello World RESTful Jersey" + "</body></h1>" + "</html> "; } }


refs

01• https://studylib.net/doc/8093860/message--and-stream-oriented-communication

02https://whatis.techtarget.com/definition/resource-oriented-architecture-ROA

03https://restful-api-design.readthedocs.io/en/latest/resources.html

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

05• https://apiguide.readthedocs.io/en/latest/build_and_publish/use_RESTful_urls.html

06https://www.dineshonjava.com/what-is-rest-and-rest-architecture-and-rest-constraints/

07https://restfulapi.net/rest-architectural-constraints/

08http://mrbool.com/rest-architectural-elements-and-constraints/29339

09https://hackernoon.com/restful-api-design-step-by-step-guide-2f2c9f9fcdbf

10https://www.ibm.com/support/knowledgecenter/cs/SSEQTP_8.5.5/com.ibm.websphere.base.doc/ae/twbs_jaxrs_defresource_mediatype.html

No comments:

Post a Comment

Tutorial 10 – Client-side development 2 - RiWAs

PROGRAMMING APPLICATIONS AND FRAMEWORKS                                                  Tutorial 10 Distinguish the term “Rich Internet...