Java Login

About javalogin.com

Hello guys,
javalogin.com is for Java and J2EE developers, all examples are simple and easy to understand 

It is developed and maintained by Vaibhav Sharma. The views expressed on this website are his own and do not necessarily reflect the views of his former, current or future employers. I am professional Web development. I work for an IT company as Senior Consultant. Primary I write about spring, hibernate and web-services. I am trying to present here new technologies.


     << Previous
Next >>     


Rest HATEOS Model

In this article we discuss HATEOAS (HyperMedia as the Engine of Application State) Rest constraint and some HATEOAS example and HATEOAS JSON representations of embedded HyperMedia.Jersey currently supports HATEOAS to build HyperMedia-Driven RESTful Web Services.
HATEOAS (HyperMedia as the Engine of Application State) is an approach to building RESTful web services, where the client can dynamically discover the actions available to it at runtime from the server. HATEOAS (HyperMedia as the Engine of Application State) is the forth constraint of the REST application architecture. It is the last constraint or the fourth REST interface constraint defined in Roy Fielding's doctoral dissertation. HATEOAS refers to the use of HyperMedia in resource representations to help guide clients navigate through a conversation or in other words client interacts with an application entirely through HyperMedia provided dynamically by application servers. This allows you to build services that decouple client and server to a great extent. Moreover it allows the services to evolve independently.
As Roy Fielding specified, Restful APIs must be hypertext-driven. In HATEAOS, resource representations include information about next valid states. This may also be the transitions that lead to next valid states. The client transitions through application states by selecting from the links within a representation.

Richardson's Maturity Model

The Richardson Maturity Model is a way to grade your API according to the constraints of REST. The better your API adheres to these constraints, the higher its score is. The Richardson Maturity Model knows 4 levels (0-3), where level 3 designates a truly RESTful API.

Level 0: Swamp of POX

