Java Stammtisch Carol McDonald

Thursday Apr 16, 2009

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

Yesterday I gave a talk at a the Ruby Jax User Group on Groovy and Grails with Netbeans , Glassfish and MySQL. The Jacksonville JUG  was invited too, it was held at the hashrocket office , which has the best view I've ever seen from an office building:
beach.jpg

You can dowload the presentation here
Groovy and Grails with Netbeans , Glassfish and MySQL

Content:
     Grails Basics and Netbeans 6.5
     Domain-driven development with Grails
     Orchestrating requests with controllers
     Groovy Views with GSP
     configuring for MySQL
     running on Glassfish  

You can read more about the code examples here:

Building a Grails Pet Catalog using Netbeans 6.5 and MySQL

Combining Groovy, Grails, MySQL, and the Java Persistence API

Writing Your First Ruby-on-Rails Web Application

Sample Catalog Application using using JRuby and Rails
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.

Thursday Mar 19, 2009


Here is a screencast about MySQL  for Developers

If you are a developer using MySQL, you should learn enough to take advantage of its strengths, because having an understanding of the database can help you develop better-performing applications. This session will talk about MySQL database design and SQL tuning for developers. Some topics include:
  • MySQL Storage Engine Architecture
  • Schema, the basic foundation of performance
  • Think about performance when choosing Data Types
  • Indexes and SQL tuning
  • Understanding SQL Statements using EXPLAIN
  • Scans and seeks
  • Solving performance problems in your queries
  • A Few Things to consider for JPA/Hibernate devlopers, Lazy loading and Optimistic locking


You can download the slides here
https://techdayscode.dev.java.net/servlets/ProjectDocumentList?folderID=9890

You can read more about this at
MySQL for Developers
GlassFish and MySQL, Part 4: Creating a RESTful Web Service and JavaFX Client
High Performance MySQL book
MySQL Pluggable Storage Engine Architecture
MySQL Storage Engine Architecture, Part 2: An In-Depth Look
Optimizing Queries with EXPLAIN
Java Persistence with Hibernate book
Jay Pipes blog
Colin Charles blog
mysql performance blog
Ronald Bradford blog
Taking JPA for a Test Drive
Pro EJB 3: Java Persistence API
Pro MySQL, Chapter 6: Benchmarking and Profiling





Tuesday Mar 10, 2009

This is the fourth article in a series of articles on GlassFish and MySQL.
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.

Glassfish and MySQL part 4

Wednesday Feb 11, 2009

grailsexample


Building a Grails Pet Catalog using Netbeans 6.5 and MySQL


This Catalog Sample app demonstrates the usage of Groovy and Grails to implement pagination of data sets for a Store Catalog.
download Catalog sample code

Overview of the Technologies and Frameworks in the Sample Application

Grails aims to bring the "coding by convention" paradigm to Groovy. It's an open-source web application framework that leverages the Groovy language and complements Java Web development.

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

MySQL is the world's most popular open-source database. It offers consistently fast performance, high reliability and ease of use.

The NetBeans IDE 6.5 , in addition to full support of all Java platforms (Java SE, Java EE, Java ME, and JavaFX), has support for software development with PHP, Ajax and JavaScript, Groovy and Grails, Ruby and Ruby on Rails, and C/C++.  Netbeans 6.5 feature highlights for Groovy and Grails:

  • Develop pure Groovy apps or use Groovy in Java SE projects
  • Groovy editor with code completion, highlighting, and more
  • Grails web application framework
  • Open existing Grails applications without adding metadata

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.

mvc.gif



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.




Setting Things Up:

  1. If MySQL is already not already installed, then download MySQL  and install it.

  2. Download and install Netbeans 6.5 bundled with Glassfish v3 Prelude.

  3. Download and install Grails.

  4. Start NetBeans IDE.  

  5. In the Netbeans IDE,  select Tools Options Groovy and set the location of the Grails package, which you installed using the Glassfish v3 updatetool.



Creating the Catalog Database Item table:
  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. In the Netbeans IDE,  Click Open Project in the File menu and select the catalog directory you just unzipped.
    The file  "/catalog/grails-app/conf/DataSource.groovy" is configured for  MySQL.

  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.
      databaselist.jpg
    • Right-mouse click on the MySQL server database and select Start.

  4. Create the catalog database as follows:
    • Right-mouse click on the MySQL server database and select Create Database.
    • Enter the database name petcatalog and userid root and password admin. 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 see a driver for the petcatalog database in the list of drivers.
      driverlist.jpg
    • Right-mouse click on the petcatalog driver and select Connect.
    • Right-mouse click on the petcatalog driver and select Execute Command. This will open up a SQL command window.
    • Copy the contents of the catalog.sql file in the <sample_install_dir>/Catalog directory and paste the contents into the SQL command window.
    • Click the Run SQL icon runsql.jpg (Ctrl+Shift+E) above the SQL command window.

  6. Ensure that the username and password settings in the catalog\grails-app\conf\DataSource.groovy file are the same as the corresponding property settings in NetBeans IDE 6.5 for your MySQL server database.
Running the Sample Code:
  1. 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/).



How to Create the Catalog Sample Application with Netbeans 6.5 and MySQL

Creating the Application
  1. Run the "grails create-app" command from the IDE, by using  the IDE "Grails Application" project template to create a new Grails application as follows:

    • Choose File > New Project (Ctrl-Shift-N) and then select "Grails Application" from the "Groovy" category. Click Next.
    • In Project Name, type "catalog"; in Project Location, select the folder where the application will be created. Click Finish.


      The IDE runs the "grails create-app" command, showing the output in the Output window. The Projects window should show you this:


      Expand the folders and have a look at the source structure created by the IDE via the Grails scripts. Also look at the generated files and notice that many of them have default values filled in.

Configure Your Grails app data source for MySQL database

Configuring the data source is a simple matter of changing the values for the desired database and driver and placing the driver jar file in the <..>/lib directory.
  1. Download MySQL Connector/J 5.1.6 from here.
  2. Extract the bundle and copy the  "mysql-connector-java-5.1.6-bin.jar" to the "lib" directory of your Grails application: catalog\lib.
  3. Double click on the file "catalog\grails-app\conf\DataSource.groovy" to edit in order to change the values for MySQL configuration. The updated file looks like this (changes highlighted in red):


    Code Sample from: catalog\grails-app\conf\DataSource.groovy

    dataSource {
        pooled = true
        driverClassName = "com.mysql.jdbc.Driver"
        username = "root"
        password = ""   // your mysql password here
        dialect = "org.hibernate.dialect.MySQL5InnoDBDialect"
    }
    hibernate {
        cache.use_second_level_cache=true
        cache.use_query_cache=true
        cache.provider_class='com.opensymphony.oscache.hibernate.OSCacheProvider'
    }
    // environment specific settings
    environments {
        development {
            dataSource {
                dbCreate = "update"  // one of 'create', 'create-drop','update'
                url = "jdbc:mysql://localhost/petcatalog"
            }
        }
        test {
            dataSource {
                dbCreate = "update"
                url = "jdbc:mysql://localhost/petcatalog"
            }
        }
        production {
            dataSource {
                dbCreate = "update"
                url = "jdbc:mysql://localhost/petcatalog"
            }
        }
    }



    Being in production, it's recommended to use InnoDB tables instead of MyISAM tables. This can be easily specified by using the dialect as explained here. More details about the contents of "DataSource.groovy" can be found here.


Creating the Domain Class
  1. use the IDE to run the "grails create-domain-class" script as follows:
    • Right-click on the Domain Classes node and choose New > Grails Domain Class.


    • Name the domain class "Item" and click Finish. The "Item.groovy" domain class is created in the Domain Classes node.


  2. Double click on the catalog\grails-app\domain\Item.groovy class to open it in the editor and add the attributes shown in red below to the item class.
    Code Sample from: catalog\grails-app\domain\Item.groovy

    class Item {
      Long id
      String name
      String description
      String imageurl
      String imagethumburl
      BigDecimal price

    }


The Model - Grails Domain Classes

The Model is your application's persistent business domain objects. A Grails domain object instance represents a row in a database table.  The command grails create-domain-class Item generates the Item.groovy class shown below corresponding to the item database table.

After model code generation you have to add the domain object's attributes and relationships.


Code Sample from: domain\Item.groovy

class Item {
  Long id
  String name
  String description
  String imageurl
  String imagethumburl
  BigDecimal price

}





SQL  Sample for items table

