Friday May 01, 2009

Preview of 2 Hands On Labs I am working on for JavaOne


I'm Speaking At JavaOne

I'm working on 2 Hands On Labs for JavaOne this year:
  • Building RIA Dojo and JavaFX™ Pet Catalog Clients for MySQL™ backed RESTful Web Services
  • Developing Real-Time Revolutionary Web Applications, Using Comet and Ajax
You can read the HOL details and download some preview documentation and code below:
  • Session ID:       LAB-6771
  • Session Title:     Building RIA Dojo and JavaFX™ Pet Catalog Clients for MySQL™ backed RESTful Web Services
  • Session Abstract:
    • The goal of the Java™ API for RESTful Web Services (JAX-RS) is to provide a high-level declarative programming model for such services that is easy to use and encourages development according to REST tenets. Services built with this API are deployable with a variety of Web container technologies and benefit from built-in support for best-practice HTTP usage patterns and conventions.
      This Hands-on Lab provides an overview of the JAX-RS API and walks developers through the design process for a sample RESTful service.
      Dojo is an open-source DHTML toolkit written in the JavaScript™ programming language. The new JavaFX™ platform brings rich Internet applications to all the screens of your life.
      In the lab, participants will use the NetBeans™ IDE to rapidly develop JAX-RS, Dojo, and JavaFX applications and then deploy them on the GlassFish™ application server, with Java DB or the MySQL™ database.
  • Speakers:       Carol McDonald, Sun Microsystems, Inc.; Sridhar Reddy, Consultant

You can read more about some of the example code for this HOL at
GlassFish and MySQL, Part 4: Creating a RESTful Web Service and JavaFX Client

You can download a preview (some of the slides, docs, code) for this HOL at
Preview subset of slides, doc, code, for Building RIA Dojo and JavaFX™ Pet Catalog Clients for MySQL™ backed RESTful Web Services

  • Session ID:       LAB-5558
  • Session Title:     Developing Real-Time Revolutionary Web Applications, Using Comet and Ajax
  • Session Abstract:  
    • Join the asynchronous Web revolution! Emerging Ajax techniques -- variously called Ajax Push, Comet, and HTTP streaming -- are bringing revolutionary changes to Web application interactivity, moving the Web into the Participation Age. Because Ajax-based applications are almost becoming the de facto technology for designing Web-based applications, it is more and more important that such applications react on the fly, or in real time, to both client and server events. Aajx can be used to enable the browser to request information from the Web server but does not allow a server to push updates to a browser. Comet solves this problem. It is a technology that enables Web clients and Web servers to communicate asynchronously, enabling real-time operations and functions previously unheard of with traditional Web applications to approach the capabilities of desktop applications.
  • Speakers:       Justin Bolter, Sun Microsystems, Inc.; Doris Chen, Sun Microsystems, Inc.; Carol McDonald, Sun Microsystems, Inc.


You can read more about some of the example code for this HOL at
RESTful Web Services and Comet
You can download a preview (some of the slides, docs, code) for this HOL at
Preview subset of slides, doc, code, for Developing Real-Time Revolutionary Web Applications, Using Comet and Ajax

Duke



Thursday Apr 16, 2009

Developing RESTful Web Services with JAX-RS, Netbeans, Glassfish and MySQL

Developing RESTful Web Services with JAX-RS, Netbeans, Glassfish and MySQL

Yesterday I gave a talk at a the Jacksonville Java Users Group (JAXJUG) on Developing RESTful Web Services with JAX-RS, Netbeans, Glassfish, and MySQL.
Jacksonville-Beach-Ocean-View.jpg


You can dowload the StarOffice presentation here

Developing RESTful Web Services with Netbeans and JAX-RS


Content:
Lightweight RESTful approaches have emerged as a popular alternative to SOAP-based technologies for deployment of services on the Internet.

The goal of the Java API for RESTful Web Services (JAX-RS) is to provide a high-level declarative programming model for such services that is easy to use and encourages development according to REST tenets. Services built with this API are deployable with a variety of Web container technologies and benefit from built-in support for best-practice HTTP usage patterns and conventions.

