JAX-RS provides a standardized API for building RESTful web services in Java. Central to the RESTful architecture is the concept of resources identified by universal resource identifiers (URIs). The API provides a set of annotations which you can add to Plain Old Java Objects (POJOs) to expose web resources identified by URIs .

Explanation of the usage of Dojo and JAX-RS in a sample Catalog Application

The image below shows the Customer Listing page, which allows the user to page through a list of customers.

Quick installation and use of dojo with Netbeans

There are 3 ways to install dojo which you can read about in the book of dojo. A quick and easy way to use dojo with Netbeans is to download the JavaScript libraries from http://dojotoolkit.org/downloads. Create a new NetBeans Web Applications project. Extract the dojo toolkit into the project web directory: .../web , then rename dojo-release-1.1.1/ to src/ this will give you the project structure shown below. I have already done this for the sample project so you do not have to download dojo in order to run the sample.

Dojo style sheets

Every page using the dojo Grid needs to import the grid style sheetGrid.css as shown below:

Dojo is organized into three major layers: Dojo Core, Dijit, and DojoX. DojoX builds on Dojo Core and provides newer extensions to the Dojo toolkit. The rest of the Java Script for this application is in the file dynamicTable.js.

The Grid Widget

You can use widgets declaratively by using special attributes inside of regular HTML tags, or programmatically through JavaScript. The dojoType attribute declares a Dojo widget. Below is the declaration of the Grid widget for this applicaton:

The model and structure attributes point to the JavaScript variables for the model and layout structure explained below.

The Grid View

A Dojo grid is a widget useful for displaying data sets in a table with its own scrollable views. The dojo grid widget requires a layout. A grid layout is declared as an array of views. Each view is a group of columns, declared as an array of arrays. Each array element is an object, the "name" property of the object names the column. The column names will be displayed in the top row of the grid. The code below declares 4 columns: Company,City, State, Zip. This grid layout structure consists of one view as shown below:

This grid layout for this example is shown in the figure below (note: how the data for the table gets loaded is explained below).

The Grid Model

The dojo grid widget requires a data model. The model variable declares the type of Dojo object that the Grid will use for the json data that will be loaded in the grid. There are different options for the model, this example uses thedojox.grid.data.Objects which is a collection of objects to be displayed in the grid.

Code Sample from: dynamicTable.js

// the model will contain the data to be displayed in the viewmodel = new dojox.grid.data.Objects(null,null);

