GlassFish and MySQL, Part 4: Creating a RESTful Web Service and JavaFX Client

   
By Ed Ort and Carol McDonald, March 2009  

Articles Index

Introduction | The Application | Building the Application

This is the fourth article in a series of articles on GlassFish and MySQL. Part 1 of the series describes the advantages of using GlassFish with MySQL and illustrates why the combination is a perfect choice for developing and deploying web applications.

Part 2 shows how to develop a create, read, update, and delete (CRUD) web application that uses GlassFish and MySQL. The application uses the Java Persistence API implemented in GlassFish to manage data persistence.

Part 3 shows how easy it is to convert the controller layer of the web application, that is, the layer of the application that performs the CRUD operations -- into a SOAP-based web service. It also shows how to create a client for the web service.

In Part 4, you'll learn how to create a RESTful web service for the web application. You'll also examine a JavaFX client for the RESTful web service. As was the case for Part 3, the web service discussed in Part 4 uses GlassFish, MySQL, and the Java Persistence API.

 
This article shows you how to use the NetBeans IDE with GlassFish and MySQL to create a RESTful web service. The article also presents a JavaFX client for the web service.

This article shows you how to use the NetBeans IDE with GlassFish and MySQL to create the RESTful web service. Specifically, you'll take advantage of features in NetBeans IDE 6.5, GlassFish Server v2.1, and MySQL 5.1 Community Server to build and deploy the RESTful web service. This article also shows you how to use the NetBeans IDE with JavaFX support to run a JavaFX client for the web service.

Contents
 
RESTful Web Services
GlassFish, JAX-RS, and Jersey
The JavaFX Platform
The Application
Inside the Application
Building the Application
Running the JavaFX Client
Summary
For More Information
Discuss
 
RESTful Web Services
 
Developers are increasingly choosing to build web services with the RESTful approach rather than using SOAP-based technologies.

RESTful web services are web services that are built using the Representational State Transfer (REST) style of software architecture. An important concept in REST is the existence of resources, each of which can be referred to using a universal resource identifier (URI). In order to manipulate these resources, clients and servers communicate using a standardized interface such as HTTP and exchange representations of these resources. Because of the lightweight nature of REST and its ability to transmit data directly over HTTP, developers are increasingly choosing to build web services with the RESTful approach rather than using SOAP-based technologies.

A RESTful web service is based on the following principles:

  • Resources and representations. Instead of providing just one endpoint for a particular web service and having that endpoint perform various operations, you provide access to resources. A resource is a single piece of your web application that you make accessible to clients. Because the resources that you have are not transportable over the network, "providing them" means providing representations of their state.
     
  • Addressability and connectedness. Resources have their representations, but providing representations of resources would be useless if you could not address them. In REST, every resource must have at least one address, that is, one URI. To address the resource, you simply specify the URI. This concept is called addressability. By publishing your web application, you introduce many different URIs that are connected to each other. Because of that connectedness, the only URI you need to give to your clients is one URI called the bootstrap URI.
     
  • Uniform interface. Even if you make resources available through URIs and representations to exchange between the client and server, this still does not allow you to establish communication. You need a communication protocol or interface to use. In a REST architecture, such an interface must be uniform. It means that whatever URI or resource address you access, the interface should be the same. For instance, on the Web, no matter what URI you enter, your web browser simply uses an HTTP GET method to retrieve a corresponding web page or resource representation, and displays it.
     
  • Statelessness. Statelessness means that a web application is not responsible for keeping any information about the state of its clients. REST does not encompass the concept of HTTP sessions. The client is responsible for tracking its own actions, if it needs to. The service maintains its resources and provides a uniform interface to the clients.
GlassFish, JAX-RS, and Jersey

GlassFish, an open-source, enterprise-quality, Java EE 5-compliant application server, implements a set of Java technologies that simplify development and use of web services. This set or "stack" of technologies is collectively called Metro. Metro includes web service technologies such as Java API for XML-Based Web Services (JAX-WS) that enable you to develop and use SOAP-based web services.