This talk will provides an overview of the design process for a sample RESTful Pet Catalog service using JAX-RS. It shows how to build 2 sample clients for the Pet Catalog service one using the dojo AJAX framework and one using JavaFX.


You can get more information here:

Here is a link to the PDF slides and recorded Webinar
Developing MySQL-Backed RESTful Web Services with Netbeans and JAX-RS

Here is a link to the Article
GlassFish and MySQL, Part 4: Creating a RESTful Web Service and JavaFX Client

Here is a link to the JavaFX code
RESTful Web Service and JavaFX client code

Here is a link to dojo client explanation and code
RESTful Web Service and dojo client explanation and code





Wednesday Mar 25, 2009

Developing MySQL-Backed Applications with Netbeans and Java RESTful Web Services

Yesterday I gave a webinar which talked about how to leverage the latest version of the Netbeans IDE to develop RESTful Web Services and clients deployed on Glassfish with MySQL. The talk gave an overview of the design process for a sample RESTful Pet Catalog service using JAX-R, and discussed how to build 3 sample clients for the Pet Catalog service,  one using the Dojo AJAX framework , one using Comet and one using JavaFX.

You can download the presentation  here:
Developing MySQL-Backed Applications with Netbeans and Java RESTful Web Services

you can watch  a 7 minute screencast on how to build a RESTful Pet Catalog using JAX-RS and dojo here

RESTful Pet Catalog screencast

You can read more about the example RESTful web service and the JavaFX client for the RESTful web service here:

Glassfish and MySQL part 4

You can read more about the Comet client for the RESTful web service here:
RESTful Web Services and Comet

You can read more about the dojo client for the RESTful web service here:
a RESTful Pet Catalog

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

Dojo – An open-source DHTML toolkit written in JavaScript. The Dojo Toolkit includes many utilities that go beyond Ajax. For example, the dojox.comet module simplifies programming Comet applications.

Comet – Techniques that enable a server to push data to client browsers through an HTTP open line of communication.

Friday Aug 29, 2008

RESTful Web Services and Comet

Rick Palkovic and I have written an article about a Comet application which allows users to watch and chat about a slide show. The Application loads the slide URLs from a RESTful Web Service and then uses dojo bayeux with Grizzly on Glassfish to publish the slides and/or text to all the slideshow subscribers. See RESTful Web Services and Comet. RESTful Web Services and Comet

Wednesday Aug 06, 2008

a RESTful Pet Catalog

a RESTful Pet Catalog


This Sample Pet Store Catalog application shows how to expose a  Catalog  as a RESTful Web Service for remote client applications, and it shows how to code a Dojo client which  gets and displays the Web Service responses in a dynamic Ajax table ( Dojo grid). I re-implemented this Sample Catalog application implemented with JAX-WS on the server side and JSF on the client side which is also available in the Java One Metro hands on lab.

Download the RESTful Pet Catalog Code

Dojo is an open source DHTML toolkit written in JavaScript.

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 Catalog Listing page, which allows a user to page through a list of items in a store.
petcatalog

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.
dojonetproj.JPG

Dojo style sheets

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

Code Sample from:  index.html

    <style type="text/css">
      /\* tundraGrid.css matches Dijit Tundra style. \*/
      @import "src/dojox/grid/_grid/tundraGrid.css";
      @import "src/dijit/themes/tundra/tundra.css";
      @import "src/dojo/resources/dojo.css";
      @import "src/dojox/grid/_grid/Grid.css";
    </style>



This will load the the CSS files required by the Dojo grid widget, you can just use  dojox/grid/_grid/Grid.css instead of tundraGrid if you don't want the  tundra style. 

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:

Code Sample from:  index.html

 <script type="text/javascript" src="src/dojo/dojo.js"
           djConfig="isDebug: true, debugAtAllCosts: false,
           parseOnLoad: true">
 </script>




This script element will load the base dojo script which gives you access to all the dojo functionality.

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

Code Sample from:  index.html

 <script type="text/javascript">
   dojo.require("dojox.grid.Grid");
   dojo.require("dojox.grid._data.model");
   dojo.require("dojo.parser");
 </script>


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:
Code Sample from:  index.html

<div id="grid" dojoType="dojox.Grid" model="model" structure="layout">
</div>


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:

Code Sample from:  dynamicTable.js

