TSM - JavaFX and RESTful Web Services communication

Silviu Dumitrescu - Line manager@Telenav

A client application can access remote distributed resources. There are several ways to access these resources, but maybe the most portable is that of web services. In this article, we will talk about the REST services (Representational State Transfer), self-descriptive, modern services, with a Java API which has an extraordinary evolution in the last versions of the Java Enterprise platform. We will start by discussing some architectural aspects which are part of the understanding of the components of a distributed application that uses the web services.

The two tiers architecture

This architecture has two essential components:

A. The client application with the following features:

B. The data base server - A JavaFX client application consists of the following:

The advantages of using this architecture are:

The disadvantages are:

The three tiers architecture

It has the following structure:

Thus, the application server will contain a collection of RESTful web services, which in their turn will communicate through JPA with the data base server. The Glassfish application server provides the infrastructure for both JPA and JAX-RS APIs.

The advantages of using a three tiers architecture:

The disadvantages are:

In spite of the disadvantages listed above, the three tier architecture is often used for big applications. It is the one that we will focus on in this article and in the following articles on this topic.

In the following part, we will briefly discuss the web service paradigm, as a way to clarify the ideas even for those who are less familiarized with this paradigm.

Web Services

They are applications which communicate through HTTP in WWW. They provide a standard which facilitates the inter-operability of software applications that run on a variety of platforms and frameworks. The interoperability and extensibility are given by XML. They can be combined in a manner that loses coupling in order to obtain complex operations.

By using the web services, a two tier application can be changed into a three tier one, which can operate over the web. The application thus becomes extensible and interoperable with different types of client applications.

There are two types of web services:

We will use the REST services for the integration through web and we will use the SOAP services in enterprise applications that have integration scenarios which require advanced capacities of the services (QoS).

We will choose JAX-RS since the services are easier to consume for many types of clients, while it allows the server to evolve and scale. Clients may choose to consume certain or all the aspects of the service and combine them with other web services.

REST applications are simple, lightweight and fast since:

REST indicates a stateless client server architecture. A REST service exposes many resources which identify the destinations of the interactions with the clients. The resources are identified through URI and manipulated by four operations: PUT, GET, POST and DELETE.

The resources are detached from the representation so that they can be accessed in a variety of formats: HTML, XML, plain text, PDF, JPEG and JSON. The metadata on the resources is used, for example, to control the cache, to detect transmission errors, to negotiate the most suitable representation format and for the authentication or access control.

Any interaction with a resource is stateless, the message is thus self-contained. There are several techniques available for us to convey the state, such as: rewriting the URI, cookies, hidden fields. The state can be included in the reply message in order to create future states of the interaction.

The clients of the web service who wish to use these resources access a certain representation by transferring the content of the application by using a little set of remote methods which describe the action that needs to be done on the resource.

In certain cases, the update or delete actions can be done through POST (for instance, when the service is consumed by browsers which do not support PUT or DELETE). The following mappings can be applied for PUT or POST:

Developing a REST web service with JAX-RS

JAX-RS is a Java API:

Jersey implements the support for annotations defined by the JAX-RS specifications. An archive of the Java EE application containing the JAX-RS resource classes will have the resources set up, the helper classes and the artefacts generated and the resource exposed to the clients by the deploy of an archive on the application server.

Let’s take the following example of a file representing the code of the root resource class of a REST web service, which uses JAX-RS annotations:

package com.example.ws;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

@Path("/hello")
public class Hello {
private String name="";

    /**
     * Default constructor. 
     */
    public Hello() {
        // TODO Auto-generated constructor stub
    }

    /**
     * Retrieves representation of an instance of 
     * Hello
     * @return an instance of String
     */
    @GET
    @Produces("text/plain")
    public String sayHello() {
        // TODO return proper representation object
    return "Hello World"+name;
    }

    /**
     * PUT method for updating or creating an
     * instance of Hello
     * @param content representation for the resource
     * @return an HTTP response with content of the 
     * updated or created resource.
     */
    @PUT
    @Consumes("text/plain")
    public void putText(String content) {
     name=content; 
    }
}

The used annotations are:

In Eclipse, the creation of the file structure is done by following these steps:

The project in which I created the resource is a Dynamic Web Project where:

The checking of the service is performed at the address: http://localhost:8080/JerseyFirst/jaxrs/hello. This name is derived from the value of the tag from the web.xml, completed by the value of of (automatically generated) and the value of the @Path annotation.

Creating a client

Jersey contains a REST library which can be used for the testing or creation of a Java client. We will create a Client Project Application, with the following code:

import java.net.URI;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

public class Main {
  public static void main(String[] args) {
    ClientConfig config = new DefaultClientConfig();
    Client client = Client._create_(config);
    WebResource service = client.resource(_getBaseURI_());
                System._out_.println(service.path("jaxrs").path("hello").accept(MediaType._TEXT_PLAIN_).get(ClientResponse.class).toString());
System._out_.println(service.path("jaxrs").path("hello").accept(MediaType._TEXT_PLAIN_).get(String.class));
  }

  private static URI getBaseURI() {
    return UriBuilder._fromUri_("http://localhost:8080/JerseyFirst/").build();
  }
}

The three tier architecture using REST is illustrated in the following picture:

The steps for generating a REST web service are:

  1. Checking the following conditions

  2. The proper generation of the web services:

When we are testing a web service we need to take the following things into consideration:

The steps to be taken in order to develop a client of the REST web service are:

We will come back in the future issues of the magazine with more complex applications, which will also include the interaction with a data base.

We are looking forward to your questions!