Part 3 of this series of articles describes how to develop a SOAP-based web service using JAX-WS. GlassFish also supports the Java API for RESTful Web Services (JAX-RS) and its production-ready reference implementation, Jersey, that you can use to develop and use RESTful web services. You can use the GlassFish Update Center to add Jersey to GlassFish.

 
JAX-RS provides a standardized API for Java developers to build RESTful web services, a popular alternative to SOAP-based web services.

JAX-RS provides a standardized API for Java developers to build RESTful web services. The API basically provides a set of annotations and associated classes and interfaces. Applying the annotations to Plain Old Java Objects (POJOs) enables you to expose web resources.

Here, for example, is a class that uses JAX-RS annotations to expose a resource that represents a simple message:

   package restservice;

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

      @Path("/myresource")
      public class MyResource {

          @GET
          @Produces("text/plain")
          public String getIt() {
              return "Got it!";
          }
      }
 

The @Path annotation identifies the URI path for which the MyResource class will serve requests. The @GET annotation indicates that the getIt() method responds to HTTP GET requests. The @Produces annotation indicates that the getIt() method returns plain text.

To communicate with a resource in REST, you make an HTTP request specifying its URI and one of the following HTTP methods: GET, PUT, POST, DELETE. For example, here is a GET request for the RESTful web service resource provided by the MyResource class:

   GET http://localhost:8080/myresource
 

In response, the getIt() method in the MyResource class returns the plain text string Got it!

Note that Jersey also provides a client API that you can use to consume a RESTful web service. However, the focus in this article is on the JavaFX approach to accessing a RESTful web service.

The JavaFX Platform
 
Java FX is a platform for creating and delivering rich Internet applications that can run in a wide variety of devices, anywhere from handsets to laptops to desktops.

Java FX is a platform for creating and delivering rich Internet applications (RIAs) -- web applications that use rich media types such as video, audio, and graphics -- that can run in a wide variety of devices, anywhere from handsets to laptops to desktops. In many cases, you can compile and run the same JavaFX application code in a mobile environment, a desktop environment, or in a browser.

The Java FX platform combines a declarative scripting language, JavaFX Script, and set of tools that enable developers and designers to build RIAs quickly and collaboratively. The tools include NetBeans IDE 6.5 for JavaFX 1.1 and JavaFX 1.1 Production Suite.

NetBeans IDE 6.5 for JavaFX 1.1 provides a sophisticated integrated development environment (IDE) for building, previewing, and debugging JavaFX applications. A JavaFX plugin is also available to add the JavaFX platform to NetBeans IDE 6.5 if the IDE is already installed. NetBeans IDE 6.5 for JavaFX 1.1 features a drag-and-drop palette that you can use to quickly add JavaFX objects -- including objects for transformations, effects, and animation -- to application source code. The IDE automatically generates the source code for these objects.

NetBeans IDE 6.5 for JavaFX 1.1 also comes with its own set of sample applications and the JavaFX Mobile Emulator, a mobile phone simulator. Figure 1 shows a JavaFX application in NetBeans IDE 6.5 for JavaFX 1.1. Notice the project structure in the Project window of the IDE, the source code in the editor window, and the drag-and-drop palette. Figure 1 also shows the output displayed by the running the application on the desktop and in the JavaFX Mobile Emulator.

 

JavaFX 1.1 Production Suite is a suite of tools and plugins that enable designers to export graphical assets from tools such as Adobe Photoshop and Adobe Illustrator to JavaFX applications.

NetBeans IDE 6.5 for JavaFX 1.1 integrates JavaFX technology into NetBeans IDE 6.5 through the JavaFX 1.1 SDK. The SDK includes the JavaFX 1.1 desktop runtime, APIs, API documentation, compiler, sample programs, and the JavaFX 1.1 mobile runtime and Mobile Emulator. The SDK is also available as a stand-alone download. In other words, you can create JavaFX applications using NetBeans IDE 6.5 for JavaFX 1.1, or if you prefer to work from a command line or code editor, you can create JavaFX applications using the JavaFX 1.1 SDK. You can also create JavaFX applications using an IDE other than NetBeans by incorporating the SDK.