formatImage = function(value) {
    if (!value)
        return '&nbsp;';   
        return "<img src='" + value + "'/>";   
};

// Data Grid layout
// A grid view is a group of columns
var view1 = {
            cells: [
        [
            {name: 'Name', field: "name"},
            {name: 'Description', field: "description", width: '200px'},
            {name: 'Photo',field: "imagethumburl", formatter: formatImage, width: '120px'},
            {name: 'Price',field: "price"}
        ]
    ]
};
// a grid layout is an array of views.
var layout = [ view1 ];




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 the dojox.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 view
model = new dojox.grid.data.Objects(null,null);

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

// make request to the items web service
function loadTable(page){
    start = page \* batchSize;
    var targetURL = "resources/items/?start="+ encodeURIComponent(start);   
    dojo.xhrGet({
        url: targetURL,
        handleAs: "json",
        load: handleResponse,
        error: handleError
    });
}

The loadTable function calls   dojo.xhrGet to make an XMLHttpRequest to the items 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  items JAX-RS web service. Below is an example of a JSON response from the items JAX-RS web service:

Example json data

{"items":
  {"@uri":"http://host/catalog/resources/items/",
   "item":[
     {"@uri":"http://host/catalog/resources/items/1/",
       "name":"Friendly Cat",
      "description":"This black and white colored cat is super friendly.",     
       "id":"1",
       "imageurl":"http://localhost:8080/CatalogService/images/anthony.jpg"},
     {"@uri":"http://host/catalog/resources/items/2/",
       "name":"Fluffy Cat",
       "description":"A great pet for a hair stylist!
       "id":"2",
       "imageurl":"http://localhost:8080/CatalogService/images/bailey.jpg"}
    ]
  }
}


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  items JAX-RS web service and sets the results in the grid data model.

Code Sample from:  dynamicTable.js

    <script type="text/javascript">
        dojo.addOnLoad(function(){
            loadTable(0);
        });
    </script>


Events for paging

The  "<<"">>" buttons call the next() previous() functions when clicked:

Code Sample from:  index.html

<input type="button" value="<<" onclick="previous();">
</input>
<input type="button" value=">>" onclick="next();">
</input>


The next() function  increments the page number and then calls the loadTable() funtion:

Code Sample from: dynamicTable.js


function next() {
    page =page + 1;
    loadTable(page);
}

function previous() {
    page =page - 1;
    if (page < 0) page = 0;
    loadTable(page);
}


RESTful  Web Services with JAX-RS

The  dojo.xhrGet url: parameter  references the URI  resources/items/ for the items   RESTful web service.  The items 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 items RESTful web service was generated from the item data base table (the sql is in the how to run section). 

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

Code Sample from: ItemsResource.java

// Service URI path "/items/"

@Path("/items/")

