JavaFX and RESTful Web Services communication – Part 1

Previously published on Today Software Magazine.

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:

  • It directly accesses the data base and has the disadvantage of requiring code that has to be altered for different types of data bases. Thus, we can end up with a bottleneck in the case of certain demands of data which require an important traffic volume for the data transport.
  • It implements the logic of the application, with the note that it can be limited by the capacity of the client station (memory, CPU) and, in addition, it requires code that has to be distributed to each client.

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

  • a component which contains the FXML files representing the front-end, the classes corresponding to the controller that performs the event handling, a class for launching the application, CSS files as well as formatting classes.
  • a component which contains the entity classes, which are mapped to the tables of the data base.
  • a component which contains the classes that carry out operations on the data base, using the previous component (DAO classes).
  • JPA, which is used in order to connect to the data base and to perform the operations on it more easily.

The advantages of using this architecture are:

  • It is much more extensible than the one tier architecture
  • It combines the presentation logic, business logic and the data resource in a single system
  • It can have a client on any host as long as it is connected to the data base through a network
  • It has fewer weak points that can generate errors than the three tiers system

The disadvantages are:

  • Any alteration in the business strategy triggers a modification in the logic of the application, with implications on each client. This can be very costly and time consuming
  • Each client needs a connection to the data resource
  • It restricts or complicates the adding of caching, mirroring, proxy services or secure transactions
  • Since the business logic is on the client, the entire data base is exposed in the network

The three tiers architecture

It has the following structure:

  • The client application – much fewer resources are necessary on the client station. No alterations are necessary if the location of the data base changes, there is less code to be distributed to the client stations
  • The application server – manipulates the requests from several clients, reduces the data traffic in the network
  • The data base server
  • The application on the server part is described as:
  • It will contain the business logic so as to carry out CRUD operations on the data base found on the data base server
  • The components will be published as web services
  • The web services will be developed by using Jersey, which is an implementation of the JAX-RS specifications
  • They will be deployed on an application server, for instance Glassfish, and they can be consumed by using HTTP

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:

  • It allows an efficient usage of the connection to the data resource by using connection pooling
  • We can alter the business logic without affecting the software of the client
  • It is a much more suitable architecture for scaling and load balancing than others
  • Scaling mostly affects the middle tier

The disadvantages are:

  • It increases the network traffic
  • It is much more vulnerable to errors
  • The business objects must be designed to handle the integrity of the transactions

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:

  1. SOAP (Simple Object Access Protocol), using XML messages which define the architecture of the message and its formats. These systems often contain a description of the operations offered by the service, written in the WSDL file (Web Service Description Language), which is in fact a XML file.
  2. RESTful (Representational State Transfer) is much more appropriate for basic scenarios, with an ad-hoc integration. They are much better integrated with HTTP than SOAP, they do not require XML or WSDL definitions. They are based on JSR-311 specifications, and Jersey is one of their implementations. The REST services use W3C and IETF standards (Internet Engineering Task Force): HTTP, XML, URI, MIME.

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:

  • The resources are identified through URI, which provides a global addressing way
  • A uniform interface is used for resource manipulation
  • Self-descriptive messages are used, or metadata for the resources
  • Stateful interactions through hyperlinks are based on the concept of explicit state of transfer

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.

  • GET is used to obtain data or to make a request on a resource. The data returned from the web service are a representation of the requested resource
  • PUT is used in order to create a new resource. The web service may respond with data or a status which indicates the success or failure
  • POST is used in order to update the resources or the existing data
  • DELETE is used to erase a resource or data.

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:

  • Create = PUT, if we send the entire content to a specified resource (URL)
  • Create = POST, if we send an order to the server in order to create a resource subordinated to the specified resource, by using server-side algorithms.
  • Update = PUT, if we update the entire content of the specified resource
  • Update = POST, if we ask the server to update one or several resources subordinated to the specified resource.

Developing a REST web service with JAX-RS

JAX-RS is a Java API:

  • Designed to facilitate the development of applications using the REST architecture
  • It uses Java annotations in order to simplify the development of REST services
  • It uses runtime annotations, which, by reflection, will generate helper classes and the artefacts for the resource.

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:
  • The value of the @Path annotation is a relative URI. The Java class will be, in the case of our example, on the path given by the URI /hello. The URI is static, but we can also include variables in it. The templates for the URI paths are URIs with variables included in the URI syntax
  • The @GET annotation is designed for the request method, together with @POST, @PUT, @DELETE, @HEAD and it is defined by JAX-RS, corresponding respectively to the similar HTTP methods. In our example, the annoted method will process the HTTP GET requests. The behavior of a resource is determined by the HTTP method the resource replies to
  • The @Produces annotation is used in order to specify the MIME media type that a resource can produce and send to the client. In the case of our example, the type is: text/plain
  • The @Consumes annotation is used to specify the MIME type that a resource can consume and which has been sent to the client.

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

Creation of file structure in Eclipse

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

Dynamic Web Project

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:

Three tier architecture

The steps for generating a REST web service are:

1. Checking the following conditions

  • Jersey is added to the project
  • JAX-RS API is added to the project

2. The proper generation of the web services:

  • The creation of the REST services
  • The validation of the generated web service classes
  • The validation of the configuration in the web.xml file

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

  • The URL address correctly represents the endpoint of the deployed service and the annotations of the method
  • The GET, PUT, DELETE or POST requests invoke the appropriate methods of the service
  • The methods return the expected data

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

  • Ensuring that the project has all the necessary libraries added
  • Identifying the GUI window and checking the place where the results of invoking the web service will be displayed
  • The following information is useful when developing the client: the URL of the service, the name of the package and the class where the client code will be generated
  • Invoking the code in the GUI window

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!