The JavaFX Script Language

 
The JavaFX Script language makes it easy to program in a visual context. It allows you to create highly expressive user interfaces quickly and easily.

The declarative style of the JavaFX Script language makes it easy to program in a visual context. It allows you to create highly expressive user interfaces (UIs) quickly and easily. For example, the following JavaFX application coded in JavaFX Script renders a green rounded rectangle and a white circle with a red outline on the top of the rectangle. Both objects are placed on a window titled "Declaring Is Easy!"

   import javafx.stage.Stage;
   import javafx.scene.Scene;
   import javafx.scene.shape.Rectangle;
   import javafx.scene.paint.Color;
   import javafx.scene.shape.Circle;

   Stage {
     title: "Declaring Is Easy!"
     width: 249
     height: 251
     visible: true
     scene: Scene {
       content: [
         Rectangle {
           x: 45 y: 35
           width: 150 height: 150
           arcWidth: 15 arcHeight: 15
           fill: Color.GREEN
         },
         Circle {
           centerX: 118
           centerY: 110
           radius: 83
           fill: Color.WHITE
           stroke: Color.RED
         }
       ]
     }
   }
 

Figure 2 shows what the application displays.

 
Figure 2. A JavaFX Script Application That Renders a Circle on Top of a Rounded Rectangle
 

Notice how few lines of code are needed for the application. Also notice how the structure of the code models the UI. In the code, Stage, Scene, Rectangle, and Circle are objects that are used to construct the UI. The Stage object is used to render a window. In JavaFX Script, you create an object with an object literal that describes the object's state and its behavior. You specify the object's state using instance variables and values, and you specify the object's behavior with instance functions.

Variables: A variable is a construct that holds a value. You declare a variable with either the var or def keywords. You can assign new values to a var variable but not to a def variable. For example, the following code defines three variables. All three are assigned values, but only the result variable can be assigned a new value.

   def numOne = 100;
   def numTwo = 2;
   var result;
 

You can also specify variables and values within an object instance and in this way define the state of the object. For example, in the previous circle-above-rectangle example, the Stage object literal, that is, Stage { ...}, specifies the instance variables and values shown in Table 1.

Table 1: The Instance Variables in the Circle-Above-Rectangle example
 
Instance Variable
Value
Meaning
title
Declaring Is Easy!
The window title is Declaring Is Easy!
width
249
The window width is 249 pixels.
height
251
The window height is 251 pixels.
visible
true
The window is visible.
 
 
In JavaFX Script, objects are rendered within a scene, a logical container that is used to hold graphical objects called nodes. In essence, a scene is a drawing surface for graphical content in JavaFX.

The Stage object literal also specifies an instance variable, scene, that has as its value a Scene object. In JavaFX Script, objects are rendered within a scene, a logical container that is used to hold graphical objects. Internally, JavaFX handles a scene and the graphical objects it contains in a hierarchical structure called a scene graph. A single element in the scene graph is called a node. The graphical objects in a scene, that is, the nodes within a scene graph, can be UI components, shapes, text, images, and media content such as video or audio. In essence, a scene is a drawing surface for graphical content in JavaFX. If you add a scene to a Stage object, JavaFX renders all the nodes in the scene.

You can perform transformations such as rotation on nodes. You can also animate nodes and apply various effects on them such as fading in or fading out. The Scene object creates a scene. The content instance variable specifies the nodes to be rendered in the scene, which in the circle-above-rectangle example are a Rectangle object and a Circle object.

Functions: A function is an executable block of code that performs some particular task. For example, the following function adds two numbers and prints the result:

   function add(argOne: Integer, argTwo: Integer) {
        var result ="{argOne} + {argTwo} = {result}");
   }
 