public class 
ItemsResource {

  @GET
@ProduceMime("application/json")
    public
ItemsConverter get(@QueryParam("start")
@DefaultValue("0") int start, @QueryParam("max")
            @DefaultValue("4") int max, @QueryParam("expandLevel")
            @DefaultValue("1") int expandLevel, @QueryParam("query")
            @DefaultValue("SELECT e FROM Item e") String query) {
        try {
            ItemsConverter items = new ItemsConverter(
getEntities(start, max, query),
                context.getAbsolutePath(), expandLevel);
            return
items;
        } finally {
            PersistenceService.getInstance().close();
        }
    }


The ItemsResource represents a list of items. The ItemsResource get method returns a list of Item 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 ItemsResource  the URI path is /items/.
  • @GET specifies that the get method supports the HTTP GET method.
  • @ProduceMime specifies the MIME types that a method can produce. Here, the annotation specifies that the get method returns a JSONArray object.  The ItemsConverter class is a JAXB annotated class which is used to marshal a list of Item objects into XML or JSON format.   The getEntities method returns a list of Item entity objects and is explained below.  
  • @QueryParam specifies input parameters for methods.  When the method is invoked, the input value will be injected into the corresponding input argument. 
  • @DefaultValue specifies a default value for an arguement if no input value is given.
Here is an example of an HTTP request for this Web Service:

Request: GET http://host/catalog/resources/items/?start=0


Here is an example of an HTTP response for this Web Service:

Received:
{"items":
  {"@uri":"http://host/catalog/resources/items/",
   "item":[
     {"@uri":"http://host/catalog/resources/items/1/",
       "name":"Friendly Cat",
      "description":"This black and white colored cat is super friendly.",     
       "id":"1",
       "imageurl":"http://localhost:8080/CatalogService/images/anthony.jpg"},
     {"@uri":"http://host/catalog/resources/items/2/",
       "name":"Fluffy Cat",
       "description":"A great pet for a hair stylist!
       "id":"2",
       "imageurl":"http://localhost:8080/CatalogService/images/bailey.jpg"}
    ]
  }
}


The ItemsConverter class is a JAXB annotated class, used to marshal a list of Item objects into XML or  JSON format.  A snippet of the ItemsConverter class is shown below:


Code Sample from: ItemsConverter.java

@XmlRootElement
public class ItemsConverter {

@XmlElement
    public Collection<ItemConverter> getItem(){
     ...
       return items;
    }
    @XmlAttribute
   public URI getUri() {
        return uri;
    }



Java Persistence Query API

The ItemsResource getEntities method uses the Java Persistence API Query object to return a list of items.

Code Sample from: ItemsResource.java

@Path("/items/")

public class 
ItemsResource {

    . . .

    protected Collection<Item> getEntities(int start, int max, String query) {
PersistenceService ps = PersistenceService.getInstance();
        Query query = ps.
createQuery(query);
        query.
setFirstResult(start);
query.setMaxResults(max);
        return query.getResultList();
    }



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 Item entity class which maps to the  CUSTOMER table that stores the item instances. This is a typical Java Persistence entity object. There are two requirements for an entity:
  1. annotating the class with an @Entity annotation.
  2. annotating the primary key identifier with @Id
Because the fields name, description.... are basic mappings from the object fields to columns of the same name in the database table, they don't have to be annotated. 
For more information on Netbeans and JPA see basics of developing a web application using Java™ Persistence API.


Code Sample from: Item.java

@Entity

public class Item implements Serializable {

@Id
    private Long id;

    private String name;
    private String description; 
    private String imageurl; 
    private String state; 
    private BigDecimal price;


    public
Item() { }

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

   . . .

}   




Conclusion
This 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 items, and a dojo client which  gets and displays the Web Service responses in a dynamic Ajax table.

Configuration of the Application for Netbeans 6.5m1 , Glassfish V2, and MySQL


Running the Sample Code

  1. 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.
  2. Start NetBeans IDE. Click Open Project in the File menu and select the catalog directory you just unzipped.
  3. Start the MySQL database as follows:
    • Click the Services tab in the NetBeans IDE.
    • Expand the databases node. You should see the MySQL server database in the list of databases.
      Database list
    • Right-mouse click on the MySQL server database and select Start.
  4. Create the petcatalog database as follows:
    • Right-mouse click on the MySQL server database and select Create Database.
    • Enter the database name catalog. This will open a New Database Connection window. Click O.K. to accept the displayed settings.
  5. Create the tables in the MySQL catalog database as follows:
    • Expand the Drivers node. You should a driver for the catalog database in the list of drivers.
      Driver list
    • Right-mouse click on the catalog driver and select Connect.
    • Right-mouse click on the catalog driver and select Execute Command. This will open up a SQL command window.
    • Copy the contents of the createdbmysql.sql file in the catalog directory and paste the contents into the SQL command window.
    • Click the Run SQL icon Run SQL icon (Ctrl+Shift+E) above the SQL command window.
  6. Build the project as follows:

    • Right click the catalog node in the Projects window.
    • Select Clean and Build Project.

  7. Run the project as follows:

    • Right click the catalog 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/catalog/).

For more Information:




Tuesday Jul 29, 2008

a Dynamic Ajax table example using dojo and RESTful Web Services on Glassfish

a Dynamic Ajax table example using dojo and RESTful Web Services on Glassfish


This Sample Catalog app demonstrates a RESTful Web Service, coded using JAX-RS: Java API for RESTful Web Services (JSR-311) and Java Persistence API, which provides a list of customers, and a Dojo client which  gets and displays the Web Service responses in a dynamic Ajax table ( Dojo grid).

Download the dojo Sample Application Code

Dojo is an open source DHTML toolkit written in JavaScript.

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.

table.jpg


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.
dojonetproj.JPG

Dojo style sheets

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

Code Sample from:  index.html

    <style type="text/css">
      /\* tundraGrid.css matches Dijit Tundra style. \*/
      @import "src/dojox/grid/_grid/tundraGrid.css";
      @import "src/dijit/themes/tundra/tundra.css";
      @import "src/dojo/resources/dojo.css";
      @import "src/dojox/grid/_grid/Grid.css";
    </style>



This will load the the CSS files required by the Dojo grid widget, you can just use  dojox/grid/_grid/Grid.css instead of tundraGrid if you don't want the  tundra style. 

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:

Code Sample from:  index.html

 <script type="text/javascript" src="src/dojo/dojo.js"
           djConfig="isDebug: true, debugAtAllCosts: false,
           parseOnLoad: true">
 </script>




This script element will load the base dojo script which gives you access to all the dojo functionality.

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

Code Sample from:  index.html

 <script type="text/javascript">
   dojo.require("dojox.grid.Grid");
   dojo.require("dojox.grid._data.model");
   dojo.require("dojo.parser");
 </script>


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:
Code Sample from:  index.html

<div id="grid" dojoType="dojox.Grid" model="model" structure="layout">
</div>


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:

Code Sample from:  dynamicTable.js

// Data Grid layout
// A grid view is a group of columns
var view1 = {
            cells: [
                [
                    {name: 'Company', field: "name"},
                    {name: 'City', field: "city"},
                    {name: 'State',field: "state"},
                    {name: 'Zip',field: "zip"}
                ]
            ]
};
// a grid layout is an array of views.
var layout = [ view1 ];


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

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 the dojox.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 view
model = 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);       
}  