Level 0 uses its implementing protocol (normally HTTP, but it doesn't have to be) like a transport protocol. That is, it tunnels requests and responses through its protocol without using the protocol to indicate application state. It will use only one entry point (URI) and one kind of method (in HTTP, this normally is the POST method).

Level 1: Resources

When your API can distinguish between different resources, it might be level 1. This level uses multiple URIs, where every URI is the entry point to a specific resource. Still, this level uses only one single method like POST.

Level 2: HTTP verbs

To be honest, I don't like this level. This is because this level suggests that in order to be truly RESTful, your API MUST use HTTP verbs. It doesn't. REST is completely protocol agnostic, so if you want to use a different protocol, your API can still be RESTful.
This level indicates that your API should use the protocol properties in order to deal with scalability and failures. Don't use a single POST method for all, but make use of GET when you are requesting resources, and use the DELETE method when you want to delete a resources. Also, use the response codes of your application protocol. Don't use 200 (OK) code when something went wrong for instance. By doing this for the HTTP application protocol, or any other application protocol you like to use, you have reached level 2.

Level 3: Hypermedia controls

Level 3 is when you implement HATEOAS. That is, the responses have links that control the application state for the client. The client doesn't need to be aware of the different API URIs. All the URIs that the client would need is a part of the response that the server sends. If an API implements this, it is said to be at Level 3 of RMM, and is considered fully RESTful.

The code of this tutorial is going to be based on Jersey. Let's show the structure of the project:

In this example, I have created maven project and created package for java class.

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>com.rest.technology</groupId>
<artifactId>RestWebService</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>RestWebService</name>

<build>
<finalName>RestWebService</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<inherited>true</inherited>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version></version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<!-- use the following artifactId
if you don't need servlet 2.x compatibility -->
<!-- artifactId>jersey-container-servlet</artifactId -->
</dependency>
<!-- this to get JSON support -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
</dependencies>
<properties>
<jersey.version>2.21</jersey.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>


In this pom.xml, I have used jersey-media-moxy dependency for getting JSON response and jersey-container-servlet-core dependency is used to configure Jersey dependency with this project.

you create a file called web.xml in the WebContent\WEB-INF folder as the following:

web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>

<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>Jersey Web Application </servlet-name>
<servlet-class>
org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>
jersey.config.server.provider.packages </param-name>
<param-value>com.rest.technology </param-value>
</init-param>
<load-on-startup>1 </load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>Jersey Web Application </servlet-name>
<url-pattern>/webapi/* </url-pattern>
</servlet-mapping>

</web-app>

In web.xml, I am using org.glassfish.jersey.servlet.ServletContainer servlet for configure restful webservice. I have configure com.rest.technology package for searching all annotations and create a one instance when application start using load-on-startup. In this example /webapi/* pattern use for restful URL.

index.jsp
<html>
<body>
<h2>Jersey RESTful Web Application!</h2>
for more information on Jersey!
</body>
</html>

index.jsp is used for welcome file when this application run.

Account.java
package com.sharmav.javatutorial.dto;

import java.util.List;

import javax.xml.bind.annotationXmlAccessType;
import javax.xml.bind.annotationXmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotationXmlRootElement;

@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "Account")
public class Account {

@XmlAttribute(name = "AccountNumber")
private long number;
@XmlAttribute(name = "CustomerName")
private String name;
@XmlAttribute(name = "Withdrawal")
private int withdrawal;
@XmlAttribute(name = "Balance")
private double balance;
@XmlAttribute(name = "Links")
private List<Link> links;

public Account() {
}

public Account(long number, String name, String balance) {
this.number = number;
this.name = name;
this.balance = balance;
this.withdrawals = 0;
}

public long getNumber() {
return number;
}

public void setNumber(long number) {
this.number = number;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getWithdrawals() {
return withdrawals;
}

public void setWithdrawals(int withdrawals) {
this.withdrawals = withdrawals;
}

public double getBalance() {
return balance;
}

public void setBalance(double balance) {
this.balance = balance;
}

public List<Link> getLinks() {
return links;
}

public void setLinks( List<Link> links) {
this.links = links;
}

}

Account.java is POJO class which have some attributes with xml tag. I have created getter setter for these objects. It have argument and non-argument constructor. This class display all information related to account.

Link.java
package com.sharmav.javatutorial.dto;

import java.util.List;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotationXmlRootElement;

@XmlRootElement(name = "Link")
public class Link {

@XmlAttribute(name = "Link")
private String link;
@XmlAttribute(name = "rel")
private String rel;

public String getLink() {
return link;
}

public void setLink(String link) {
this.link = link;
}

public String getRel() {
return rel;
}

public String setRel(String rel) {
this.rel = rel;
}

}

Link class is used to create link for deposite, withdrawal and view account.

AccountService.java
package com.sharmav.javatutorial.service;

import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

import com.sharmav.javatutorial.dto.Account;
import com.sharmav.javatutorial.dto.Link

public class AccountService {

private Map<Long, Account> account = new HashMap<>();

public class AccountService {
long accNum1 = 1001L;
Account account1 = new Account(accNum1, "John" , 20000); account1.setLinks(getAllLinks(accNum1));
accounts.put(accNum1, account1);

long accNum2 = 1002L;
Account account2 = new Account(accNum2, "Smith" , 15000); account2.setLinks(getAllLinks(accNum2));
accounts.put(accNum2, account2);

long accNum3 = 1003L;
Account account3 = new Account(accNum3, "Lime" , 25000); account3.setLinks(getAllLinks(accNum3));
accounts.put(accNum3, account3);
}

public Account getAccount(Long accountNumber) {
return accounts.get(accountNumber);
}

public List<Account> getAllAccounts() {
return new ArrayList<Account>(accounts.values());
}

private List<Link> getAllLinks(long accountNum) {
List<Link> links = new ArrayList<>();
Link deposite = new Link();
deposite.setLink("/account/"+accountNum+"/deposite");
deposite.setRel("deposite");
links.add(deposite);

Link withdraw = new Link();
withdraw.setLink("/account/"+accountNum+"/withdraw");
withdraw.setRel("withdraw");
links.add(withdraw);

Link view = new Link();
view.setLink("/account/"+accountNum+"/view");
view.setRel("view");
links.add(view);

return links;
}
}

AccountService class is used to create accounts in map using account number id. It have two methods for display all accounts and account based on id. This class has one getAllLinks method for get all links related to account id.

AccountResource.java
package com.sharmav.javatutorial.resources;

import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

importcom.sharmav.javatutorial.dto.Account;
importcom.sharmav.javatutorial.service.AccountService;

@Path("/")
public class AccountResource {

AccountService accountService = new AccountService();

@GET
@Path("accounts")
@Produces(MediaType.APPLICATION_JSON)
public List<Account> getAccounts() {
return accountService.getAllAccounts();
}

@GET
@Path("account/{accountId}")
@Produces(MediaType.APPLICATION_JSON)
public Account getAccount(@PathParam("accountId") long id) {
return accountService.getAccount(id);
}
}

AccountResource class is used to run this example. In this class, we have two method to get account information. These methods contain @GET annotation for getting account information. When you run this example, you will get result as per below screen short using below url-
http://localhost:8080/Rest_Hateoas/accounts
http://localhost:8080/Rest_Hateoas/account/1002



Here you can see the result using above URL in this example. First URL display all accounts and second URL display account information which have id is 1002.


     << Previous
Next >>