The definition of a function begins with the function keyword. You invoke a function by specifying the function name and its arguments (if any). For example, the following invocation of the add() function displays 4 + 2 = 6:

   add(4, 2)
 

You can also specify a function within an object instance and in this way define behavior for the object. For example, suppose you want the circle-above-rectangle application to close when a user clicks the mouse pointer on the circle. You could do that by assigning a function to an instance variable in the Circle object, as follows:

   import javafx.stage.Stage;
   import javafx.scene.Scene;
   import javafx.scene.shape.Rectangle;
   import javafx.scene.paint.Color;
   import javafx.scene.shape.Circle;



   Stage {
     title: "Declaring Is Easy!"
     width: 249
     height: 251
     visible: true
     scene: Scene {
       content: [
         Rectangle {
           x: 45 y: 35
           width: 150 height: 150
           arcWidth: 15 arcHeight: 15
           fill: Color.GREEN
         },
         Circle {
           centerX: 118
           centerY: 110
           radius: 83
           fill: Color.WHITE
           stroke: Color.RED
           onMouseClicked: function (e) {
             javafx.lang.FX.exit();
           }
         }
       ]
     }
   }
 

Here the Circle object specifies an instance variable, onMouseClicked, whose value is a function that is called when the user clicks the mouse pointer within this node. The function calls the javafx.lang.FX.exit() method to exit the application.

Binding: One of the significant features in JavaFX Script is data binding. This features allows you bind the value of a variable with the value of some other construct such as another variable or an object. JavaFX Script calls this other construct a bound expression. What's important about this is that when the value of the variable changes, the new value is automatically assigned to the bound expression. For example, the following code displays the same result as shown in Figure 2.

   import javafx.stage.Stage;
   import javafx.scene.Scene;
   import javafx.scene.shape.Rectangle;
   import javafx.scene.paint.Color;
   import javafx.scene.shape.Circle;

   var radical = 83;

   Stage {
     title: "Declaring Is Easy!"
     width: 249
     height: 251
     visible: true
     scene: Scene {
       content: [
         Rectangle {
           x: 45 y: 35
           width: 150 height: 150
           arcWidth: 15 arcHeight: 15
           fill: Color.GREEN
         },
         Circle {
           centerX: 118
           centerY: 110
           radius: bind radical
           fill: Color.WHITE
           stroke: Color.RED
         }
       ]
     }
   }
 

However, if you change the value assigned to the radical variable, it automatically changes the radius of the circle. For example, assigning a value of 33 to radical displays a smaller circle as shown in Figure 3

 
Figure 3. Data Binding Changes the Radius of the Circle
 

Libraries: JavaFX provides a rich set of libraries that makes it easy to include graphics, media, and web services in an application. The JavaFX application that displays the red-outlined circle above the green rectangle uses the JavaFX libraries shown in Table 2.

Table 2: JavaFX Libraries Used in the Circle-Above-Rectangle example
 
Library
Purpose
javafx.stage
Provides top-level container classes for JavaFX script
javafx.scene
Provides base classes for a JavaFX scene graph
javafx.scene.shape
Provides classes for defining and performing operations on two-dimensional geometric objects
javafx.scene.paint
Provides classes for colors and gradients used to fill shapes and backgrounds when rendering a scene graph
 
 
JavaFX provides a rich set of libraries that makes it easy to include graphics, media, and web services in an application. In addition, you can use any Java library in a JavaFX application.

You can view these and additional JavaFX libraries in the JavaFX 1.1 API.

You can also use any Java library in a JavaFX application. In other words, you can take advantage of JavaFX libraries to do things such as add rich media types to an application, perform animation, do transformations, or apply effects, and you can take advantage of features in the Java platform such as its sophisticated security architecture.

» Continue to the next page of this article

Introduction | The Application | Building the Application

MySQL GlassFish