// make request to the customers web service
function loadTable(page){
    start = page \* batchSize;
    var targetURL = "resources/customers/?start="+
                      encodeURIComponent(start);   
    dojo.xhrGet({
        url: targetURL,
        handleAs: "json",
        load: handleResponse,
        error: handleError
    });
}


The loadTable function calls   dojo.xhrGet to 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:

Example json data

{"customers":
  {"@uri":"http://host/dojoRest/resources/customers/",
   "customer":[
     {"@uri":"http://host/dojoRest/resources/customers/1/",
       "name":"JumboCom",
      "city":"Fort Lauderdale",     
       "state":"FL",
       "zip":"33015"},
     {"@uri":"http://host/dojoRest/resources/customers/2/",
       "name":"Livermore Enterprises",
       "city":"Miami",
       "state":"FL",
       "zip":"33055"}
    ]
  }
}


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.

Code Sample from:  dynamicTable.js

    <script type="text/javascript">
        dojo.addOnLoad(function(){
            loadTable(0);
        });
    </script>


Events for paging

The  "<<"">>" buttons call the next() previous() functions when clicked:

Code Sample from:  index.html

<input type="button" value="<<" onclick="previous();">
</input>
<input type="button" value=">>" onclick="next();">
</input>


The next() function  increments the page number and then calls the loadTable() funtion:

Code Sample from: dynamicTable.js


function next() {
    page =page + 1;
    loadTable(page);
}

function previous() {
    page =page - 1;
    if (page < 0) page = 0;
    loadTable(page);
}


RESTful  Web Services with JAX-RS


The  dojo.xhrGet url: 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 :

Code Sample from: CustomersResource.java


// Service URI path "/customers/"

@Path("/customers/")

public class CustomersResource {