function handleResponse(responseObject, ioArgs){ // set the model object with the returned customers list model.setData(responseObject.customers.customer); }

The loadTablefunction calls dojo.xhrGetto make an XMLHttpRequest to the customers JAX-RS web service specified by the url: parameter. When the response from web service is returned, the callback function handleResponse specified by load: is called and the response is passed to the callback function in the responseObject. The handleAs parameter specifies the response data type, handleAs: "json" means the returned data is of the type JSON (Java Script object notation).In the handleResponse callback function, model.setData is called to populate the Dojo grid with the data returned from the the customers JAX-RS web service. Below is an example of a JSON response from the customers JAX-RS web service:

Loading the table

The dojo.addOnLoad function allows you to call a function after a page has loaded and after Dojo has finished its initilization. This application uses dojo.addOnLoad to call the loadTable() function (which we looked at above) which calls the customers JAX-RS web service and sets the results in the grid data model.

RESTful Web Services with JAX-RS

The dojo.xhrGeturl: parameter references the URI resources/customers/for the customers RESTful web service. The customers RESTful web service was generated using Netbeans 6.1 as explained in the Generating RESTful Web Services from Entity Classes tutorial. Using Netbeans 6.1 you can generate JPA Entity Classes from Database tables, then you can Generate RESTful Web Services from Entity Classes, and then you can test the Web Services with a browser interface. The customers RESTful web service was generated from the customer data table which comes already created in the Java DB with Netbeans.

Below is a snippet from the CustomersResource.java class which was generated by the Netbeans "Generate RESTful Web Services from Entity Classes" feature :

The CustomersResourcerepresents a list of customers. The CustomersResourcegetmethod returns a list of Customer objects in JSON format.

To address a resource in REST you specify its URI. @Path is a JAX-RS annotation that identifies the URI path for the resource. For the CustomersResource the URI path is /customers/.

@GET specifies that thegetmethod supports the HTTP GET method.

@ProduceMimespecifies the MIME types that a method can produce. Here, the annotation specifies that the getmethod returns a JSONArray object. TheCustomersConverterclass is a JAXB annotated class which is used to marshal a list of Customer objects into XML or JSON format. The getEntitiesmethod returns a list of Customer entity objects and is explained below.

@QueryParamspecifies input parameters for methods. When the method is invoked, the input value will be injected into the corresponding input argument.

@DefaultValuespecifies a default value for an arguement if no input value is given.

The Java Persistence Query APIs are used to create and execute queries that can return a list of results. The JPA Query interface provides support for pagination via the setFirstResult() and setMaxResults() methods: query.setMaxResults(int maxResult) sets the maximum number of results to retrieve.query.setFirstResult(int startPosition) sets the position of the first result to retrieve.

In the code below, we show the Customerentity class which maps to the CUSTOMER table that stores the customer instances. This is a typical Java Persistence entity object. There are two requirements for an entity:

ConclusionThis concludes the sample application which demonstrates a RESTful Web Service, coded using JAX-RS: Java API for RESTful Web Services (JSR-311) , which provides a list of customers, and a dojo client which gets and displays the Web Service responses in a dynamic Ajax table.

Configuration of the Application for jMaki, JPA, Netbeans 6.1 and Glassfish V2

Download the sample code and extract its contents. You should now see the newly extracted directory as<sample_install_dir>/dojoRest, where <sample_install_dir> is the directory where you installed the sample package. For example, if you extracted the contents to C:\ on a Windows machine, then your newly created directory should be atC:\dojoRest.

Start the NetBeans IDE. Click Open Project in the File menu and select the dojoRest directory you just unzipped.

Build the project as follows:

Right click the dojoRest node in the Projects window.

Select Clean and Build Project.

Run the project as follows:

Right click the dojoRest node in the Projects window.

Select Run Project.

When you run the project, your browser should display the opening page of the Sample Application (at http://localhost:8080/dojoRest/).

jMaki is an Ajax framework that provides a lightweight model for creating JavaScript centric Ajax-enabled web applications. jMaki provides wrappedwidgets that can be used as JavaServer Pages tags, as JavaServer Faces components, within a Phobos application, or with PHP. This sample applicaton uses jMaki with JavaServer Pages.

JAX-RS provides a standardized API for building RESTful web services in Java. Central to the RESTful architecture is the concept of resources identified by universal resource identifiers (URIs). The API provides a set of annotations which you can add to Plain Old Java Objects (POJOs) to expose web resources identified by URIs .

Explanation of the usage of jMaki and JAX-RS in a sample Catalog Application

The image below shows the Customer Listing page, which allows the user to page through a list of customers.

The sample application's index.jsp page uses a jMaki yahoo.dataTable widget to display a list of customers in a dynamic table.

The jMaki table widgets (there is also a jMaki dojo table widget) are useful when you want to show a set of results in tabular data on a web page. Table widgets provide sortable columns, row selection, and they can be updated using jMaki publish subscribe events.

In the List.jsp web page the dataTable is defined as shown below: (Note:Redcolors are for jMaki tags or variables, and Green for my code orvariables)

To determine the data format and events for the table you can refer to the jMaki Table Data Model or look at the widget.json file for the table widget. This file is located in the resources/yahoo/dataTable directory.

The serviceattribute references the customers/jMakiTableRESTful web service which returns the data to be included in the table. The data for the table should be a JSON object containing an object of columns and an array of row arrays. The column names need a unique id which is then used in the data to associate it with a given row. An example for a table of companies is shown below:

The subscribe="/table" attribute specifies a topic that events can be sent to. Publish and subscribe events can be used to tie widgets together (more on this later).

RESTful Web Services with JAX-RS

The dataTable's serviceattribute references the URI webresources/customers/jMakiTablefor thecustomers jMakiTable RESTful web service. The customers RESTful web service was generated using Netbeans 6.1 as explained in the Generating RESTful Web Services from Entity Classes tutorial. Using Netbeans 6.1 you can generate JPA Entity Classes from Database tables, then you can Generate RESTful Web Services from Entity Classes, and then you can test the Web Services with a browser interface. The customers RESTful web service was generated from the customer data table which comes already created in the Java DB with Netbeans. I added the jMakiTable method to the generated customers Web Service, in order to return the customers in the jMaki table format. I followed the jMakiBackend example which comes with Jersey (the JAX-RS reference implementation) which is expained in Japods blog: jMaki Widgets Talking To Jersey Resources In JSON.

Below is a snippet from the CustomersResource.java class which was generated by the Netbeans "Generate RESTful Web Services from Entity Classes" feature :

The CustomersResourcerepresents a list of customers. The CustomersResourcegetmethod returns a list of Customer objects in JSON format.

To address a resource in REST you specify its URI. @Path is a JAX-RS annotation that identifies the URI path for the resource. For the CustomersResource the URI path is /customers/.

@GET specifies that thegetmethod supports the HTTP GET method.

@ProduceMimespecifies the MIME types that a method can produce. Here, the annotation specifies that the getmethod returns a JSONArray object. TheCustomersConverterclass is a JAXB annotated class which is used to marshal a list of Customer objects into XML or JSON format. The getEntitiesmethod returns a list of Customer entity objects and is explained below.

@QueryParamspecifies input parameters for methods. When the method is invoked, the input value will be injected into the corresponding input argument.

@DefaultValuespecifies a default value for an arguement if no input value is given.

The getTablemethod calls the CustomersResourcegetmethod, explained above, to get a list of Customer Entities which are used to create a CustomerTableModelclass. The CustomerTableModelclass is a JAXB annotated class, used to marshal a list of Customer objects into the jMaki JSON table format. A snippet of the CustomerTableModelclass is shown below:

The Java Persistence Query APIs are used to create and execute queries that can return a list of results. The JPA Query interface provides support for pagination via the setFirstResult() and setMaxResults() methods: query.setMaxResults(int maxResult) sets the maximum number of results to retrieve.query.setFirstResult(int startPosition) sets the position of the first result to retrieve.

In the code below, we show the Customerentity class which maps to the CUSTOMER table that stores the customer instances. This is a typical Java Persistence entity object. There are two requirements for an entity:

Connecting the listener to the handlerThe listener handler for the /button/nexttopic is shown below. First you declare the topic to listen to and then the listener function which will handle the notification. The/button/nextlistener handler increments the page number and then calls the getNextPagefuntion.

The getNextPagefunction uses jmaki.doAjax, which provides an easy way to make an XMLHttpRequest, to call the /customers/RESTful Web Service passing the start index as a URI parameter. The callbackfunction uses eval to convert the XMLHttpRequest response into a JSON object. Then jmaki.publishis called to publish the returned customerJSON objects to the /table/addRowtopic.

The yahoo.dataTable widget subscribes to thetabletopic.Subscribe events allow you to manipulate a given instance of a widget. The event names are appended to the the subscribe topic name following a "/". For example "/table/addRow" will call the yahoo.dataTableaddRowfunction which will add the payload value passed to the widget to the the table. This will cause the returnedcustomerJSON object to be displayed in the table on the html page.

ConclusionThis concludes the sample application which demonstrates a RESTful Web Service, coded using JAX-RS: Java API for RESTful Web Services (JSR-311) , which provides a list of customers, and a jMaki client which gets and displays the Web Service responses in a dynamic Ajax table.

Configuration of the Application for jMaki, JPA, Netbeans 6.1 and Glassfish V2

Download the sample code and extract its contents. You should now see the newly extracted directory as<sample_install_dir>/jmakiRest, where <sample_install_dir> is the directory where you installed the sample package. For example, if you extracted the contents to C:\ on a Windows machine, then your newly created directory should be atC:\jmakiRest.

Start the NetBeans IDE. Click Open Project in the File menu and select the jmakiRest directory you just unzipped.

Build the project as follows:

Right click the jmakiRest node in the Projects window.

Select Clean and Build Project.

Run the project as follows:

Right click the jmakiRest node in the Projects window.

Select Run Project.

When you run the project, your browser should display the opening page of the Sample Application (at http://localhost:8080/jmakiRest/).

The Java Persistence API provides a POJO-based persistence model for Java EE and Java SE applications. It handles the details of how relational data is mapped to Java objects, and it standardizes Object/Relational (O/R) mapping.

Groovy is an agile anddynamic language for the Java Virtual Machine, itcompiles to Java bytecode, and it combines popular features from languages such as Smalltalk, Python, and Ruby.

Grails is a Model-View-Controller based framework that simplifies the development of web applications by reducing the need for configuration files and by generating a lot of the things needed in a database-backed Web application.

The Sample Application

The sample application displays an online catalog of pets sold in a pet store. The image below shows the Catalog Listing page, which allows a user to page through a list of items in a store.

The Model - JPA Entity Classes

The Model is your application's persistent business domain objects. A JPA Entity instance represents a row in a database table. Item is an Entity class -- a typical Java Persistence entity object -- which maps to an ITEM table that stores the item instances.

The Itemclass has a many-to-one relationship with the Addressclass, this is specified using the @ManyToOne annotation in theItemclass and the @OneToMany(mappedBy = "address")annotation in the Addressentity class shown below:

modify the DataSource.groovy file in the catalog\grails-app\conf directory to use MySQL as the data base and the GrailsAnnotationConfiguration class to use the annotations in the JPA entities as shown below :

will generate the ItemController.groovy class for the model.Item entity class.

Controllers handle incoming http requests, interact with the model to get data and to process requests, invoke the correct view, and direct domain data to the view for display. In Grails, http requests are handled by Controller classes which are made up of one or more action methods that are executed on request and then either render a Groovy Server Page or redirect to another action. Grails routes requests to the controller action which corresponds to the URL mapping for the request. In Grails the default mapping from URL to action method follows this convention: http://host/app/controller/action/id . For example the URL http://host/catalog/item/list calls thelistaction method in the item controller class shown below. Grails Scaffoldingprovides a series of standardized Controller action methods for listing, showing, creating, updating, and deleting objects of a class. These standardized actions come with both controller logic and default view Groovy Server Pages. The ItemControllerlistaction renders a view with a paginated list of item objects.

When a URL has a controller but no action (e.g. http://localhost:8080/catalog/item/ ), Grails defaults to the index action. In theItemControllercode the indexaction method redirects to the listaction. The ItemControllerlistaction method calls the Item.list()method which returns an ArrayList of item objects retrieved from the item database table . If there are more than params.max objects in the table, Grails creates next and previous pagination links automatically. The itemListvariable is automatically made available to the view by the framework.

After executing code, actions usually render a GSP in the views directory corresponding to the name of the controller and action, for example the list action will render the grails-app\views\item\list.gsp .

The View

Entering the Grails command (in the directory catalog)

> grailsgenerate-viewsmodel.Item

will generate the create.gsp , edit.gsp, list.gsp, show.gsp groovy server pages for the model.Item entity class. The view layer generates a web page, using data from domain objects provided by the controller. In Grails, the view is rendered usingGroovy Server Pages. Below is part of the list.gsp for the Catalog application (note I modified the html table format from the default generated).

the <g:link> GroovyTag creates an html anchor taghref based on the action,id, controller parameters specified. In this example it generates a link to the item/show/id action which when clicked will display the corresponding item details. For example this line will generate the following HTML for the variableitem:

<ahref="/catalog/item/show/2">Friendly Cat</a>

<img src="${createLinkTo(dir:'images',file:item.imagethumburl)}"/>

The createLinkTotag generates an HTML link for the item's imagethumburl attribute.

${item.price?.encodeAsHTML()}

displays the value of the item 's price attribute as escaped HTML text.

<g:paginate total="${Item.count()}" />

The paginate tag creates next/previous buttons and a breadcrumb trail to allow pagination of results using the Item.count()domain method.

The Show Action Method

In Grails the mapping for the URL http://host/item/show/1 ( http://host/controller/action/id ) will route to the showaction in the ItemControllerpassing 1 to the method as the id of theparamsparameter hash. The showaction of the ItemControllerclass is shown below. The ItemControllershowaction renders a view showing the details of the item object corresponding to the id parameter.

The showaction method calls the Item.get()method which queries the items table returning the iteminstance variable corresponding to the item with the attributeid(primary key) equal to the idparameter. This is the equivalent of the following sql : select * from items where id='1' . The itemvariable is automatically made available to the Show view by the framework.

The Show View GSP

After executing code in the action, the showaction renders the app/views/item/show.gsp . Below is the GSP for the item show view :

Layouts

Grails layouts let you put common html on multiple views (for example page headers, footers, sidebars). Default layout templates are in the views layouts directory with a file name corresponding to the controller, or you can associate a view with a layout using the "layout" meta tag to your page:

<meta name="layout" content="main">

To add a title and parrot image to the top of the Pet Catalog pages, I put this table in the app\views\layouts\main.gsp layout:

ConclusionThis concludes the sample application which demonstrates how to work with Groovy and Grails to page through a list of Item JPA Entities which are retrieved using Item Controller action methods, and displayed using Item ViewGSPs.

Download the sample code and extract its contents. You should now see the newly extracted directory as<sample_install_dir>/Catalog, where<sample_install_dir> is the directory where you unzipped the sample package. For example, if you extracted the contents to C:\ on a Windows machine, then your newly created directory should be at C:\Catalog. The file "/Catalog/grails-app/conf/DataSource.groovy" is configured for aMySQL configuration.

A Comet Slideshow example using dojo, Comet, Bayeux, on Grizzly with Glassfish

dojo is an open source DHTML toolkit written in JavaScript. It includes many utilities that go beyond Ajax, for example the dojox.comet module simplifies programming comet applications. Comet is a term coined by Alex Russell to describe applications where the Server pushes data to the client. For example in the diagram below on the left you see Ajax polling which uses synchronous requests/responses to get events from the server. Comet uses long-lived previously-opened HTTP connections to "push" data to the client at any time, not only in response to user input.

Grizzly is an HTTP framework which uses the Java™ NIO API to provide fast HTTP processing . Grizzly provides Comet (long-lived streaming HTTP connections) support built on top of Grizzly's Asynchronous Request Processing (ARP). With Grizzly ARP, each Comet request isn't holding onto a thread which gives scalability. Bayeuxis a protocol for routing JSON encoded events between clients andservers in a publish subscribe model. Grizzly provides an implementation of Bayeux, which makes it really easy to build Comet applications with dojo, you just configure Glassfish for Comet and configure your Web Application's web.xml for the Grizzly Bayeux servlet then you can use the dojox cometd publish and subscribe methods to send and receive Comet events as described in more detail below.

Grizzly comes with Glassfish , or it can be used separately. To use Comet with Glassfish you just need to add the bold red line to the Glassfish config domain.xml:

Package your war and deploy it on Glassfish, then every request sent to your war's context-path/cometd/will be serviced by the Grizzly Bayeux runtime.

Explanation of the usage of dojox cometd in the sample Slideshow Application

I modified the comet chat example fromhere (originally written by Greg Wilkins), to share a slideshow presentation among all subscribed clients. The image below shows the Comet Slideshow page, which allows the users to share a Slideshow and chat at the same time.

Quick installation and use of dojo with Netbeans

There are 3 ways to install dojo which you can read about at in the book of dojo. A quick and easy way to use dojo with Netbeans is to download the JavaScript libraries from http://dojotoolkit.org/downloads. Create a new NetBeans Web Applications project. Extract the dojo toolkit into the project web directory: .../web , then rename dojo-release-1.1.1/ to src/ this will give you the project structure shown below. I have already done this for the sample project so you do not have to download dojo in order to run the sample.

Loading base dojo and required modules into an application

In order to load dojo into your application, put the relative path to the dojo.js file in a script element in the head section of your HTML page as shown below:

This script element will load the base dojo script which gives you access to all the dojo functionality. The rest of the Java Script for this application is in the file chat.js.

Next in chat.js the application specifies which dojo modules to load, using the dojo.require function (kind of like import in Java):

Code Sample from: chat.js

dojo.require("dojox.cometd");

Dojo is organized into three major layers: Dojo Core, Dijit, and DojoX. DojoX builds on Dojo Core and provides newer extensions to the Dojo toolkit. DojoX cometd implements a Bayeux protocol client for use with a Bayeux server.

Initializing a connection between the dojo client and the Grizzly BayeuxServlet

When a user first loads the slideshow application, he can enter a username and join a slideshow session.

When a user clicks on the Join button, the joinjavascript function is called. In the joinfunction, the call to dojox.cometd.init initialises a connection to the given Comet server, in this case with the Glassfish Grizzly Bayeux servlet (note/cometd/* is the url-pattern for theGrizzly Cometd Servlet configured in the web.xml for the application).

The dojox.cometd.subscribe line subscribes the_chat callback function to the /chat/demochannel. Any time a message is sent to the /chat/demo channel the_chat function will be called.Thedojox.cometd.publish line publishes the message that the user (the name that was entered with the join button) has joined the /chat/demo channel. Subscribers to the /chat/demo channel will get this message.

Publishing the next slide for the Comet Slideshow

When the user clicks on the "Next Slide" button shown below, a javascript funtion is called which publishes the url for the next slide.

When the user clicks on the Next Slide button, the javascript function shown below is called. This function callsroom.next passing the url for the next slide. The function then increments the index for the next slide. The urls for the slides are stored in the slideUrls array shown below.

When a message is published to a Bayeux channel on the server, it is delivered to all clients subscribed to that channel, in this case to the "/chat/demo" channel . In the room.join function shown beforedojox.cometd.subscribe("/chat/demo", room, "_chat")was called to subscribe the _chat callback function to the/chat/demochannel. The_chat callback function, shown below, is called with the published message as an input argument. The _chat callback function updates the browser page by setting the slide dom element innerHTML to an html img tag with the slide url from the published message "<img src='" + slideUrl + "'/>" . This updates the browser page with the image corresponding to the slide URL which was published.

Download the sample code and extract its contents. You should now see the newly extracted directory as<sample_install_dir>/dojoComet, where<sample_install_dir> is the directory where you unzipped the sample package. For example, if you extracted the contents to C:\ on a Windows machine, then your newly created directory should be atC:\dojoComet.

Start the NetBeans IDE. Click Open Project in the File menu and select the dojoComet directory you just unzipped.

Build the project as follows:

Right click the dojoComet node in the Projects window.

Select Clean and Build Project.

Run the project as follows:

Right click the dojoComet node in the Projects window.

Select Run Project.

When you run the project, your browser should display the opening page of the Sample Application (at http://localhost:8080/dojoComet/). Open another browser and set that url to http://localhost:8080/dojoComet/ then enter a name and click on the join button in both browser windows. Then click on the next slide button in one browser window. Both browsers should get updated with the next slide.