CREATE TABLE item (
  id INT NOT NULL,
  product_id BIGINT NOT NULL,
  name VARCHAR(30) NOT NULL,
  description VARCHAR(500) NOT NULL,
  imageurl VARCHAR(55),
  imagethumburl VARCHAR(55),
  price DECIMAL(14,2) NOT NULL,
  primary key (id),

);


Groovy with Grails dynamically generates getters and setters and the dynamic methods Item.save(), Item.delete(),  Item.list(), Item.get() to retrieve/update data from/to the db table.

Grails Object Relational Mapping (GORM) is currently built on top of Hibernate but you don't have to know Hibernate to use it.

Creating the Controller and Views
  1. use the "grails generate-all" script to create a controller and views for the domain class as follows:
    • Right-click the Controllers node and choose New > Grails Controller.


    • The Item controller and Item views are generated.


The Controller

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 the list action method in the item controller class shown below.     Grails Scaffolding provides 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 command generate-all Item generates the Item controller and the List, Show, Create, Edit Groovy Server Pages for the Item domain object. The ItemController list action renders a view with a paginated list of item objects.

Code Sample from: catalog\grails-app\controllers\ItemController.groovy

class ItemController {

def index = { redirect(action:list,params:params) }

  def list = {
    if(!params.max) params.max = 10
    [ itemInstanceList: Item.list( params ) ]
  }
. . .


When a URL has a controller but no action (e.g. http://localhost:8080/catalog/item/  ), Grails defaults to the index action. In the ItemController code the  index action method redirects to the list action.  The ItemController list action 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 itemInstanceList variable  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 catalog\grails-app\views\item\list.gsp .



Running the Application

The catalog Grails application is ready to run:.
  1. Right-click the application and choose "Run".

  2. When you run the project, your browser should display the opening page of the Sample Application (at http://localhost:8080/catalog/) . If the browser does not open automatically, paste the URL into a browser and then you'll see your application.



  3. Click the "ItemController" link and you'll see this:


Modifying The View

The view layer generates a web page, using data from domain objects provided by the controller. In Grails, the view is rendered using Groovy Server Pages

Modifying the List View GSP

  1. Copy the sub directory images from the sample application directory catalog\web-app\ to your application's catalog\web-app\  directory.
  2. Double click on the file "catalog\grails-app\views\item\ list.gsp" to edit in order to modify the item list table. Make the changes highlighted in red):
    Code Sample from: grails-app\views\item\list.gsp

    <table>
       <thead>
         <tr>
    <g:sortableColumn property="name" title="Name" />
            <g:sortableColumn property="imagethumburl" title="Photo" />
            <g:sortableColumn property="price" title="Price" />
         </tr>
       </thead>
       <tbody>
    <g:each in="${itemInstanceList}" status="i" var="itemInstance">
            <tr class="${(i % 2) == 0 ? 'odd' : 'even'}">
    <td>
                  <g:link action="show" id="${itemInstance.id}">
                    ${fieldValue(bean:itemInstance, field:'name')}</g:link>
               </td>
               <td>
                  <img src="${itemInstance.imagethumburl}" alt="Pet" />
               </td>
               <td>
                  ${fieldValue(bean:itemInstance, field:'price')}
               </td>
            </tr>
         </g:each>
      </tbody>
     </table>

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


    The view uses instance variables set by the controller to access the data it needs to render the GSP.

    GSP has a GroovyTagLib similar to the  JSP tag library. <g: are GroovyTags.

    <g:sortableColumn
           The sortableColumn tag renders a sortable column to support sorting in tables.

    <g:each in="${itemInstanceList}" status="i" var="itemInstance">
    loops through each object in the itemInstanceList variable, which is an ordered ArrayList of Item model objects,  and assigns each Item model object to the iteInstance variable.

    <g:link action="show" id="${itemInstance.id}"> ${fieldValue(bean:itemInstance, field:'name')} </g:link>
    the <g:link> GroovyTag creates an html anchor tag href 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 variable item:
    <a href="/catalog/item/show/2">Friendly Cat</a>
    <img src="${itemInstance.imagethumburl}" alt="Pet" />
    sets the HTML img tag to the item's imagethumburl attribute. 

    ${fieldValue(bean:itemInstance, field:'price')}
    displays the value of the  item 's price attribute .

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

  3. Save your modifcations in the editor. Click reload current page on your browser. The Item List page should now look like the image below:


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 show action in the ItemController passing 1 to the method as the id of the params parameter hash. The show action of the ItemController class is shown below. The ItemController show action renders a view showing the details of the item object corresponding to the id parameter.

Code Sample from: grails-app\controllers\ItemController.groovy

 def show = {
   def itemInstance = Item.get( params.id )

   if(!itemInstance) {
      flash.message = "Item not found with id ${params.id}"
      redirect(action:list)
   }
   else { return [ itemInstance : itemInstance ] }
 }



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

Modifying the Show View GSP

After executing code in the action, the show action renders the catalog\grails-app\views\item\show.gsp.
  1. Double click on the file "catalog\grails-app\views\item\show.gsp" to edit in order to modify the item show view. Make the changes highlighted in red below:

    Code Sample from: catalog\grails-app\views\item\show.gsp

     <table>
         <tbody>
    <tr class="prop">
                 <td valign="top" class="name">Name:</td>
                 <td valign="top" class="value">${itemInstance.name}</td>
             </tr>
             <tr class="prop">
                 <td valign="top" class="name">Description:</td>
                 <td valign="top" class="value">${itemInstance.description}</td>
             </tr>
             <tr class="prop">
                 <td valign="top" class="name">Photo:</td>
                 <td><img src="${itemInstance.imageurl}" alt="Pet" /></td>
             </tr>
             <tr class="prop">
                 <td valign="top" class="name">Price:</td>
                 <td valign="top" class="value">${itemInstance.price}</td>
             </tr>
         </tbody>
     </table>



    ${itemInstance.description}
    displays the value of the  item 's description attribute.
    <img src="${itemInstance.imageurl}" />
    sets the HTML image tag for the item's imageurl attribute.
    ${itemInstance.price}
    displays the value of the  item's price attribute.

  2. Save your modifcations in the editor. Click reload current page on your browser.
    The image below shows the resulting page for the url http://host/catalog/item/show/1, which displays the item 1's details:



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 replace the Grails logo with a title and parrot image at the top of the Pet Catalog pages,  put this table in the catalog\grails-app\views\layouts\main.gsp  layout page:

Code Sample from: app/views/layouts/main.gsp

<table>
  <tr>
   <td>Pet Catalog</td>
   <td>
     <img src="${createLinkTo(dir:'images',file:'pet_logo.jpg')}"/>
   </td>
 </tr>
</table>


The image below shows the result on the show page after modifying main.gsp layout page :





Running you Grails app on Glassfish v2:

Netbeans does not yet support deploying grails app directly to Glassfish, but you can create a WAR file and deploy it on Glassfish as follows:
  1. If Jetty is running stop it: click on the IDE Services Tab, Under the Jetty server right-click on the catalog app and select Stop

  2. Right-click on the catalog project node and choose Create War File.

  3. Rename the catalog-0.1.war file to catalog.war. Copy the  catalog.war file from your catalog directory to your Glassfish installation glassfish-v2ur2\domains\domain1\autodeploy  directory. Start Glassfish.

    Enter the URL  http://localhost:8080/catalog/  in your browser, you should see the home page of the Sample Application.

Running you Grails app on Glassfish v3:

GlassFish v3 Prelude is a lightweight Web 2.0 development and deployment platform built on a modular OSGi-based architecture. Developers can benefit from a dynamically extensible and embeddable platform with support for existing Java Web technologies, JRuby, and Groovy. GlassFish Support For Grails Framework adds the Grails framework to the GlassFish application server and allows development and easy deployment of Grails applications. Applications can be deployed in shared or standalone mode. Shared mode allows library reuse and results in much smaller war files.
  1. Install the Grails package to Glassfish v3 using the updatetool.   Start the GlassFish Update Center by issuing the following command: GF_install\updatecenter\bin\updatetool. Check the GlassFish Support for Grails Framework checkbox in the GlassFish Update Center and click Install.
  2. Read the Glassfish Getting started with Grails.

Conclusion

This concludes the sample application which demonstrates how to work with Groovy and Grails  to page through a list of  Item Model objects which are retrieved using Item Controller action methods, and displayed using Item View GSPs.

References


Saturday Feb 07, 2009


Pet Catalog Photos : JavaFX Example Application

Pet Catalog Photos is a simple JavaFX application that displays pet photos retrieved from a RESTful Pet Catalog app (implemented using JAX-RS) described in an earlier blog entry and in this screencast.  This JavaFX example is a modification of the Interesting Photos : JavaFX Example Application.

catalogclient.jpg


Understanding the Code


Code Sample from: main.fx

// Application User Interface
def stage = Stage {
    title: "Pet Catalog"
    resizable: false
    x: bind stageX with inverse
    y: bind stageY with inverse
    width: stageWidth
    height: stageHeight
    visible: true
    style: StageStyle.TRANSPARENT
    scene: Scene {
        content: Group {
            content: bind stageContent
            clip: Rectangle {
                width: stageWidth
                height: stageHeight
                arcWidth: 20
                arcHeight: 20
            }
        }
        fill: Color.TRANSPARENT
    }
}


Stage is the  top level container window required to display any visible JavaFX objects. The variables title, width and height define the the text that appears on the window's top border and its height and width.
The scene variable defines an instance of the Scene object literal, which sets the area in which you can place the JavaFX objects.
Scene is a drawing surface for graphical content and a container that holds the scene graph nodes. It can be added to Stage, and JavaFX renders everything on a scene.
The scene instance variable has a content variable that is used to hold JavaFX graphical elements and defines the graphical content of the application. Here the content consists of a Group Node . The Group Node has a  content variable which is a sequence of child Nodes that will be rendered in order whenever this Group is rendered. The Group Node has a clip variable which specifies a Rectangle which defines the the clipping shape for this Group Node.

stage5_1_1_1.JPG

The Group Node content variable has a data binding  with stageContent.  Data binding allows creating a direct and immediate relationship between two variables or between a variable and the outcome of a function or an expression.   stageContent  is a sequence of Nodes as shown in the code below.  Node - is an element in a scene graph. The following visual objects are examples of javafx.scene.Node implementations: javafx.scene.image.ImageView, javafx.scene.media.Mediaview, javafx.ext.swing.*, javafx.scene.shape.*, and javafx.scene.text.Text. These are leaf nodes, which cannot have a child element.

Code Sample from: main.fx

// Application User Interface
var stageContent: Node[];

stageContent = [
        bgImage, titleBar, nextButton, backButton, closeButton,
        titleText, statusText, thumbImageViewGroup, fullImageView
];

stage4.gif
A grid of ImageView is added to Scene of Stage.

The thumbImageViewGroup variable has a data binding  with thumbImageViews which is a sequence of ThumbImageView which extends ImageView. ImageView is a Node used for painting images loaded with Image class.  The code below shows how the  thumbImageViews sequence is initialized to a  grid of  3 columns and 3 rows of  ThumbImageView .

Code Sample from:  main.fx

var thumbImageViews: ThumbImageView[]; // Thumbnail images
for(col in [0..2]) {
    for(row in [0..2]) {
        def thumbImageView = ThumbImageView {
            x: thumbBaseX + (col * (thumbSize + thumbSpace))
            y: thumbBaseY + (row * (thumbSize + thumbSpace))
            fitWidth: thumbSize
            fitHeight: thumbSize
        }
        insert thumbImageView into thumbImageViews;
    }
}
var thumbImageViewGroup = Group {
    content: bind thumbImageViews
}


calling the RESTful  Pet Catalog Web Service 


Information and URLs for pet photos is obtained by performing an HTTP GET request on a RESTful Catalog service by using the JavaFX asynchronous HTTP API (javafx.io.http.HttpRequest).  HttpRequest allows one to specify a location and method and start a HTTP operation with the function enqueue().  The content of the HTTP response can be accessed in the onInput callback function. onInput calls the PhotoPullParser.parse function to parse the XML.The onDone Callback is invoked when the request has finished execution, onDone calls the updateImages() function, explained later, which updates the images displayed in the Photo-Grid. 


Code Sample from: main.fx

function loadImageMetadata() {
    var start=page * 9;  
    var request: HttpRequest = HttpRequest {

        location: "http://localhost:8080/catalog/resources/items/?start={start}&max=9"
        method: HttpRequest.GET

        onInput: function(input: java.io.InputStream) {                            
             var parser = PhotoPullParser{};
             photos = parser.parse(input);    
        }

        onDone: function() {
             updateImages();
        }
    }
    request.enqueue();
}


The response XML document contains a list of information about available photos. The document contains the following information about each photo:

  • id
  • imagethumburl
  • imageurl
  • server
  • name
  • price
  • productid
  • description
Here is example XML returned from the RESTFul Catalog Service:

 <items uri="http://localhost:8080/catalog/resources/items/">
       <item uri="http://localhost:8080/catalog/resources/items/1/">
           <description>This black and white colored cat is super friendly./description>
           <id>1</id>
           <imagethumburl>http://localhost:8080/catalog/images/anthony-s.jpg</imagethumburl>
           <imageurl>http://localhost:8080/catalog/images/anthony.jpg</imageurl>
           <name>Friendly Cat</name>
           <price>307.10</price>
           <productid>feline01</productid>
       </item>
   ...
   </items>


The response document is parsed by using the JavaFX XML pull parser (javafx.data.pull.PullParser) to extract information about the photos.
The parser supplies a sequence of Events as it process the document under application control. XML and JSON are the two data formats currently supported.  The PullParser can be used with the onEvent callback, which reports the current parse event.  The onEvent callback shown below parses the xml item elements into an instance of the Photo class. When the item END_ELEMENT , </item>, is reached,  the photo
variable is inserted into the photos sequence.

Code Sample from: PhotoPullParser.fx
import javafx.data.pull.PullParser;

public class PhotoPullParser {

  public function parse(input: InputStream): Photo[] {

    // Information about all catalog photos
    var photos: Photo[];
    var photo: Photo;

    // Parse the input data (Photo Metadata) and construct Photo instance
    def parser = PullParser {

        input: input

        onEvent: function(event: Event) {
            if (event.type == PullParser.START_ELEMENT) {
                if(event.qname.name == "item" and event.level == 1) {
                    photo = Photo { };
                }
            } else
            if (event.type == PullParser.END_ELEMENT) {
                if(event.qname.name == "item" and event.level == 1) {
                   insert photo into photos;
                } else
                if(event.qname.name == "id" and event.level == 2) {
                    photo.id = event.text;
                } else
                if(event.qname.name == "name" and event.level == 2) {
                    photo.name = event.text;
                } else
                if(event.qname.name == "imagethumburl" and event.level == 2) {
                    photo.imagethumburl = event.text;
                } else
                if(event.qname.name == "imageurl" and event.level == 2) {
                    photo.imageurl = event.text;
                } else
                if(event.qname.name == "description" and event.level == 2) {
                    photo.description = event.text;
                } else
                if(event.qname.name == "productid" and event.level == 2) {
                    photo.productid = event.text;
                }
            }
        }
    }
    parser.parse();
    return photos;
  }
}

A sequence of photo objects is constructed by parsing the response XML.

Code Sample from: Photo.fx

public class Photo {
    public var id: String;
    public var imagethumburl: String;
    public var imageurl: String;
    public var name: String;
    public var price: String;
    public var description: String;
    public var productid: String;
}



The onDone Callback is invoked when the HttpRequest has finished execution, onDone calls the updateImages() function, shown below.


Code Sample from:  main.fx

// Load image and data specified in given Photo object
function loadImage(photo: Photo, thumbImageView: ThumbImageView): Void {
    thumbImageView.image = Image {
        url: "{photo.imagethumburl}";
        width: thumbSize
        height: thumbSize
        backgroundLoading: true
        placeholder: thumbImageView.image
    };
    thumbImageView.photo = photo;

// Update images displayed in Photo-Grid
function updateImages() {
    for(i in [0..8]) {
        var photoIndex = i;
        loadImage(photos[photoIndex], thumbImageViews[i]);
    }
}

updateImages updates the images displayed in the thumbImageViewGroup by  updating the thumbImageView Image URLs to the photo URLs parsed from the HTTP response. The photos are then fetched and displayed in Stage as a grid. The imagethumburl , imageurl are used to retrieve and then display photos. The ImageView class knows how to retrieve the image using the URL and display it. Once the photo is retrieved, it is displayed in Scene of Stage through the use of data binding.


If the user clicks a thumb photo, the normal photo is loaded and shown.

catalogclientlarge.jpg


When the user clicks a thumb photo, the ThumbImageView onMouseClicked function sets the fullImageView url to the clicked photo's larger image url and sets the fullImageView show variable to true.


Code Sample from:  main.fx

// Initialize fullscreen ImageView
var fullImageView = FullImageView {
    translateX: thumbBaseX
    translateY: thumbBaseY
    visible: false
}

// To display thumb image
class ThumbImageView extends ImageView {

    public override var onMouseClicked = function(e:MouseEvent) {   
      // Load larger image
      fullImageView.image = Image {
         url: "{photo.imageurl}"
         placeholder: image
         backgroundLoading: true
       };
    }  
    fullImageView.show = true;
}

When the fullImageView show variable is set to true, The FullImageView Node's  visible variable is set to true which specifies that this Node and any subnodes should be rendered as part of the scene graph. The  fader() function causes the fullImageView to fade in or out. The FullImageView Node's  opacity variable specifies how opaque (that is, solid) the Node appears. Animation occurs along a timeline, represented by a javafx.animation.Timeline object. Each timeline contains one or more key frames, represented by javafx.animation.KeyFrame objects. The value of the time instance variable, 3s, defines the elapsed time at which the values within the key frame will be set in a single cycle of the Timeline object. The play() method plays the timeline as defined.


Code Sample from:  FullImageView.fx

public class FullImageView extends ImageView {

    public var show = false on replace {
        if(useEffects) {
            fader();
        } else {
visible = show;
        }
    }
    var timeline:Timeline = Timeline {
        rate: bind timelineRate with inverse
        keyFrames: [
            KeyFrame {
                time: 3s
                values: [ opacity => 1.0 tween Interpolator.LINEAR ]
            }
        ]
    };
    function fader() {    
        if(show) {
            timeline.time = 0s;
            timelineRate = 1.0;
opacity = 0.0;
visible = true;
        } else {
            timeline.time = 3s;
            timelineRate = -3.0;
opacity = 1.0;
        }   
        timeline.play();
    }


stage4.gif

Clicking the normal photo again restores the thumb photo grid. The user can navigate to the next or previous set of photos by clicking << and >> arrow buttons.  Clicking the nextButton calls the onNext() function which increments the page number and calls loadImageMetadata();

Code Sample from:  main.fx

// Display next set of photos
var nextButton = ImageButton {
    selectImage: Image {
        url: "{__DIR__}images/next_h.png"
    };        
    onMouseClicked: function(e) {
onNext();
    }
}

// Load image and data specified in given Photo object
function onNext() {
    fullImageView.show = false;
    page++;
    //updateImages();
    loadImageMetadata();
}


Running the code

Netbeans 6.5 has plugins for JavaFX.  If  you don't have Netbeans 6.5  download and install it, then  go to Tools..Plugins and select the JavaFX plugins.  You can also download the JavaFX SDK without Netbeans, but I'm going to focus on using JavaFX with Netbeans.
To start learning JavaFX  you can start off with the doc Creating Your First JavaFX Application and/or with the tutorial  Learning the JavaFX Script Programming Language.

Running the RESTful Catalog service

  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 or JavaDB database as follows:
    • Click the Services tab in the NetBeans IDE.
    • Expand the databases node. You should see the MySQL server or JavaDB database in the list of databases.
      databaselist.jpg
    • Right-mouse click on the MySQL or JavaDB server database and select Start.
  4. Create the catalog database as follows:
    • Right-mouse click on the MySQL or JavaDB server database and select Create Database.
    • Enter the database name petcatalog and userid root and password admin. 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 see a driver for the petcatalog database in the list of drivers.
      driverlist.jpg
    • Right-mouse click on the petcatalog driver and select Connect.
    • Right-mouse click on the petcatalog driver and select Execute Command. This will open up a SQL command window.
    • Copy the contents of the catalog.sql file in the catalog directory and paste the contents into the SQL command window.
    • Click the Run SQL icon runsql.jpg (Ctrl+Shift+E) above the SQL command window.
    • Open the  catalog/setup/sun-resources.xml file and verify that the property values it specifies match those of the database you created (jndi datasource, username, password...). For example
      <resources>
        <jdbc-resource  jndi-name="catalog" />
          <property name="User" value="root"/>
          <property name="Password" value="admin"/>
          <property name="serverName" value="localhost"/>
          <property name="portNumber" value="3306"/>
          <property name="databaseName" value="petcatalog"/>
          <property name="URL" value="jdbc:mysql://localhost:3306/petcatalog"/>
      </resources> 
      Edit the property values as necessary to match the database you created .
  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 and empty html page at http://localhost:8080/catalog/  (this is the service not the client).

Running the JavaFX Pet Catalog Client

  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:\catalogclient.
  2. In NetBeans IDE, click Open Project in the File menu and select the catalogclient directory you just unzipped.
  3. Run the project as follows:
    • Right click the catalogclient  node in the Projects window.
    • Select Run Project.
When you run the project, your browser should display the Pet Catalog Client.

References



Friday Feb 06, 2009

for those interested in REST ,  a 7 minute screencast on how to build a
RESTful Pet Catalog using JAX-RS and dojo

http://www.netbeans.org/kb/docs/websvc/pet-catalog-screencast.html 

http://www.bestechvideos.com/2008/11/11/netbeans-tv-restful-web-services-pet-catalog



Saturday Dec 06, 2008

Pet Catalog Photos : JavaFX Example Application

Pet Catalog Photos is a simple JavaFX application that displays pet photos retrieved from a RESTful Pet Catalog app (implemented using JAX-RS) described in an earlier blog entry and in this screencast.  This JavaFX example is a modification of the Interesting Photos : JavaFX Example Application.

catalogclient.jpg


Understanding the Code

Information and URLs for pet photos is obtained by performing an HTTP GET request  on a RESTful Catalog service by using the JavaFX asynchronous HTTP API (javafx.io.http.HttpRequest). The response document is parsed by using the JavaFX XML pull parser (javafx.data.pull.PullParser) to extract information about the photos. The photos are then fetched and displayed in Stage as a grid. The user can click the thumb image to load the normal image. Clicking the normal image again returns the UI to thumb image view. 

The response XML document contains a list of information about available photos. The document contains the following information about each photo:

  • id
  • imagethumburl
  • imageurl
  • server
  • name
  • price
  • productid
  • description
Here is example XML returned from the RESTFul Catalog Service:
  
 <items uri="http://localhost:8080/catalog/resources/items/">
       <item uri="http://localhost:8080/catalog/resources/items/1/">
           <description>This black and white colored cat is super friendly./description>
           <id>1</id>
           <imagethumburl>http://localhost:8080/catalog/images/anthony-s.jpg</imagethumburl>
           <imageurl>http://localhost:8080/catalog/images/anthony.jpg</imageurl>
           <name>Friendly Cat</name>
           <price>307.10</price>
           <productid>feline01</productid>
       </item>
   ...
   </items>

The imagethumburl , imageurl are used to retrieve and then display photos. The ImageView class knows how to retrieve the image using the URL and display it. Once the photo is retrieved, it is displayed in Scene of Stage through the use of data binding.

A sequence of photo objects is constructed by parsing the response XML. A grid of ImageView is added to Scene of Stage. If the user clicks this thumb photo, the normal photo is loaded and shown. Clicking the normal photo restores the thumb photo grid. The user can navigate to the next or previous set of photos by clicking << and >> arrow buttons.


Running the code

Netbeans 6.5 has plugins for JavaFX.  If  you don't have Netbeans 6.5  download and install it, then  go to Tools..Plugins and select the JavaFX plugins.  You can also download the JavaFX SDK without Netbeans, but I'm going to focus on using JavaFX with Netbeans.
To start learning JavaFX  you can start off with the doc Creating Your First JavaFX Application and/or with the tutorial  Learning the JavaFX Script Programming Language. 

Running the RESTful Catalog service

  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 catalog 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 catalog.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.
    • Open the  catalog/setup/sun-resources.xml file and verify that the property values it specifies match those of the database you created (jndi datasource, username, password...). Edit the property values as necessary.
  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 and empty html page at http://localhost:8080/catalog/  (this is the service not the client).

Running the JavaFX Pet Catalog Client

  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:\catalogclient.
  2. In NetBeans IDE, click Open Project in the File menu and select the catalogclient directory you just unzipped.
  3. Run the project as follows:
    • Right click the catalogclient  node in the Projects window.
    • Select Run Project.
When you run the project, your browser should display the Pet Catalog Client.

References


Tuesday Sep 30, 2008


Since September 24th I've been speaking in Brazil at JUGs, Universitys, and at Sun Tech Days as part of the September Month of Java in Brazil .

MapBRAZIL-Cities2.jpg


I spoke on September 24  in Maringa to ~500 JUG members/students/professors, September 25 in Toledo to ~ 500,  September 26 in  Xanxere to ~ 200, September 27 in Porto Alegre to ~70, and in Sao Paulo there were ~1000 attendees.   We spoke in a different location each evening which meant going to sleep late and waking up early the next morning to travel to the next location.  The guys organizing this obviously do not value sleep and time to run (I'm a avid runner)  as much as I do !   They also don't have the same conception of safety, our driver was going 90mph on a 2 lane road with oncoming traffic which didn't phase Bruno and Eduardo, whereas I was seriously praying to God for my life !! :)  The attendees in each city were very friendly and enthusiastic which compensated for the difficult schedule  (but next time I will insist on more time to travel between destinations!) .   Also we drove close to the beautiful  Iguaçu_Falls  and we flew through the beautiful Florianópolis  (note to self,  next time make sure to schedule a little time to rest and see noteworthy sites ;) .

During this trip I spoke on:

I learned a little about Brazil in conversations over dinner:
It was good that USA kicked out the Brits before we discovered gold, because the Portuguese took away a lot of Brazil's gold. USA has probably had more economic stability (until recently) because we always had a strong middle class, whereas in Brazil historically there was a big gap between the rich and poor with the wealth concentrated in a small percent of the population, however this has been improving recently
Brazil had really bad inflation during the 1970s, ~ 25% per month !  Brazillians told me they used to take their salary check and buy food for the whole month the same day.  But now the Brazillian inflation is under control, they paid off their debt,  and the economy is doing well. Last year they received more foreign investment than any other country.  
Last year Brazil made a huge oil discovery  which could raise Brazil's petroleum reserves by ~40 percent and boost Brazil into the ranks of the world's major exporters (drill baby drill) .  Brazillian cars are required to run on a gas ethanol  mixture and they have a very cost-effective process to produce ethanol from sugar cane. Brazil's sugar cane-based industry is far more efficient than the U.S. corn-based industry. Sugar cane ethanol has an energy balance 7 times greater than ethanol produced from corn , and Brazil's sugar cane based ethanol industry has not caused food prices to increase.
Bruno told me that he grew up near the amazon forest and used to swim in rivers with piranhas,  he said they don't bite unless you have a cut and are bleeding, can you imagine swimming with these things ?
piran.jpg

Here are some photos from my trip :

IMG_0868_1_1.JPG IMG_0871_1_1.JPGIMG_0878_1_1.JPG IMG_0885_1_1.JPGIMG_0886_1_1.JPG IMG_0888_1_1.JPG



Saturday Sep 20, 2008

Here is a screencast 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.
You can read more about this application at RESTful Web Services and Comet

Tuesday Sep 16, 2008

this is a write up of info I gathered from   Jay PipesHigh Performance MySQL , Colin Charles and others (see References below) for a Sun Tech Days MySQL presentation.

MySQL powers many high-volume Web sites,  including industry leaders such as Yahoo!, Alcatel-Lucent, Google, Nokia, YouTube, and Zappos.com.

MySQL for Developers

If you are a developer using MySQL, you should learn enough to take advantage of its strengths, because having an understanding of the database can help you develop better-performing applications. This can be especially important for Hibernate or JPA developers, since ORM frameworks tend to obscure the database schema and SQL  for the developer, which can lead to poorly-performing index and schema strategies and inefficient SQL.

MySQL Storage Engine Architecture


A key difference between MySQL and other database platforms is the pluggable storage engine architecture of MySQL, which allows you to select a specialized storage engine for a particular application need such as data warehousing, transaction processing, high availability...
A storage engine is  responsible for storing and retrieving all the data stored .  The storage engines have different functionality, capabilities and performance characteristics, in many applications choosing the right storage engine can greatly improve performance. Here is a brief summary of some of the more common engines:
  • MyISAM - offers high-speed query and insert capability, is nontransactional, provides table-level locking, full-text indexing, compression, GIS functions, and supports indexes. MyISAM is a good choice for read-only or read-mostly applications that don't require transactions and issue primarily either SELECT or INSERT queries, such as Web Catalogs or listing of jobs, auctions, real estate, etc., or data warehousing applications. You can use multiple storage engines in a single application, sometimes specific components of an application (such as logging) fall into this category. MyISAM is not a good general purpose storage engine for high concurrent UPDATEs or DELETEs since these obtain exclusive write locks, however new rows can be inserted with shared read locks.
  • InnoDB - supports ACID transactions, multi-versioning, row-level locking, foreign key constraints, crash recovery,  and  good query performance depending on indexes. InnoDB uses row-level locking with multiversion concurrency control (MVCC). MVCC can allow fewer row locks by keeping data snapshots. Depending on the isolation level, InnoDB does not require any locking for a SELECT. This makes high concurrency possible, with some trade-offs: InnoDB requires more disk space compared to MyISAM, and for the best performance, lots of memory is required for the InnoDB buffer pool. InnoDB is a good choice for any order processing application, any application where transactions are required.  
  • Memory - stores all data in RAM for extremely fast access. Useful when you need fast access to data that doesn't change or doesn't need to persist after a restart.  Good for "lookup" or "mapping" tables, for caching the results of periodically aggregated data, for intermediate results when analyzing data.
    MEMORY tables do not support variable-length columns, this means that VARCHAR columns get implicitly converted to CHAR columns, and it is impossible to create a MEMORY table with TEXT or BLOB columns.
  • Merge - allows to logically group together a series of identical MyISAM tables and reference them as one object. Good for very large DBs like data warehousing.
  • Archive - provides for storing and retrieving large amounts of seldom-referenced historical, archived, or security audit information.
More specialized engines:
  • Federated - Allows a remote server's tables to be used as if they were local, by linking together separate MySQL servers as one logical database. Can be good for distributed or data mart environments. 
  • Cluster/NDB -Highly-available clustered storage engine.  Should be used where very high speed, availability and redundancy are absolute requirements. Other tables (even in the same database) should use one or more of the other storage engines.
  • CSV-references comma-separated files as database tables.Useful for large bulk imports or exports
  • Blackhole- the /dev/null storage engine for temporarily disabling application input to the database .  Useful for benchmarking and some replication scenarios.
You can use multiple storage engines in a single application, a storage engine for the same table on a slave can be different than that of the master. This can be very useful for taking advantage of an engine's abilities.

Schema, the basic foundation of performance

Database normalization minimizes duplication of information, this makes updates simpler and faster because the same information doesn't have to be updated in multiple tables.  In a denormalized database, information is duplicated, or stored in multiple places. With a normalized database:
  • updates are usually faster.
  • there's less data to change.
  • tables are usually smaller, use less memory, which can give better performance.
  • better performance for distinct or group by queries
The disadvantages of a normalized schema are queries typically involve more tables and require more joins which can reduce performance.  Also normalizing may place columns in different tables that would benefit from belonging to the same index, which can also reduce query performance.  More normalized schemas are better for applications involving many transactions, less normalized are better for reporting types of application.  You should normalize your schema first, then de-normalize later.  Applications often need to mix the approaches, for example use a partially normalized schema, and duplicate, or cache, selected columns from one table in another table.

Data Types

In general, try to use the smallest data type that you can.  Small and simple data types usually give better performance because it  means fewer disk accesses (less I/O), more data in memory, and less CPU to process operations.

Numeric Data Types

MySQL has 9 numeric data types.

Whole Numbers:
TINYINT, SMALLINT, MEDIUMINT, INT, BIGINT:   require 8, 16, 24, 32, and 64 bits of storage space, respectively. They can store values from –2(n-1) to 2(n-1)–1, where N is the number of bits of storage space they use. 

Use UNSIGNED when you don't need negative numbers, this doubles the bits of storage space.  BIGINT is not needed for AUTO_INCREMENT,  INT UNSIGNED stores 4.3 billion values!

INT(1) does not mean 1 digit!  The number in parentheses is the ZEROFILL argument, and specifies the number of characters some tools reserve for display purposes. For storage and computational purposes, INT(1) is identical to INT(20).

Integer data types work best for primary key data types. 

Real Numbers
:
FLOAT, DOUBLE: supports approximate calculations with standard floating-point math.
DECIMAL: use DECIMAL when you need exact results, always use for monetary/currency fields.

Other:
BIT: to store  0,1 values. BIT(1) stores 1 bit, BIT(2) stores 2... max is 64.

Character Data Types

The CHAR and VARCHAR types are declared with a length that indicates the maximum number of characters to store.
VARCHAR(n)
stores variable-length character strings. VARCHAR uses only as much space as it needs, which helps performance because it saves disk space. Use when the maximum column length is larger than the average length and when updates to the field are rare, so fragmentation is not a problem.  VARCHAR gives more efficient disk usage, however MySQL internal memory buffers are fixed width, so  internal memory usage isn't more efficient, therefore try to keep VARCHAR Max Length short.
CHAR(n) is fixed-length: MySQL allocates enough space for the specified number of characters. Useful to store very short strings, when all the values are nearly the same length, and  for data that's changed frequently.

Use NOT NULL

Always define columns as NOT NULL unless there is a very good reason not to do so:
  • can save up to a byte per column per row of data
  • nullable columns make indexes, index statistics, and value comparisons more complicated.

Indexes

Indexes are data structures that help retrieve row data with specific column values faster. Indexes can especially improve performance for larger data bases.  Most MySQL storage engines support  B-tree indexes. a B-tree is (remember data strucutres 101 ?) a tree data structure that sorts data values, tree nodes define the upper and lower bounds of the values in the child nodes.  Leaf nodes have pointers to the data instead of pointers  to child nodes. B-trees are kept balanced by requiring that all leaf nodes are at the same depth.  MyISAM leaf nodes refer to the indexed row by the position of the row,  InnoDB leaf nodes refers to the index by its primary key values.

InnoDB's clustered indexes store the row data in the leaf nodes, it's called clustered because rows with close primary key values are stored close to each other.  This can make retrieving indexed data fast, since the data is in the index.  But this can be slower for updates , secondary indexes, and for full table scans.

Covering Indexes are indexes that contain all the data values needed for a query, these queries can improve performance because the row does not have to be read.

Know Every SQL Statement

You need to understand the SQL queries your application makes and  evaluate their performance. For this you can harness the MySQL slow query log and use EXPLAIN.  Consider adding an index for queries that are taking too long, or cause a lot of load. Know how your query is executed by MySQL, consider disk I/O in particular.  Basically you want to make your queries access less data, Indexes are a good way to reduce data access.

Know Every SQL Statement for Hibernate/JPA developers

If you are using Hibernate, JPA, or another ORM framework you want to look at the generated SQL-statements. If you are using Hibernate, enable the Hibernate SQL log.  If you are using Glassfish with Toplink as the JPA provider, you can log the SQL that is being sent to the database by adding this property in the definition of the persistence unit in the persistence.xml file, as follows: <property name="toplink.logging.level" value="FINE">. Then run a use case of your application and examine the SQL statements which are executed by JPA or your ORM framework. You want to make sure you are only retrieving the data your application needs, that is you want to optimize the number of SQL statements executed (see lazy loading below), and you want to examine the execution plan for queries.

Optimize data access

Basically you want to make your queries access less data:
  • is your application retrieving more data than it needs, are queries accessing too many rows or columns?
  • is MySQL analyzing more rows than it needs?

Understanding EXPLAIN

EXPLAIN provides the execution plan chosen by the MySQL optimiser for a specific SELECT statement.  It is important to run EXPLAIN on all SELECT statements that your code is executing against the database.  This step ensures that missing indexes are picked up early in the development process and gives developers insight into how the MySQL optimizer has chosen to execute the query.

To use it just precede a SELECT statement with the keyword EXPLAIN and  MySQL will display information from the optimizer about the query execution plan, which explains how it would process the SELECT,  including information about how tables are joined and in which order. The EXPLAIN EXTENDED SELECT variant, followed by SHOW WARNINGS gives some additional information, including the final rewritten query as used by the optimizer.

With the help of EXPLAIN, you can see where you should add indexes to tables to get a faster SELECT that uses indexes to find rows. You can also use EXPLAIN to check whether the optimizer joins the tables in an optimal order.

EXPLAIN
returns a row of information for each "table" used in the SELECT statement, which shows each part and the order of the execution plan.  The "table" can mean a real schema table, a derived or temporary table, a subquery, a union result. Here is an explanation of some of the output for each row:
  • table:  the real table name or an alias.
  • select_type: shows whether the row is a simple or complex SELECT. If complex it can be: PRIMARY (Outermost SELECT), UNION, SUBQUERY, DERIVED, or UNCACHEABLE.
  • type: shows the "access strategy" type to find rows. The different access types ordered from the best  to worst:
    • system, or const: very fast because  the table has at most one matching row (For example a primary key used in the WHERE)
    • eq_ref: index lookup returning one value
    • ref: index access
    • fulltext:  FULLTEXT index.
    • ref_or_null:  like ref, but with an extra search for rows that contain NULL values.
    • range:   index scan to select the rows in given range
    • index:   index tree is scanned.
    • ALL: A full table scan
  • key: the index that MySQL decided to use, from the possible_keys, to look up rows.
  • rows: the number of rows MySQL estimates it must examine to execute the query.
  • ref: columns or constants which are compared to key to select rows .
  • Extra: additional information about how MySQL resolves the query. Watch out for Extra values of Using filesort and Using temporaryUsing index means information is retrieved from the table using only information in the index tree without having to do an additional seek to read the actual row. This strategy can be used when the query uses only columns that are part of a single index (Covering Index).

When do you get a full table scan?

  • No WHERE condition
  • No index on any field in WHERE condition
  • When your range returns a large number of rows, i.e. too many records in WHERE condition
  • When optimizer sees that the condition will return > ~20% of the records in a table, it will prefer a scan versus many seeks
  • Pre-MySQL 5, using OR in a WHERE clause
    • now fixed with an index merge, so the optimiser can use more than one index to satisfy a join condition
How do you know if a scan is used?
In the EXPLAIN output, the “type” for the table/set will be “ALL” or “index”.  “ALL” means a full table data record scan is performed.  “index” means a full index record scan.  Avoid this by ensuring indexes are on columns that are used in the WHERE, ON, and GROUP BY clauses.

Scans and seeks

A seek jumps into a random place (on disk or in memory) to fetch data. A scan will jump to the start of the data, and sequentially read (from either disk or memory) until the end of the data. With large amounts of data sequentially scanning through contiguous data on disk or in memory is faster than performing many random seek operations.  But scans can also be a sign of poor indexing, if an index contains  many rows with the same value it is not very useful.  MySQL keeps stats about the  uniqueness of values in an index in order to the estimated rows returned (rows in the explain output). If the rows is greater than a certain  % of rows in the table, then MySQL will do a scan.

Indexed columns and functions don't mix

Indexes can quickly find the rows that match a WHERE clause, however this works only if the index is NOT used in a function or expression in the WHERE clause. Below is an example where an index is used :

mysql> EXPLAIN SELECT * FROM film WHERE title LIKE 'Tr%'\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: film
type: range
possible_keys: idx_title
key: idx_title
      key_len: 767
          ref: NULL
         rows: 15
        Extra: Using where


In the example above, a  fast range "access strategy" is chosen by the optimizer, and the index scan on title is used to winnow the query results down.
Below is an example where an index can not be used :

mysql> EXPLAIN SELECT * FROM film WHERE LEFT(title,2) = 'Tr' \G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: film
type: ALL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 951
        Extra: Using where


A slow full table scan (the ALL"access strategy") is used because a function (LEFT) is operating on the title column. Operating on an indexed column with a function (in this case the LEFT() function) means the optimizer cannot use the index to satisfy the query.  Typically, you can rewrite queries in order to not operate on an indexed column with a function.

Solving multiple problems in one query

Here is an example of improving a query:

SELECT * FROM Orders WHERE TO_DAYS(CURRENT_DATE()) – TO_DAYS(order_created) <= 7;

First, we are operating on an indexed column (order_created) with a function TO_DAYS – let's fix that:

SELECT * FROM Orders WHERE order_created >= CURRENT_DATE() - INTERVAL 7 DAY;

Although we rewrote the WHERE expression to remove the function on the index, we still have a non-deterministic function CURRENT_DATE() in the statement, which eliminates this query from being placed in the query cache. Any time a non-deterministic function is used in a SELECT statement, the query cache ignores the query.  In read-intensive applications, this can be a significant performance problem. – let's fix that:

SELECT * FROM Orders WHERE order_created >= '2008-01-11' - INTERVAL 7 DAY;

We replaced the function with a constant (probably using our application programming language).  However, we are specifying SELECT * instead of the actual fields we need from the table.  What if there is a TEXT field in Orders called order_memo that we don't need to see?  Well, having it included in the result means a larger result set which may not fit into the query cache and may force a disk-based temporary table. – let's fix that:

SELECT order_id, customer_id, order_total, order_created
FROM Orders WHERE order_created >= '2008-01-11' - INTERVAL 7 DAY;


A Few Things to consider for  JPA/Hibernate  devlopers:

Lazy loading and JPA

With JPA many-to-one and many-to-many relationships lazy load by default , meaning they will be loaded when the entity in the relationship is accessed. Lazy loading is usually good, but if you need to access all of the "many" objects in a relationship, it will cause n+1 selects where n is the number of  "many" objects.  You can change the relationship to be loaded eagerly as follows :
public class Employee{

    @OneToMany(mappedBy = "employee", fetch = FetchType.EAGER)
    private Collection<Address> addresses;

 .....
}
However you should be careful with eager loading which could cause SELECT statements that fetch too much data. It can cause a Cartesian product  if you eagerly load entities with several related collections. 

If you want to temporarily override the LAZY fetch type, you could use Fetch Join.  For example this query would eagerly load the employee addresses: 
@NamedQueries({ @NamedQuery(name="getItEarly", 
                 query="SELECT e FROM Employee e JOIN FETCH e.addresses")})

public class Employee{
.....
}
 

Optimistic locking and JPA

The Java Persistence API 1.0 persistence providers support optimistic locking, where your application will get an exception whenever a transaction tries to commit an object that was updated in the database since this transaction began. To enable this for a entity, you need to add a version attribute:

@Entity
public class Item {
    ...
    @Version
    private int version;
    ...
}


In Conclusion

  • Understand the storage engines
  • Keep data types small and compact
  • Understand your query execution plans with the EXPLAIN output
  • Understand the scan vs. seek choice the optimizer must make
  • Don't mix functions and indexed columns

References

High Performance MySQL book
MySQL Pluggable Storage Engine Architecture
MySQL Storage Engine Architecture, Part 2: An In-Depth Look
Optimizing Queries with EXPLAIN
Java Persistence with Hibernate book
Jay Pipes blog
Colin Charles blog
mysql performance blog
Ronald Bradford blog
Taking JPA for a Test Drive
Pro EJB 3: Java Persistence API
Pro MySQL, Chapter 6: Benchmarking and Profiling

Friday Aug 29, 2008

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

Thursday Aug 07, 2008



This Sample Store Catalog app demonstrates the usage of JavaServer Faces, a Catalog Stateful Session Bean, the Java Persistence APIs, and Seam 2. I took this example  Sample Application using JSF, Catalog Facade Stateless Session, and Java Persistence APIs  and refactored it to use Seam on Glassfish by following the steps in Brian Leonards blog Seam Refresh  and the clickable list example in the Seam Tutorial

Download the Seam Sample Application Code

Explanation of the usage of JSF, Seam, and Java Persistence APIs in a sample Store Catalog Application

The image below shows the Catalog Listing page, which allows a user to page through a list of items in a store.

listpage.jpg

DataTable  JSF component

The List.jsp page uses a JSF dataTable component to display a list of catalog items.

The dataTable component is useful when you want to show a set of results in a table. In a JavaServer Faces application, the UIData component (the superclass of dataTable)  supports binding to a collection of data objects. It does the work of iterating over each record in the data source. The HTML dataTable renderer displays the data as an HTML table.

In the List.jsp web page the dataTable is defined as shown below:   (Note: Red colors are for Java EE tags, annotations code, Blue for Seam specific and Green for my code or variables)

Code Sample from:  List.jsp

<h:dataTable value='#{items}' var='dataTableItem' border="1"
      cellpadding="2" cellspacing="0">


The value attribute of a dataTable tag references the data to be included in the table. The var attribute specifies a name that is used by the components within the dataTable tag as an alias to the data referenced in the value attribute of dataTable.  In the dataTable tag from the List.jsp page, the value attribute points to a list of catalog items. The var attribute points to a single item in that list. As the UIData component iterates through the list, each reference to dataTableItem points to the current item in the list.

The dataTable's value is bound to the items attribute of the CatalogBean class:


Code Sample from: CatalogBean.java

@Stateful

@Scope(SESSION)
@Name("catalog")
@Interceptors({org.jboss.seam.ejb.SeamInterceptor.class})

public class CatalogBean implements Serializable, Catalog {

@DataModel
    private List<Item> items=null;

@Factory("items")
    public void getItems() {
        if ((items==null)  || (index != firstItem) ){
getNextItems();
        }
    }




The @DataModel Seam annotation exposes an attribute of type java.util.List to a JSF page as an instance of javax.faces.model.DataModel. The  <h:dataTable> supports data binding to a collection of data objects represented by a DataModel instance.  The data collection underlying a DataModel instance is modeled as a collection of row objects that can be accessed by a row index.  The APIs provide mechanisms to position to a specified row index, and to retrieve an object that represents the data that corresponds to the current row index.  In this case, the DataModel is made available in a session context variable named items.

When the List.jsp page is diplayed it will try to resolve the items context variable. Since this context variable is not initialized, Seam will call the @Factory method getItems(), which performs a JPA query (see getNextItems() code below) and results in a DataModel being outjected.  The @Factory annotation tells Seam to invoke the getItems() method to initialize the items value.

The @Name Seam annotation specifies catalog as the application unique component name which Seam will use to resolve references to the catalog context variable. Seam will instantiate the component and bind a new instance to the context variable the first time JSF encounters the variable name catalog. The instance will be bound to the context specified by the @Scope Seam annotation. The CatalogBean is a org.jboss.seam.ScopeType.SESSION scoped component. This means that the JSF components  can bind to the catalog  managed bean without configuring this in the faces-config.xml.

The @Stateful EJB 3.0 annotation marks this as a Stateful EJB. A Stateful EJB is used because the current chunk of items, and the user's position in the count of items in the db table, is maintained for the user's session.

The @Interceptors EJB 3.0 annotation registers the SeamInterceptor.class as an EJB interceptor for this session bean component.
The Seam framework uses  EJB interceptors to perform bijection, context demarcation, validation, etc, (the interceptor could be defined in the ejb-jar.xml instead).

Column JSF component

On the List.jsp page the Item Name, Photo, and Price  properties are displayed with the column component:

Code Sample from: List.jsp
<h:dataTable value='#{items}' var='dataTableItem' border="1"
      cellpadding="2" cellspacing="0">
...
  <h:column>
      <f:facet name="header">
          <h:outputText value="Price"/>
      </f:facet>
      <h:outputText value="#{dataTableItem.price}"/>
  </h:column>


The column tags represent columns of data in the dataTable component. While the dataTable component is iterating over the rows of data, it processes the column component associated with each column tag for each row in the table. As the dataTable component iterates through the list, each reference to dataTableItem points to the current item in the list.

The dataTable component  iterates through the list of items and displays the names, photos, and prices. Each time the dataTable iterates through the list of items, it renders one row in each column.

The dataTable and column tags use facets to represent rows of the table that are not repeated or updated. These include headers, footers, and captions.

Java Persistence Query API

The CatalogBean Session EJB uses the Java Persistence API Query object to return a list of items. With the @PersistenceContext annotation the CatalogBean uses dependency injection to lookup and obtain a Container Managed EntityManager . Since the EntityManager can be  container managed for EJB Session Beans, the application does not have to manage its lifecycle (i.e. call the EntityManagerFactory.create() and EntityManager.close() methods).

Code Sample from: CatalogBean.java

@DataModel
   private List<Item> items=null;

@PersistenceContext(unitName="PetCatalogPu")
   private EntityManager em;

   private int batchSize = 10;
   private int index = 0;
   private int firstItem = 0;

@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
   public void getNextItems() {
Query q = em.createQuery("select object(o) from Item as o");
        q.setMaxResults(batchSize);
        q.setFirstResult(firstItem);
items= q.getResultList();
        index = firstItem;
   }


Since this query is used for Read-Only browsing, the transaction attribute in this example is specified as NOT_SUPPORTED. Queries using transaction-scoped entity managers outside of a transaction are typically more efficient than queries inside a transaction when the result type is an entity. 

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  ITEM 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.  The O/R  relationships with Address and Product are also annotated. For more information on defining JPA entities see Pro EJB 3: Java Persistence API book.

Code Sample from: Item.java

@Entity
@Name("item")
@Scope(ScopeType.EVENT)

public class Item implements java.io.Serializable {

@Id
    private String itemID;

    private String name;   
    private String description;   
    private String imageurl;   
    private String imagethumburl; 
    private BigDecimal price;
@OneToOne(cascade={CascadeType.PERSIST})
    private Address address;
@ManyToOne
    private Product product;


    public Item() { }

    public String getName() {
        return name;
    }

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



    ...
}   



The @Name seam annotation specifies the (application unique) component name item, which is used in the  Detail.jsp to display the selected item's attributes. The @Scope Seam annotation binds the item instance to the org.jboss.seam.ScopeType.EVENT context.

The CatalogBean pages through the list of items by maintaining the firstItem and batchSize attributes and passing these as parameters to the query.setFirstResult(int startPosition), query.setMaxResults(int maxResult) methods. The CatalogBean's scope is defined as org.jboss.seam.ScopeType.SESSION, which corresponds to the JSF managed bean session scope.


The CatalogBean itemCount property is  used to get and display the number of Catologue items in the  data base:

Code Sample from: List.jsp

<h:outputText value="Item #{catalog.firstItem + 1}..#{catalog.lastItem} of
     #{catalog.itemCount}"/>



The CatalogBean getItemCount() method uses the JPA javax.persistence.Query interface to get the count of all items in the database item table:

Code Sample from: CatalogBean.java

private int itemCount = 0;

    public int getItemCount() {
Query q = entityManager.createQuery("select count(o) from Item as o");     
itemCount = ((Long)q.getSingleResult()).intValue();
        return
itemCount;
    }   



A JSF commandLink is  used to provide a link to click on to display the next page of items. The commandLink tag represents an HTML hyperlink and is rendered as an HTML <a> element. The commandLink tag is used to submit an action event to the application. 

Code Sample from: List.jsp

 <h:commandLink action="#{catalog.next}" value="Next #{catalog.batchSize}"
    rendered="#{catalog.lastItem + catalog.batchSize <= catalog.itemCount}"/>   


This commandLink action attribute references the CatalogBean next() method that calculates the next page's first row number  and returns a logical outcome String, which causes the List page to display the next page's list . This CatalogBean next() method is defined as shown below:

Code Sample from: CatalogBean.java

   public String next() {
       if (firstItem + batchSize < getItemCount()) {
           firstItem += batchSize;
           getNextItems();
       }
       return "item_list";
   }


The JavaServer Faces NavigationHandler matches the logical outcome,  item_list against the navigation rules in the application configuration resource file  faces-config.xml to determine which page to access next. In this case, the JavaServer Faces implementation loads the List.jsp page after this method returns.

Code Sample from: faces-config.xml

  <navigation-rule>
      <navigation-case>
          <from-outcome>item_list</from-outcome>
          <to-view-id>/item/List.jsp</to-view-id>
      </navigation-case>
  </navigation-rule>


A JSF commandLink is  used to provide a link to click on to display the previous page of items. This commandLink action attribute  references the  CatalogBean's prev() method that calculates the previous page's first row number  and returns a logical outcome String, which causes the List page to display the previous page of items :

Code Sample from: List.jsp

 <h:commandLink action="#{catalog.prev}" value="Previous #{catalog.batchSize}"   
        rendered="#{catalog.firstItem >=catalog.batchSize}"/>


 This CatalogBean prev() method  is defined as shown below: 

Code Sample from: CatalogBean.java

    public String prev() {
        firstItem -= batchSize;
        if (firstItem < 0) {
            firstItem = 0;
        }
        getNextItems();
        return "item_list";
    }     


A JSF commandLink is  used to provide a link to click on to display a page with the item details. This commandLink action attribute  references the CatalogBean select() method:

Code Sample from: List.jsp

   <h:column>
       <f:facet name="header">
          <h:outputText value="Name"/>
       </f:facet>
       <h:commandLink action="#{catalog.select}" value="#{dataTableItem.name}"/>   
   </h:column>


With Seam if you use the @DataModelSelection with the @DataModel annotation, when the user clicks on the link, Seam will propagate the selected row from the DataModel into the annotated attribute:

Code Sample from: CatalogBean.java

    @DataModelSelection
@Out(required=false)
    private Item item;

    public String select() {
        return "item_detail";
    }



The @DataModelSelection Seam annotation tells Seam to inject the DataModel List element corresponding to the clicked link into the item attribute.  The @Out Seam annotation transfers the value of this attribute to the item event context variable, making it available to a JSP page after the action catalog.select method execution. So when a row of the dataTable is selected, the selected row is injected to the item attribute of the CatalogBean Stateful bean, and then outjected to the event context variable named item which is used in the Detail.jsp page to display the item details.

The CatalogBean select() returns a string,  "item_detail", which causes the Detail.jsp page to display the item details. The JavaServer Faces NavigationHandler matches the logical outcome,  item_detail against the navigation rules in the application configuration resource file faces-config.xml to determine which page to access next. In this case, the JavaServer Faces implementation loads the Detail.jsp page after this method returns.

Code Sample from: faces-config.xml

    <navigation-rule>
        <navigation-case>
            <from-outcome>item_detail</from-outcome>
            <to-view-id>/item/Detail.jsp</to-view-id>
        </navigation-case>
    </navigation-rule>    



The Detail.jsp uses the outputText component to display the item properties:

Code Sample from:  Detail.jsp

    <h:outputText value="#{item.name}" title="Name" />
    <h:outputText value="#{
item.description}" title="Description"/>
    <h:graphicImage url="#{item.imageurl}" title="Imageurl" />
    <h:outputText value="#{item.price}" title="Price" />
    <h:outputText value="#{item.address.city}" title="Address" />
    <h:outputText value="#{item.contactinfo.email}" title="Address"/>  




detailpage.jpg


Conclusion
This concludes the sample application which demonstrates how to use Seam with the JSF dataTable and DataModel to page through a list of  Item Entities which are retrieved using  the CatalogBean Stateful Session EJB methods which use  the Java Persistence APIs.


Configuration of the Application for Seam 2.0, JSF, JPA, running on Glassfish V2

First I recommend reading Brian Leonard's blog Seam Refresh .  I will summarize and update those steps here:

To Open and Test Run the seampagination Project:

  • Use the Resolve Reference Problems dialog to map the ejb and web modules to their project, which are subdirectories beneath the seampagination directory.
  • After the references are resolved, right-click the seampagination project and select Open Required Projects.
  • Right-click the seampagination-EJBModule and select Resolve Reference Problems:
    • browse to the Seam lib directory and select jboss-seam.jar and select Open. This should resove the reference to the following jars: jboss-seam.jar, hibernate.jar, hibernate-validator.jar, hibernate-annotations.jar, hibernate-commons-annotations.jar, javassist.jar, dom4j.jar, commons-logging.jar.
  • Right-click the seampagination-WebModule and select Resolve Reference Problems:
    • Browse to the seampagination-ejb directory which is a sub-directory below the seampagination directory and select Open Project Folder.
    • Browse to the  jboss-seam-ui.jar found in Seam lib directory.  This should resolve the reference to the following jars: jboss-seam-ui.jar and jboss-el.jar.
If you want to create your own Java EE application using Seam 2.0 on Glassfish V2 with Netbeans from scratch (read the steps in Brian Leonard's blog Seam Refresh but use the SEAM 2.0 jars listed here here):
  • Use Netbeans to create a new Enterprise Application
  • Right-click the Libraries node of the EJBModule project , choose Add Jar  and add these jars:
    • Seam \lib\jboss-seam.jar
    • Seam \lib\hibernate.jar
    • Seam \lib\hibernate-validator.jar
    • Seam \lib\hibernate-annotations.jar
    • Seam \lib\hibernate-commons-annotations.jar
    • Seam \lib\javassist.jar
    • Seam \lib\dom4j.jar
    • Seam \lib\commons-logging.jar
  • Right-click the Libraries node of the WebModule project ,  choose Add Jar  and add these jars:
    • your ejbModule
    • Seam \lib\jboss-seam-ui.jar
    • Seam \lib\jboss-el.jar
  • create an empty seam.properties file in the seampagination-EJBModule src\conf Folder.
  • add  the following phase listener to your faces-config.xml file under webpages web-inf:
    <lifecycle>
            <phase-listener>
                org.jboss.seam.jsf.SeamPhaseListener
            </phase-listener>
    </lifecycle>
    
    
  • add the following  context parameter to your web.xml file
    <context-param>
         <param-name>
               org.jboss.seam.core.init.jndiPattern
         </param-name>
         <param-value>
               java:comp/env/your ear name/#{ejbName}/local
         </param-value>    
    </context-param>
  • add the following listener class to your web.xml file
    <listener>
            <listener-class>
                org.jboss.seam.servlet.SeamListener
            </listener-class>
    </listener>
  • For any session EJB's referenced from the web, add  EJB references to your web.xml, for example:
    <ejb-local-ref>
         <ejb-ref-name>your ear name/CatalogBean/local</ejb-ref-name>
         <ejb-ref-type>Session</ejb-ref-type>
         <local-home/>
         <local>your package name.Catalog</local>
         <ejb-link>CatalogBean</ejb-link>
    </ejb-local-ref>
  • For any EJB's referenced from the web add  a Seam interceptor to the EJB, for example : @Interceptors({org.jboss.seam.ejb.SeamInterceptor.class})

References:




[Read More]