  @GET
@ProduceMime("application/json")
  public
CustomersConverter get(@QueryParam("start")
@DefaultValue("0") int start, @QueryParam("max")
            @DefaultValue("4") int max, @QueryParam("expandLevel")
            @DefaultValue("1") int expandLevel,
            @QueryParam("query")
            @DefaultValue("SELECT e FROM Customer e") String query{


        try {
            CustomersConverter custs = new CustomersConverter(
                getEntities
(start, max, query),
                context.getAbsolutePath(), expandLevel);
            return
custs;
        } finally {
            PersistenceService.getInstance().close();
        }
    }


The CustomersResource represents a list of customers. The CustomersResource get method 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 the get method supports the HTTP GET method.
  • @ProduceMime specifies the MIME types that a method can produce. Here, the annotation specifies that the get method returns a JSONArray object.  The CustomersConverter class is a JAXB annotated class which is used to marshal a list of Customer objects into XML or JSON format.   The getEntities method returns a list of Customer entity objects and is explained below.  
  • @QueryParam specifies input parameters for methods.  When the method is invoked, the input value will be injected into the corresponding input argument. 
  • @DefaultValue specifies a default value for an arguement if no input value is given.
Here is an example of an HTTP request for this Web Service:

Request: GET http://host/dojoRest/resources/customers/?start=0


Here is an example of an HTTP response for this Web Service:

Received:
{"customers":
  {"@uri":"http://host/dojoRest/resources/customers/",
   "customer":[
     {"@uri":"http://host/dojoRest/resources/customers/1/",
       "name":"JumboCom",
      "city":"Fort Lauderdale",     
       "state":"FL",
       "zip":"33015"},
     {"@uri":"http://host/dojoRest/resources/customers/2/",
       "name":"Livermore Enterprises",
       "city":"Miami",
       "state":"FL",
       "zip":"33055"}
    ]
  }
}


The CustomersConverter class is a JAXB annotated class, used to marshal a list of Customer objects into XML or  JSON format.  A snippet of the CustomersConverter class is shown below:


Code Sample from: CustomersConverter.java

@XmlRootElement
public class CustomersConverter {

@XmlElement
    public Collection<CustomerConverter> getCustomer(){
     ...
       return items;
    }
    @XmlAttribute
   public URI getUri() {
        return uri;
    }



Java Persistence Query API

The CustomersResource getEntities method uses the Java Persistence API Query object to return a list of customers.

Code Sample from: CustomersResource.java


@Path("/customers/")

public class CustomersResource {

    . . .

    protected Collection<Customer> getEntities(int start, int max,
        String query) {

        PersistenceService ps = PersistenceService.getInstance();
        Query query = ps.
createQuery(query);
        query.
setFirstResult(start);
        query.
setMaxResults(max);
        return query.getResultList();
    }



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 Customer entity 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:
  1. annotating the class with an @Entity annotation.
  2. annotating the primary key identifier with @Id
Because the fields name, description.... are basic mappings from the object fields to columns of the same name in the database table, they don't have to be annotated. 
For more information on Netbeans and JPA see basics of developing a web application using Java™ Persistence API.


Code Sample from: Customer.java


@Entity

public class Customer implements Serializable {

    @Id
    private Integer customerId;

    private String name;
    private String addressline1;   
    private String city;  
    private String state; 
    private String zip;


    public
Customer() { }

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



}   




Conclusion
This 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 and install NetBeans 6.1 bundled with GlassFish V2
  • Alternatively you can  Download and install GlassFish V2 separately.

Open and Run the Sample code:

  1. 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 at C:\\dojoRest.

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

  3. Build the project as follows:

    • Right click the dojoRest node in the Projects window.
    • Select Clean and Build Project.

  4. 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/).

References:



Tuesday Jul 01, 2008

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

This Sample Slideshow app demonstrates the usage of the dojo Ajax framework, Comet, Bayeux, with Grizzly and Glassfish.

cometgrizzly

Download the dojo Comet Sample Application Code

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.

comet http
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.   Bayeux is a protocol for routing JSON encoded events between clients and servers 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:

Code Sample from:  index.html
<http-listener acceptor-threads="1" address="0.0.0.0" 
  blocking-enabled="false" default-virtual-server="server" 
  enabled="true" family="inet" id="http-listener-1" port="8080" 
  security-enabled="false" server-name="" xpowered-by="true">
   <property name="cometSupport" value="true"/>
</http-listener>

Enabling Bayeux in GlassFish

to enable Bayeux on Glassfish, add the following to your Web application web.xml :

Code Sample from:  index.html

<servlet>
   <servlet-name>Grizzly Cometd Servlet</servlet-name>
   <servlet-class>
	com.sun.grizzly.cometd.servlet.CometdServlet
   </servlet-class>
   <init-param>
      <description>
	expirationDelay is the long delay before a request is
	resumed. -1 means never.
      </description>
      <param-name>expirationDelay</param-name>
      <param-value>-1</param-value>
   </init-param>
   <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
   <servlet-name>Grizzly Cometd Servlet</servlet-name>
   <url-pattern>/cometd/\*</url-pattern>
</servlet-mapping>	

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 from here (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.

comet slideshow



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:

Code Sample from:  index.html

<script type="text/javascript" src="src/dojo/dojo.js"></script>
<script type="text/javascript" src="chat.js"></script>



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 join javascript function is called.  In the join function, 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 the Grizzly Cometd Servlet configured in the web.xml for the application).

Code Sample from:  chat.js
var room = {
 ...
 join: function(name){

   dojox.cometd.init(
"/cometd");
   dojox.cometd.subscribe("/chat/demo", room, "_chat");
   dojox.cometd.publish("/chat/demo",
      { user: room._username,
        join: true, chat : room._username+" has joined"});
 }


The dojox.cometd.subscribe line subscribes the _chat callback function to the /chat/demo channel. Any time a message is sent to the  /chat/demo channel the _chat function will be called.
The dojox.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.



Code Sample from:  index.html
<input id="previousB" class="button" type="submit" name="previous" value="Previous Slide"/> 
<input id="nextB" class="button" type="submit" name="next" value="Next Slide"/>



When the user clicks on the Next Slide button, the  javascript function shown below is called. This function calls room.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. 

Code Sample from:  widget.json
var room = {
...
  _init: function(){

    var slideUrls=[
            "/dojoComet/images/image0.jpg",
            "/dojoComet/images/image1.jpg",
            "/dojoComet/images/image2.jpg",
            "/dojoComet/images/image3.jpg",
            "/dojoComet/images/image4.jpg",
            "/dojoComet/images/image5.jpg"];
    var i=0;

element=dojo.byId('nextB');
    element.onclick = function(){
       room.next( slideUrls[i]);
       if (i>=
slideUrls.length){i=0;}
       else {i++;}
    }

    element=dojo.byId('previousB');
    element.onclick = function(){
       room.next( slideUrls[i]);
       if (i<=0){i=0;}
       else {i--;}
    }

  }
...


The function  room.next, shown below, calls dojox.cometd.publish to publish the next slide url (input argument)  to the /chat/demo channel. Subscribers   to the /chat/demo channel will get this message.


Code Sample from:   chat.js
var room = {
    ...

    next: function(text){
        dojox.cometd.publish("/chat/demo", {slide: text});
    }
    ...
}


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 before dojox.cometd.subscribe("/chat/demo", room, "_chat") was called  to subscribe the _chat callback function to the /chat/demo channel.   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.

Code Sample from: chat.js
var room = {
    ...
    _chat: function(message){
        var slide=dojo.byId('slide');
        var slideUrl=message.data.slide;
        slide.innerHTML ="<img src='" + slideUrl + "'/>";
    ...
}



Conclusion
This concludes the sample application which demonstrates the usage of the dojo Ajax framework, Comet, Bayeux, with Grizzly and Glassfish.

Running the Sample Code

The sample code  is available as a NetBeans project. You can build and run the sample code using the NetBeans IDE.

Setting Things Up

  • Download and install NetBeans 6.1 bundled with GlassFish V2
  • Alternatively you can  Download and install GlassFish V2 separately.
  • To use Comet with Glassfish you just need to add the bold red line to the Glassfish config  domain.xml (in the directory glassfish/domains/domain1/config ):
    Code Sample from:  index.html
    <http-listener acceptor-threads="1" address="0.0.0.0" 
      blocking-enabled="false" default-virtual-server="server" 
      enabled="true" family="inet" id="http-listener-1" port="8080" 
      security-enabled="false" server-name="" xpowered-by="true">
       <property name="cometSupport" value="true"/>
    </http-listener>
    
  • Bayeux and dojo are already configured in the sample code.

Open and Run the Sample code:

  1. 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 at C:\\dojoComet.

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

  3. Build the project as follows:

    • Right click the dojoComet node in the Projects window.
    • Select Clean and Build Project.

  4. 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.  

For more Information:


About

caroljmcdonald

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today