Wednesday Dec 02, 2009

Wicket, JPA, GlassFish and Java Derby or MySQL

This Pet Catalog app explains a web application that uses Wicket, JPA, GlassFish and MySQL. I took this example JSF 2.0, JPA, GlassFish and MySQL and modified it to use Wicket instead of JSF. 

Explanation of the usage of Wicket, Java Persistence APIs, Glassfish and MySQL 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.






The Wicket Framework



The Wicket Web Framework provides a component-oriented programmatic manipulation of HTML markup. The Diagram below shows how the Wicket Framework fits into the MVC design pattern.




A Wicket component controller receives user input. The component uses the user input to interact with the model, to handle page navigation and events. The Model provide components with an interface to domain data. The Component view renders the User Interface HTML elements. The controller and view parts are combined into the Component  in Wicket.


Wicket Triad of HTML Templates, Components, and Model


The Wicket component, the model, and HTML template work together. The HTML template defines the static parts of the pages, components fill in the dynamic parts, and models are used by components to get the domain data for the dynamic parts.  Wicket matches wicket:id tags with components, Models are a reference to the data for the Java components.

Wicket  HTML Templates


Wicket templates are written in plain HTML, consumable by standard HTML editors. Wicket uses HTML namespace standards to extend HTML with placeholders,  where Wicket components are hooked in, so that there is no custom syntax at all. Wicket matches wicket: id attributes and attaches Java components to the tags in which these attributes are defined.

Wicket Web pages are all Java classes that map to an HTML template, with the same name as the Java class.




The ListPage.html file holds the markup for the ListPage.java.  Wicket matches the Java page instance and the HTML template file with the same name in the same Java package.

Code Sample from:  ListPage.html

<table>
  <tr>
   <th> Name </th>
   <th> Photo</th>
   <th> Price </th>
  </tr>
  <tr wicket:id="rows" >
     <td>
        <a wicket:id="details" href="#">
         <span wicket:id="name">name</span>
        </a>
     </td>
     <td> <img wicket:id="photo"/></td>
     <td><span wicket:id="price"></span></td>

   </tr>
</table>
<span wicket:id="pager">navigation controls here</span>



Pages are special top-level components that hold the root for component trees. Below is the component tree for the ListPage above:



Wicket Components


Wicket matches the wicket:id="rows" attribute in the ListPage.html with the corresponing Java component in ListPage.java,  which is a DataViewComponent which has a DataProvider model as shown in the diagram below.


The corresponding ListPage.java code is shown below:

Code Sample from: ListPage.java



public class ListPage extends WebPage {

// create the Model DataProvider
        IDataProvider itemDataProvider = new IDataProvider<Item>() {

            public Iterator iterator(int first, int count) {
                return itemController.findItemEntities(count, first).iterator();
            }
            public int size() {
                return itemController.getItemCount();
            }
            public IModel model(final Item object) {
                return new LoadableDetachableModel() {
                    @Override
                    protected Item load() {
                        return (Item) object;
                    }
                };
            }
            public void detach() {
            }
        };

// create the DataView component for the wicketid "rows" attribute in ListPage.html
        DataView dataView = new DataView<Item>("rows", itemDataProvider, ROWS_PER_PAGE) {

            @Override
            protected void populateItem(org.apache.wicket.markup.repeater.Item<Item> repItem) {
                Item item = (Item) repItem.getModelObject();
                repItem.setModel(new CompoundPropertyModel<Item>(item));
                repItem.add(ItemDetails.link("details", item));
                repItem.add(new Image("photo", new ResourceReference(this.getClass(),  item.getImagethumburl()))); 
                repItem.add(new Label("price"));

            }
        };
// add the DataView component to the page
        add(dataView);
// create the PagingNavigator component for the "pager" attribute in ListPage.html
        PagingNavigator pager = new PagingNavigator("pager", dataView);
        add(pager);



DataView is a component which makes it simple to populate a Wicket RepeatingView from a database by utilizing IDataProvider to act as an interface between the database and the dataview.  A Wicket RepeatingView renders the components added to it from data from a collection of objects.

The  DataView instantiation passes to the constructor  the wicket id "rows" , the itemDataProvider, and the number of rows for paging, and
anonymously overrides the populateItem() method, which will be called for each Item object provided by itemDataProvider.  The  populateItem method adds the child components ( Link, Image, Label)  with the Item  Model to the Dataview.

The itemDataProvider IDataProvider provides the Pet Catalog  Item data to the DataView.  The IDataProvider iterator(int first, int count) method gets an iterator for the subset of total data.  The itemDataProvider iterator method calls the  itemController.findItemEntities , which uses JPA to query the database and return a list of Item entities.  The itemDataProvider model method  is a Callback used by the consumer of this data provider to wrap objects retrieved from iterator(int, int) with a model (usually a detachable one).




Using the Java Persistence API (JPA) with Wicket

The ItemJpaController findItemEntities method is defined as shown below:

Code Sample from: ItemJpaController.java

public class ItemJpaController {

    public ItemJpaController() {
        emf = Persistence.createEntityManagerFactory("wicketCatalogPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }
    private List<Item> findItemEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createNamedQuery("Item.findAll");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }





The ItemJpaController uses the Java Persistence API EntityManager Query object to return a list of items. The ItemJpaController calls Persistence.createEntityManagerFactory which gets an EntityManagerFactory  when it is instatiated. 

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: q.setMaxResults(int maxResult) sets the maximum number of results to retrieve. q.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. 

Code Sample from: Item.java

@Entity
public class Item implements java.io.Serializable {

@Id
    private Integer id;

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


    public Item() { }

    public String getName() {
        return name;
    }

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


    ...
}   


A Wicket PagingNavigator component is used to provide navigation links to the next, previous, first and last page of catalog Items.  The PagingNavigator component maintains a complete page navigator, meant to be easily added to any PageableListView.

Code Sample from: ListPage.html

<span wicket:id="pager">navigation controls here</span>


Code below for adding creating a PagingNavigator for the dataView and adding it to the ListPage:

Code Sample from: ListPage.java


public class ListPage extends WebPage {


PagingNavigator pager = new PagingNavigator("pager", dataView);
add(pager);




A Wicket Link component is used to provide a link to click on to navigate to a page with the selected item details.

Code Sample from: ListPage.html

<a wicket:id="details" href="#">
        <span wicket:id="name" >name</span>
  </a>



Code below show the call to  the ItemDetails.link method to create and add the link:

Code Sample from: ListPage.java


public class ListPage extends WebPage {

// create the DataView component corresponding to the wicketid "rows" attribute in ListPage.html
        DataView dataView = new DataView<Item>("rows", itemDataProvider, ROWS_PER_PAGE) {
            @Override
            protected void populateItem(org.apache.wicket.markup.repeater.Item<Item> repItem) {
           '    ...
// call ItemDetails to create the link component
                repItem.add(ItemDetails.link("details", item));
...

            }
        };
// add the DataView component to the page
        add(dataView);



Code below for creating a BookmarkablePageLink for adding to the dataView, clicking on this link will Navigate to the ItemDetails page, passing the selected Itemid as a parameter.

Code Sample from: ItemDetails.java

public class ItemDetails extends BasePage {

        public static BookmarkablePageLink<Void> link(final String name, final Item item) {

        final BookmarkablePageLink<Void> link = new BookmarkablePageLink<Void>(name, ItemDetails.class);

        if (item != null) {
            link.setParameter("itemid", item.getItemid());
            link.add(new Label("name", new Model<Item>(item)));
        }

        return link;
    }


The ItemDetails page, shown below, displays details about the selected Catalog Item:

Code Sample from: ItemDetails.html

<html xmlns:wicket="http://wicket.apache.org/">
    <head>
        <title></title>
        <link wicket:id='stylesheet'/>
    </head>
    <body>
        <span wicket:id='mainNavigation'/>
        <table>
            <tr>
                <td align="right">Name:</td>
                <td>
                    <span wicket:id="name">name </span>
                </td>
            </tr>
            <tr>
                <td align="right">Description:</td>
                <td> <span wicket:id = "description">
                  description
                    </span>
                </td>
            </tr>
            <tr>
                <td align="right">Photo:</td>
                <td> <img wicket:id="imagethumburl"/>   </td>
            </tr>
        </table>
    </body>
</html>




The ItemDetails constructor gets the item data, and adds Labels and a image, for the name, description and photo to the ItemDetails page.

Code Sample from: ItemDetails.java

public class ItemDetails extends BasePage {

    public ItemDetails(PageParameters params) {
        Item item = itemController.findItem(params.getString("itemid"));
        add(new Label("name", item.getName()));
        add(new Label("description", item.getDescription()));
        add(new Image("imagethumburl", new ResourceReference(this.getClass(),item.getImageurl())));
    }






Hot Deployment with Wicket and Glassfish

  • Incremental compile of all Wicket  artifacts when you save.
  • Auto-deploy of all web artifacts

Conclusion
This concludes the sample application which demonstrates a pet catalog web application which uses  Wicket, JPA, GlassFish and MySQL.

Running the Sample Application

  1. If you haven't already done so, download and install NetBeans IDE , GlassFish , and MySQL Community Server . You can download and install GlassFish with NetBeans as a single bundle.
  2. Follow these instructions to setup Netbeans with the Wicket plugin.
  3. Download the sample code.

Create the Pet Catalog database

In order to run the sample code you first have to create the Pet Catalog database and fill in  the Item table.

  1. Start NetBeans IDE
  2. Ensure that GlassFish is registered in the NetBeans IDE, as follows:
    • Click the Services tab in the NetBeans IDE.
    • Expand the Servers node. You should see GlassFish v2 in the list of servers. If not, register GlassFish v2 as follows:
      • Right-click the Servers node and select Add Server. This opens an Add Server Instance wizard.
      • Select GlassFish v2 in the server list of the wizard and click the Next button.
      • Enter the location information for the server and click the Next button.
      • Enter the admin name and password and click the Finish button.
  3. Start the MySQL or Java DB database as follows:
    • Click the Services tab in the NetBeans IDE.
    • Expand the databases node. You should see the Java DB database in the list of databases. If you have installed the MySQL server database, you should also see the MySQL database in the list of databases.. Note:  Java DB  comes bundled with Netbeans, you can  download MySQL separately.

    • Right-mouse click on the Java DB or MySQL server database and select Start.
  4. If you installed MySQL, set the properties of the MySQL server database as follows:
    • Right-click on the MySQL server database and select Properties. This opens the MySQL Server Properties dialog box, as shown in Figure 8.

      MySQL Server Basic Properties
      Figure 8. MySQL Server Basic Properties

    • In the Basic Properties tab, enter the server host name and port number. The IDE specifies localhost as the default server host name and 3306 as the default server port number.
    • Enter the administrator user name, if not displayed, and the administrator password -- the default administrator password is blank.
    • Click the Admin Properties tab.
    • Enter an appropriate path in the Path/URL to admin tool field. You can find the path by browsing to the location of a MySQL Administration application such as the MySQL Admin Tool.
    • Enter an appropriate path in the Path to start command. You can find the path by browsing to the location of the MySQL start command. To find the start command, look for mysqld in the bin folder of the MySQL installation directory.
    • Enter an appropriate path in the Path to stop command field. You can find the path by browsing to the location of the MySQL stop command. This is usually the path to mysqladmin in the bin folder of the MySQL installation directory. If the command is mysqladmin, in the Arguments field, type -u root stop to grant root permissions for stopping the server. The Admin Properties tab should look similar to Figure 9.

      MySQL Server Administration Properties
      Figure 9. MySQL Server Administration Properties

    • Click the OK button.

  5. Right-click on the MySQL server or Java DB database and select Start.
  6. Create the petcatalog database as follows:
    • Right-mouse click on the Java DB or MySQL server database and select Create Database. This will open a create Database window.
    • Enter the database name catalog for Java DB or petcatalog for MySQL.


      For Java DB enter userid password app app as shown below:


       Click O.K. to accept the displayed settings.
  7. Create the tables in the catalog database as follows:
    • Underneath Databases you should see a database connection for the petcatalog database. For example MySQL:

      or Java DB:

    • Right-mouse click on the petcatalog connection and select Connect.
    • Right-mouse click on the petcatalog connection and select Execute Command. This will open up a SQL command window.
    • Copy the contents of the catalog.sql file in the riapetcatalog\\exercises\\exercise0 directory and paste the contents into the SQL command window, as shown in below:

      Creating Tables in the Database
    • Click the Run SQL icon Run SQL icon (Ctrl+Shift+E) above the SQL command window.
    • Note: It is ok to see this: "Error code -1, SQL state 42Y55: 'DROP TABLE' cannot be performed on 'ITEM' because it does not exist. Line 2, column 1" . This just means you are deleting a table that does not exist.  If you need to delete and recreate the tables you will not  see this message the second time.
  8. View the data in the Pet Catalog database Item table as follows:
    • Underneath Databases you should see a database connection for the petcatalog database. For example MySQL:

      or Java DB:

    • If the database connection is broken like in the following diagram:

      • Right-mouse click on the petcatalog connection and select Connect. as shown below:

      • if prompted for a password, for MySQL leave it blank, for JavaDB enter user app password app.
    • Expand the Tables node below the petcatalog database in the Services window. You should see the item table under the Tables node. You can expand the item table node to see the table columns, indexes, and any foreign keys, as shown in below :
      An Expanded Table Node
      Figure 12. An Expanded Table Node

      You can view the contents of a table or column by right-clicking the table or column and selecting View Data as shown  below:

      Viewing the Contents of a Table
      Figure 13. Viewing the Contents of a Table


  9. Follow these instructions to Create a JDBC Connection pool and JDBC resource.Name the  pool mysql_petcatalog_rootPool and the jndi resource jdbc/petcatalog. Note: you do not have to create a JDBC connection pool and resource if you use the Netbeans wizard to generate JPA entities from database tables as described in this article GlassFish and MySQL, Part 2: Building a CRUD Web Application With Data Persistence.

Running the Sample solution:

If you want to run the sample solution, you have to create the catalog database tables first as described above.

  1. If you haven't already download the sample code and start the NetBeans IDE. Unzip the catalog.zip file which you downloaded, this will create a catalog directory with the project code.
  2. Open the catalog/setup/sun-resources.xml file and verify that the property values it specifies match those of the petcatalog database and jdbc resources you created. Edit the property values as necessary.

  3. Open the catalog project as follows:
    • In NetBeans IDE, click Open Project in the File menu. This opens the Open Project dialog.
    • Navigate in the Open Project dialog to the catalog  directory and click the Open Project button.

    In response, the IDE opens the catalog project.  You can view the logical structure of the project in the Projects window (Ctrl-1).
  4. Run the catalog by right-clicking on the catalog project in the Projects window and selecting Run Project. The NetBeans IDE compiles the application, deploys it on Glassfish, and brings up the default page in your browser.  (at http://localhost:8080/catalog/).

For more information see the following resources:


Friday Aug 21, 2009

JPA Caching


JPA Level 1 caching

JPA has 2 levels of caching. The first level of caching is the persistence context.

The JPA Entity Manager maintains a set of Managed Entities in the Persistence Context.

The Entity Manager guarantees that within a single Persistence Context, for any particular database row, there will be only one object instance. However the same entity could be managed in another User's transaction, so you should use either optimistic or pessimistic locking  as explained in JPA 2.0 Concurrency and locking

The code below shows that a find on a managed entity with the same id and class as another in the same persistence context , will return the same instance.

@Stateless public ShoppingCartBean implements ShoppingCart {

 @PersistenceContext EntityManager entityManager;

 public OrderLine createOrderLine(Product product,Order order) {
        OrderLine orderLine = new OrderLine(order, product);
        entityManager.persist(orderLine);   //Managed
        OrderLine orderLine2 =entityManager.find(OrderLine,
orderLine.getId()));
     (orderLine == orderLine2  // TRUE
        return (orderLine);
    }

}

The diagram below shows the life cycle of an Entity in relation to the Persistent Context.

The code below illustrates the life cycle of an Entity. A reference to a container managed EntityManager is injected using the persistence context annotation. A new order entity is created and the entity has the state of new. Persist is called, making this a managed entity. because it is a stateless session bean it is by default using container managed transactions , when this transaction commits , the order is made persistent in the database. When the orderline entity is returned at the end of the transaction it is a detached entity.

The Persistence Context can be either Transaction Scoped-- the Persistence Context 'lives' for the length of the transaction, or Extended-- the Persistence Context spans multiple transactions. With a Transaction scoped Persistence Context, Entities are "Detached" at the end of a transaction.

As shown below, to persist the changes on a detached entity, you call the EntityManager's merge() operation, which returns an updated managed entity, the entity updates will be persisted to the database at the end of the transaction.

An Extended Persistence Context spans multiple transactions, and the set of Entities in the Persistence Context stay Managed. This can be useful in a work flow scenario where a "conversation" with a user spans multiple requests.

The code below shows an example of a Stateful Session EJB with an Extended Persistence Context in a use case scenario to add line Items to an Order. After the Order is persisted in the createOrder method, it remains managed until the EJB remove method is called. In the addLineItem method , the Order Entity can be updated because it is managed, and the updates will be persisted at the end of the transaction.


The example below contrasts updating the Order using a transaction scoped Persistence Context verses an extended Persistence context. With the transaction scoped persistence context, an Entity Manager find must be done to look up the Order, this returns a Managed Entity which can be updated. With the Extended Persistence Context the find is not necessary. The performance advantage of not doing a database read to look up the Entity, must be weighed against the disadvantages of memory consumption for caching, and the risk of cached entities being updated by another transaction.  Depending on the application and the risk of contention among concurrent transactions this may or may not give better performance / scalability.

JPA second level (L2) caching

JPA second level (L2) caching shares entity state across various persistence contexts.


JPA 1.0 did not specify support of a second level cache, however, most of the persistence providers provided support for second level cache(s). JPA 2.0 specifies support for basic cache operations with the new Cache API, which is accessible from the EntityManagerFactory, shown below:


If L2 caching is enabled, entities not found in persistence context, will be loaded from L2 cache, if found.

The advantages of L2 caching are:
  • avoids database access for already loaded entities
  • faster for reading frequently accessed  unmodified entities
The disadvantages of L2 caching are:
  • memory consumption for large amount of objects
  • Stale data for updated objects
  • Concurrency for write (optimistic lock exception, or pessimistic lock)
  • Bad scalability for frequent or concurrently updated entities

You should configure L2 caching for entities that are:
  • read often
  • modified infrequently
  • Not critical if stale
You should protect any data that can be concurrently modified with a locking strategy:
  • Must handle optimistic lock failures on flush/commit
  • configure expiration, refresh policy to minimize lock failures
The Query cache is useful for queries that are run frequently with the same parameters, for not modified tables.

The EclipseLink JPA persistence provider caching Architecture

The  EclipseLink caching Architecture is shown below.


Support for second level cache in EclipseLink is turned on by default, entities read are L2 cached. You can disable the L2 cache. EclipseLink caches entities in L2, Hibernate caches entity id and state in L2. You can configure caching by Entity type or Persistence Unit with the following configuration parameters:
  • Cache isolation, type, size, expiration, coordination, invalidation,refreshing
  • Coordination (cluster-messaging)
  • Messaging: JMS, RMI, RMI-IIOP, …
  • Mode: SYNC, SYNC+NEW, INVALIDATE, NONE
The example below shows configuring the L2 cache for an entity using the @Cache annotation

The Hibernate JPA persistence provider caching Architecture

The Hibernate JPA persistence provider caching architecture is different than EclipseLink: it is not configured by default, it does not cache enities just id and state, and you can plug in different L2 caches. The diagram below shows the different L2 cache types that you can plug into Hibernate.

The configuration of the cache depends on the type of caching plugged in. The example below shows configuring the hibernate L2 cache for an entity using the @Cache annotation

For More Information:

Introducing EclipseLink
EclipseLink JPA User Guide
Hibernate Second Level Cache
Speed Up Your Hibernate Applications with Second-Level Caching
Hibernate caching
Java Persistence API 2.0: What's New ?
Beginning Java™ EE 6 Platform with GlassFish™ 3
Pro EJB 3: Java Persistence API (JPA 1.0)





Tuesday Aug 11, 2009

Java EE 6 Pet Catalog with GlassFish v3 preview and MySQL


Java EE 6 Pet Catalog with GlassFish v3 preview and MySQL


This Pet Catalog app explains a web application that uses JSF 2.0, Java EE 6, GlassFish and MySQL. I took this example  GlassFish and MySQL, Part 2: Building a CRUD Web Application With Data Persistence and modified it to use some of the new features of JSF 2.0 and Java EE 6.
http://www.netbeans.org/kb/samples/index.html 

Explanation of the usage of JSF 2.0 and Java EE 6 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.



JSF 2.0 Facelets XHTML instead of JSP

For JSF 2.0, Facelets XHTML is the preferred way to declare JSF Web Pages. JSP is supported for backwards compatibility, but not all JSF 2.0 features will be available for views using JSP as their page declaration language.  JSF 2.0 Facelets has some nice features like templating (similar in functionality to Tiles) and composite components, which I'm not going to discuss here but you can read about that in this article: http://www.ibm.com/developerworks/java/library/j-jsf2fu2/index.html and in this Tech Tip Composite UI Components in JSF 2.0.


The Catalog application's resources


JSF 2.0 standardizes how to define web resources. Resources are any artifacts that a component may need in order to be rendered properly -- images, CSS, or JavaScript files.  With JSF 2.0 you put resources in a resources directory or a subdirectory.


In your Facelets pages, you can access css files with the  <h:outputStylesheet>,  javascript files with the <h:outputScript> , and images with the <h:graphicImage> JSF tags. The list.xhtml uses the  <h:outputStylesheet tag to load the styles.css stylesheet , and the <h:graphicImage tag to display images from the resources as shown below:

Code Sample from:  list.xhtml

<h:outputStylesheet name="css/styles.css" target="body"/>

<h:graphicImage library="images" name="banner_logo.gif"  />   




The Catalog application uses a resource bundle to contain the static text and error messages used by the Facelets pages. Putting messages in a resource bundle makes it easier to modify and internationalize your Application text.  The messages are in a properties file in a java package directory.

Code Sample from:  messages.properties 

Title=Pet Catalog
Next=Next
Previous=Prev
Name=Name



The resource bundle is configured in the faces-config.xml File (you don't need any other configuration in the faces-config.xml for JSF 2.0, as explained later you no longer have to configure managed beans and navigation with XML).


Code Sample from:  faces-config.xml

<application>
    <resource-bundle>
        <base-name>web.WebMessages</base-name>
        <var>msgs</var>
    </resource-bundle>
</application>




The List.xhtml facelets page uses a JSF dataTable component to display a list of catalog items in an html table.  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.xhtml web page the dataTable is defined as shown below:  (Note: Red colors are for Java EE tags, annotations code,  and Green is for my code or variables)

Code Sample from:  list.xhtml

<h:dataTable value='#{catalog.items}' var='row' 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 dataTable component iterates through the list, each reference to dataTableItem points to the current item in the list.

JSF 2.0 Annotations instead of XML configuration

The dataTable's value is bound to the items property of the catalog managed bean. With JSF 2.0 managed beans do not have to be configured in the faces-config.xml file, you annotate the managed beans instead as shown below:

Code Sample from: Catalog.java


@ManagedBean
@SessionScoped
public class Catalog implements Serializable {




By convention, the name of a managed bean is the same as the class name, with the first letter of the class name in lowercase. To specify a managed bean name you can use the name attribute of the ManagedBean annotation, like this: @ManagedBean(name = "Catalog").


This Catalog ManagedBean items property is defined as shown below:

Code Sample from: Catalog.java

    private List<Item> items = null;

    public List<Item> getItems() {
        if (items == null) {
            getPagingInfo();
            items = getNextItems(pagingInfo.getBatchSize(), pagingInfo.getFirstItem());
        }
        return items;
    }





The getItems() method returns a List of item objects. The JSF dataTable, supports data binding to a collection of data objects.  The dataTable object 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.   

The Item properties name, imagethumburl, and price are displayed with the column component:

Code Sample from: list.xhtml

<h:dataTable var="row" value="#{catalog.items}">
  <h:column>
      <f:facet name="header">
          <h:outputText value="#{msgs.Name}"/>
      </f:facet>
      <h:commandLink action="#{catalog.showDetail(row)}" value="#{row.name}" />
  </h:column>

  <h:column>
      <f:facet name="header">
          <h:outputText value="#{msgs.Photo}"/>
      </f:facet>
<h:graphicImage library="images" name="#{row.imagethumburl}"/>
  </h:column>

  <h:column>
      <f:facet name="header">
          <h:outputText value="#{msgs.Price}"/>
      </f:facet>
      <h:outputText value="#{row.price}"/>
  </h:column>
</h:dataTable>


The column tags represent columns of data in a dataTable component. While the dataTable component is iterating over the rows of data, it processes the UIColumn component associated with each column tag for each row in the table.

The dataTable component  iterates through the list of items (catalog.items)  and displays the item (var="row") attribute value. Each time UIData iterates through the list of items, it renders one cell in each column.

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

Java EE 6: JSF 2.0,  EJB 3.1, and Java Persistence API (JPA)  2.0

The Catalog ManagedBean annotates the field private ItemFacade itemFacade;  with @EJB , which causes an itemFacade EJB to be injected when the managed bean is instatiated. The Catalog getNextItems method calls the ItemFacade Stateless EJB which uses the Java Persistence API EntityManager Query object to return a list of items.


Code Sample from: Catalog.java

@ManagedBean
@SessionScoped
public class Catalog implements Serializable {


@EJB
    private ItemFacade itemFacade;

    public List<Item>  getNextItems(int maxResults, int firstResult) { 
       return itemFacade.findRange(maxResults, firstResult);    
   }


EJB 3.1 No-interface local client View

With EJB 3.1, local EJBs  do not  have to a implement separate interface, that is, all public methods of the bean class are automatically exposed to the caller.

Simplified Packaging

With Java EE 6, EJBs can be directly packaged in a WAR file just like web components.

The ItemFacade EJB uses the Java Persistence API EntityManager Query object to return a list of items. The ItemFacade EJB annotates the field private EntityManager em;  with @PersistenceContext , which causes an entity manager to be injected when it is instatiated.

Code Sample from: ItemFacade.java

@Stateless
public class ItemFacade {


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

    public List<Item> findRange(int maxResults, int firstResult) {
Query q = em.createQuery("select object(o) from Item as o");
        q.setMaxResults(maxResults);
        q.setFirstResult(firstResult);
        return q.getResultList();
    }


The Java Persistence Query APIs are used to create and execute queries that can return a list of results.  The JPA Query interface provides support for pagination via the setFirstResult() and setMaxResults() methods: q.setMaxResults(int maxResult) sets the maximum number of results to retrieve. q.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
public class Item implements java.io.Serializable {

@Id
    private Integer id;

    private String name;   
    private String description;   
    private String imageurl;   
    private String imagethumburl; 
    private BigDecimal price;
@ManyToOne
    private Address address;
@ManyToOne
    private Product product;


    public Item() { }

    public String getName() {
        return name;
    }

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


    ...
}   




The Catalog ManagedBean pages through the list of Items by maintaining the PagingInfo.firstItem and PagingInfo.batchSize attributes and passing these as parameters to the  getNextItems(firstItem, batchSize) method. The catalog's scope  is defined with the annotation @SessionScoped, a JSF Managedbean with session scope will be stored in the session meaning that the bean's properties will stay alive for the life of the Http Session.


A JSF commandButton is  used to provide a button to click on to display the next page of items.  The commandButton tag is used to submit an action event to the application. 

Code Sample from: list.xhtml

 <h:commandButton action="#{catalog.next}" value="#{msgs.Next}" />   


This commandButton action attribute references the catalog Managed bean next() method which calculates the next page's first row number  and returns a logical outcome String, which causes the list.xhtml page to display the next page's list . The catalog next method is defined as shown below:

Code Sample from: catalog.java

   public String next() {
       if (firstItem + batchSize < itemCount()) {
           firstItem += batchSize;
       }
       return "list";
   }


JSF 2.0 Simplified Navigation


The JavaServer Faces 2.0  NavigationHandler convention adds .xhtml to the logical outcome of the action method (in this example list) and loads that file, in this case, it loads the list.xhtml page after this method returns. If the action doesn't begin with a forward slash (/), JSF assumes that it's a relative path.  You can specify an absolute path by adding the slash like this "/items/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 catalog showDetail() method:

Code Sample from: list.xhtml

   <h:column>
       <f:facet name="header">
          <h:outputText value="Name"/>
       </f:facet>
       <h:commandLink action="#{catalog.showDetail(row)}" value="#{row.name}"/>   
   </h:column>


With JSF 2.0 you can now specify parameters in method expressions. The dataTable row object associated with the selected link is passed as a parameter in the  "#{catalog.showDetail(row)}" method expression.
The Catalog showDetail() method  gets the item data from the input parameter, and returns a string which causes the detail.xhtml page to display the item details :

Code Sample from: Catalog.java

    public String showDetail(Item item) {
        this.item = item;
        return "detail";
    }


The JavaServer Faces NavigationHandler adds .xhtml to the logical outcome of the action, detail and loads that file. In this case, the JavaServer Faces implementation loads the detail.xhtml page after this method returns.

The detail.xhtml uses the outputText component to display the catalog ManagedBean's item properties:

Code Sample from: detail.xhtml

    <h:outputText value="#{catalog.item.name}" title="Name" />
    <h:outputText value="#{catalog.item.description}" title="Description"/>
    <h:graphicImage library="images" name="#{catalog.item.imageurl}" title="Imageurl" />

    <h:outputText value="#{
catalog.item.price}" title="Price" />
    <h:outputText value="#{
catalog.item.address.city}" title="Address" />
    <h:outputText value="#{
catalog.item.contactinfo.email}" title="Address"/>  





GlassFish v3 is a lightweight server

  • OSGi-based; Embedded API; RESTful admin API; Lightweight and fast startup;
  • iterative development cycle "edit-save-refresh browser":
    • Incremental compile of all JSF 2.0 artifacts when you save.
    • Auto-deploy of all web or Java EE 6 artifacts
  • Session retention: maintain sessions across re-deployments


Conclusion
This concludes the sample application which demonstrates a pet catalog web application which uses Java EE 6, GlassFish v3 and MySQL.

Running the Sample Application

  1. Download and install NetBeans IDE 6.8 M1 with GlassFish v3 b57 (Glassfish v3 preview is Java EE 6 Preview) , and MySQL Community Server .
  2. Follow these instructions to set up a  jdbc-driver for MySQL. (Normally this is already setup with Glassfish, but I got an errror message with Glassfish v3 b57 that it was missing)
  3. Download the sample code. Unzip the catalog.zip file which you downloaded, this will create a catalog directory with the project code.

Create the Pet Catalog database

In order to run the sample code you first have to create the Pet Catalog database and fill in  the Item table.

  1. Start NetBeans IDE
  2. Ensure that GlassFish is registered in the NetBeans IDE, as follows:
    • Click the Services tab in the NetBeans IDE.
    • Expand the Servers node. You should see GlassFish v2 in the list of servers. If not, register GlassFish v2 as follows:
      • Right-click the Servers node and select Add Server. This opens an Add Server Instance wizard.
      • Select GlassFish v2 in the server list of the wizard and click the Next button.
      • Enter the location information for the server and click the Next button.
      • Enter the admin name and password and click the Finish button.
  3. Start the MySQL or Java DB database as follows:
    • Click the Services tab in the NetBeans IDE.
    • Expand the databases node. You should see the Java DB database in the list of databases. If you have installed the MySQL server database, you should also see the MySQL database in the list of databases.. Note:  Java DB  comes bundled with Netbeans, you can  download MySQL separately.

    • Right-mouse click on the Java DB or MySQL server database and select Start.
  4. If you installed MySQL, set the properties of the MySQL server database as follows:
    • Right-click on the MySQL server database and select Properties. This opens the MySQL Server Properties dialog box, as shown in Figure 8.

      MySQL Server Basic Properties
      Figure 8. MySQL Server Basic Properties

    • In the Basic Properties tab, enter the server host name and port number. The IDE specifies localhost as the default server host name and 3306 as the default server port number.
    • Enter the administrator user name, if not displayed, and the administrator password -- the default administrator password is blank.
    • Click the Admin Properties tab.
    • Enter an appropriate path in the Path/URL to admin tool field. You can find the path by browsing to the location of a MySQL Administration application such as the MySQL Admin Tool.
    • Enter an appropriate path in the Path to start command. You can find the path by browsing to the location of the MySQL start command. To find the start command, look for mysqld in the bin folder of the MySQL installation directory.
    • Enter an appropriate path in the Path to stop command field. You can find the path by browsing to the location of the MySQL stop command. This is usually the path to mysqladmin in the bin folder of the MySQL installation directory. If the command is mysqladmin, in the Arguments field, type -u root stop to grant root permissions for stopping the server. The Admin Properties tab should look similar to Figure 9.

      MySQL Server Administration Properties
      Figure 9. MySQL Server Administration Properties

    • Click the OK button.

  5. Right-click on the MySQL server or Java DB database and select Start.
  6. Create the petcatalog database as follows:
    • Right-mouse click on the Java DB or MySQL server database and select Create Database. This will open a create Database window.
    • Enter the database name catalog for Java DB or petcatalog for MySQL.


      For Java DB enter userid password app app as shown below:


       Click O.K. to accept the displayed settings.
  7. Create the tables in the catalog database as follows:
    • Underneath Databases you should see a database connection for the petcatalog database. For example MySQL:

      or Java DB:

    • Right-mouse click on the petcatalog connection and select Connect.
    • Right-mouse click on the petcatalog connection 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, as shown in below:

      Creating Tables in the Database
    • Click the Run SQL icon Run SQL icon (Ctrl+Shift+E) above the SQL command window.
    • Note: It is ok to see this: "Error code -1, SQL state 42Y55: 'DROP TABLE' cannot be performed on 'ITEM' because it does not exist. Line 2, column 1" . This just means you are deleting a table that does not exist.  If you need to delete and recreate the tables you will not  see this message the second time.
  8. View the data in the Pet Catalog database Item table as follows:
    • Underneath Databases you should see a database connection for the petcatalog database. For example MySQL:

      or Java DB:

    • If the database connection is broken like in the following diagram:

      • Right-mouse click on the petcatalog connection and select Connect. as shown below:

      • if prompted for a password, for MySQL leave it blank, for JavaDB enter user app password app.
    • Expand the Tables node below the petcatalog database in the Services window. You should see the item table under the Tables node. You can expand the item table node to see the table columns, indexes, and any foreign keys, as shown in below :
      An Expanded Table Node
      Figure 12. An Expanded Table Node

      You can view the contents of a table or column by right-clicking the table or column and selecting View Data as shown  below:

      Viewing the Contents of a Table
      Figure 13. Viewing the Contents of a Table


  9. Follow these instructions to Create a JDBC Connection pool and JDBC resource. Name the  pool mysql_petcatalog_rootPool and the jndi resource jdbc/petcatalog. Note: you do not have to create a JDBC connection pool and resource if you use the Netbeans wizard to generate JPA entities from database tables as described in this article GlassFish and MySQL, Part 2: Building a CRUD Web Application With Data Persistence.
  10. Open the catalog/setup/sun-resources.xml file and verify that the property values it specifies match those of the petcatalog database and jdbc resources you created. Edit the property values as necessary.

Running the Sample solution:

If you want to run the sample solution, you have to create the catalog database tables first as described above.

  1. Open the catalog project as follows:
    • In NetBeans IDE, click Open Project in the File menu. This opens the Open Project dialog.
    • Navigate in the Open Project dialog to the catalog  directory and click the Open Project button.

    In response, the IDE opens the catalog project.  You can view the logical structure of the project in the Projects window (Ctrl-1).
  2. Run the catalog by right-clicking on the catalog project in the Projects window and selecting Run Project. The NetBeans IDE compiles the application, deploys it on Glassfish, and brings up the default page in your browser.  (at http://localhost:8080/catalog/).

For more information see the following resources:



Thursday Jul 30, 2009

JPA 2.0 Concurrency and locking

Optimistic Concurrency


Optimistic locking lets concurrent transactions process simultaneously, but detects and prevent collisions, this works best for applications where most concurrent transactions do not conflict. JPA Optimistic locking allows anyone to read and update an entity, however a version check is made upon commit and an exception is thrown if the version was updated in the database since the entity was read.  In JPA for Optimistic locking you annotate an attribute with @Version as shown below:

public class Employee {
    @ID int id;
@Version int version;

The Version attribute will be incremented with a successful commit. The Version attribute can be an int, short, long, or timestamp.  This results in SQL like the following:

“UPDATE Employee SET ..., version = version + 1
     WHERE id = ? AND version = readVersion

The advantages of optimistic locking are that no database locks are held which can give better scalability. The disadvantages are that the user or application must refresh and retry failed updates.

Optimistic Locking Example


In the optimistic locking example below, 2 concurrent transactions are updating employee e1. The transaction on the left commits first causing the e1 version attribute to be incremented with the update. The transaction on the right throws an OptimisticLockException because the e1 version attribute is higher than when e1 was read, causing the transaction to roll back.
img60.jpg

Additional Locking with JPA Entity Locking APIs


With JPA it is possible to lock an entity, this allows you to control when, where and which kind of locking to use. JPA 1.0 only supported Optimistic read or Optimistic write locking.  JPA 2.0 supports Optimistic and Pessimistic locking, this is layered on top of @Version checking described above.

JPA 2.0 LockMode values :
  • OPTIMISTIC (JPA 1.0 READ):
    • perform a version check on locked Entity before commit, throw an OptimisticLockException if Entity version mismatch.
  • OPTIMISTIC_FORCE_INCREMENT (JPA 1.0 WRITE)
    • perform a version check on locked Entity before commit, throw an OptimisticLockException if Entity version mismatch, force an increment to the version at the end of the transaction, even if the entity is not modified.
  • PESSIMISTIC:
    • lock the database row when reading
  • PESSIMISTIC_FORCE_INCREMENT
    • lock the database row when reading, force an increment to the version at the end of the transaction, even if the entity is not modified.
There are multiple APIs to specify locking an Entity:
  • EntityManager methods: lock, find, refresh
  • Query methods: setLockMode 
  • NamedQuery annotation: lockMode element

OPTIMISTIC (READ) LockMode Example


In the optimistic locking example below,  transaction1 on the left updates the department name for dep , which causes dep's version attribute to be incremented. Transaction2 on the right gives an employee a raise if he's in the "Eng" department. Version checking on the employee attribute would not throw an exception in this example since it was the dep Version attribute that was updated in transaction1. In this example the employee change should not commit if the department was changed after reading, so an OPTIMISTIC lock is used : em.lock(dep, OPTIMISTIC).  This will cause a version check on the  dep Entity before committing transaction2  which will throw an OptimisticLockException because the dep version attribute is higher than when dep was read, causing the transaction to roll back.
img62.jpg

OPTIMISTIC_FORCE_INCREMENT (write) LockMode Example


In the OPTIMISTIC_FORCE_INCREMENT locking example below,  transaction2 on the right wants to be sure that the dep name does not change during the transaction, so transaction2 locks the dep Entity em.lock(dep, OPTIMISTIC_FORCE_INCREMENT) and then calls em.flush() which causes dep's version attribute to be incremented in the database. This will cause any parallel updates to dep  to throw an OptimisticLockException and roll back. In transaction1 on the left at commit time when the dep version attribute is checked and found to be stale, an OptimisticLockException is thrown
img63.jpg

Pessimistic Concurrency

Pessimistic concurrency locks the database row when data is read, this is the equivalent of a (SELECT . . . FOR UPDATE [NOWAIT]) .  Pessimistic locking ensures that transactions do not update the same entity at the same time, which can simplify application code, but it limits concurrent access to the data which can cause bad scalability and may cause deadlocks. Pessimistic locking is better for applications with a higher risk of contention among concurrent transactions.
The examples below show:
  1. reading an entity and then locking it later
  2. reading an entity with a lock
  3. reading an entity, then later refreshing it with a lock

The Trade-offs are the longer you hold the lock the greater the risks of bad scalability and deadlocks. The later you lock the greater the risk of stale data, which can then cause an optimistic lock exception, if the entity was updated after reading but before locking.
img66.jpg
img672.jpg
The right locking approach depends on your application:
  • what is the risk of risk of contention among concurrent transactions?
  • What are the requirements for scalability?
  • What are the requirements for user re-trying on failure?

References and More Information:

Preventing Non-Repeatable Reads in JPA Using EclipseLink
Java Persistence API 2.0: What's New ?
What's New and Exciting in JPA 2.0
Beginning Java™ EE 6 Platform with GlassFish™ 3
Pro EJB 3: Java Persistence API (JPA 1.0)

Java Persistence API: Best Practices and Tips





Friday Jul 24, 2009

JSF 2.0, JPA, GlassFish and MySQL

JSF 2.0, JPA, GlassFish and MySQL

JSF 2.0, JPA, GlassFish and MySQL


This Pet Catalog app explains a web application that uses JSF 2.0, JPA, GlassFish and MySQL. I took this example  GlassFish and MySQL, Part 2: Building a CRUD Web Application With Data Persistence and modified it to use some of the new features JSF 2.0. 

Explanation of the usage of JSF 2.0, Java Persistence APIs, Glassfish and MySQL 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.



JSF 2.0 Facelets XHTML instead of JSP

For JSF 2.0, Facelets XHTML is the preferred way to declare JSF Web Pages. JSP is supported for backwards compatibility, but not all JSF 2.0 features will be available for views using JSP as their page declaration language.  JSF 2.0 Facelets has some nice features like templating (similar in functionality to Tiles) and composite components, which I'm not going to discuss here but you can read about that in this article: http://www.ibm.com/developerworks/java/library/j-jsf2fu2/index.html and in this Tech Tip Composite UI Components in JSF 2.0.


The Catalog application's resources


JSF 2.0 standardizes how to define web resources. Resources are any artifacts that a component may need in order to be rendered properly -- images, CSS, or JavaScript files.  With JSF 2.0 you put resources in a resources directory or a subdirectory.


In your Facelets pages, you can access css files with the  <h:outputStylesheet>,  javascript files with the <h:outputScript> , and images with the <h:graphicImage> JSF tags. The list.xhtml uses the  <h:outputStylesheet tag to load the styles.css stylesheet , and the <h:graphicImage tag to display images from the resources as shown below:

Code Sample from:  list.xhtml

<h:outputStylesheet name="css/styles.css" target="body"/>

<h:graphicImage library="images" name="banner_logo.gif"  />   




The Catalog application uses a resource bundle to contain the static text and error messages used by the Facelets pages. Putting messages in a resource bundle makes it easier to modify and internationalize your Application text.  The messages are in a properties file in a java package directory.

Code Sample from:  messages.properties 

Title=Pet Catalog
Next=Next
Previous=Prev
Name=Name



The resource bundle is configured in the faces-config.xml File (you don't need any other configuration in the faces-config.xml for JSF 2.0, as explained later you no longer have to configure managed beans and navigation with XML).


Code Sample from:  faces-config.xml

<application>
    <resource-bundle>
        <base-name>web.WebMessages</base-name>
        <var>msgs</var>
    </resource-bundle>
</application>




The List.xhtml facelets page uses a JSF dataTable component to display a list of catalog items in an html table.  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.xhtml web page the dataTable is defined as shown below:  (Note: Red colors are for Java EE tags, annotations code,  and Green is for my code or variables)

Code Sample from:  list.xhtml

<h:dataTable value='#{catalog.items}' var='row' 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 dataTable component iterates through the list, each reference to dataTableItem points to the current item in the list.

JSF 2.0 Annotations instead of XML configuration

The dataTable's value is bound to the items property of the catalog managed bean. With JSF 2.0 managed beans do not have to be configured in the faces-config.xml file, you annotate the managed beans instead as shown below:

Code Sample from: Catalog.java


@ManagedBean
@SessionScoped
public class Catalog implements Serializable {




By convention, the name of a managed bean is the same as the class name, with the first letter of the class name in lowercase. To specify a managed bean name you can use the name attribute of the ManagedBean annotation, like this: @ManagedBean(name = "Catalog").


This Catalog ManagedBean items property is defined as shown below:

Code Sample from: Catalog.java

    private DataModel items = null;

    public DataModel getItems() {
        if (items == null) {
            getPagingInfo();
            items = new ListDataModel(getNextItems(pagingInfo.getBatchSize(), pagingInfo.getFirstItem()));
        }
        return items;
    }





The getItems() method wraps a List of item objects in a DataModel. UIData, the superclass of 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.   

The Item properties Name, Photo, and price are displayed with the column component:

Code Sample from: list.xhtml

<h:dataTable var="row" value="#{catalog.items}">
  <h:column>
      <f:facet name="header">
          <h:outputText value="#{msgs.Name}"/>
      </f:facet>
      <h:outputText value="#{row.name}"/>
  </h:column>

  <h:column>
      <f:facet name="header">
          <h:outputText value="#{msgs.Photo}"/>
      </f:facet>
<h:graphicImage library="images" name="#{row.imagethumburl}"/>
  </h:column>

  <h:column>
      <f:facet name="header">
          <h:outputText value="#{msgs.Price}"/>
      </f:facet>
      <h:outputText value="#{row.price}"/>
  </h:column>
</h:dataTable>


The column tags represent columns of data in a UIData component. While the UIData component is iterating over the rows of data, it processes the UIColumn component associated with each column tag for each row in the table.

The UIData component  iterates through the list of items (catalog.items)  and displays the row.price. Each time UIData iterates through the list of items, it renders one cell in each column.

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

Using the Java Persistence API (JPA) with JSF

The Catalog ManagedBean uses the Java Persistence API EntityManager Query object to return a list of items. The Catalog ManagedBean annotates the field private EntityManager em;  with @PersistenceContext , which causes an entity manager to be injected when the managed bean is instatiated.


Code Sample from: Catalog.java

@ManagedBean
@SessionScoped
public class Catalog implements Serializable {


@PersistenceUnit(unitName = "catalogPU")
    private EntityManagerFactory emf;

    private EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public List<Item>  getNextItems(int maxResults, int firstResult) { 
       EntityManager em = getEntityManager();
       try {    
Query q = em.createQuery("select object(o) from Item as o");
         q.setMaxResults(maxResults);
         q.setFirstResult(firstResult);
         return q.getResultList();
        } finally {
            em.close();
        }      
   }


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: q.setMaxResults(int maxResult) sets the maximum number of results to retrieve. q.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
public class Item implements java.io.Serializable {

@Id
    private Integer id;

    private String name;   
    private String description;   
    private String imageurl;   
    private String imagethumburl; 
    private BigDecimal price;
@ManyToOne
    private Address address;
@ManyToOne
    private Product product;


    public Item() { }

    public String getName() {
        return name;
    }

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


    ...
}   




The Catalog ManagedBean pages through the list of Items by maintaining the PagingInfo.firstItem and PagingInfo.batchSize attributes and passing these as parameters to the  getNextItems(firstItem, batchSize) method. The catalog's scope  is defined with the annotation @SessionScoped, a JSF Managedbean with session scope will be stored in the session meaning that the bean's properties will stay alive for the life of the Http Session.


A JSF commandButton is  used to provide a button to click on to display the next page of items.  The commandButton tag is used to submit an action event to the application. 

Code Sample from: list.xhtml

 <h:commandButton action="#{catalog.next}" value="#{msgs.Next}" />   


This commandButton action attribute references the catalog Managed bean next() method which calculates the next page's first row number  and returns a logical outcome String, which causes the list.xhtml page to display the next page's list . The catalog next method is defined as shown below:

Code Sample from: catalog.java

   public String next() {
       if (firstItem + batchSize < itemCount()) {
           firstItem += batchSize;
       }
       return "list";
   }


JSF 2.0 Simplified Navigation


The JavaServer Faces 2.0  NavigationHandler convention adds .xhtml to the logical outcome of the action method (in this example list) and loads that file, in this case, it loads the list.xhtml page after this method returns. If the action doesn't begin with a forward slash (/), JSF assumes that it's a relative path.  You can specify an absolute path by adding the slash like this "/items/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 catalog getDetail() method:

Code Sample from: list.xhtml

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


The catalog getDetail() method  gets the item data from the current row of the dataModel, and returns a string which causes the detail.xhtml page to display the item details :

Code Sample from: Catalog.java

    public String getDetail() {
        item = (Item) model.getRowData();
        return "detail";
    }


The JavaServer Faces NavigationHandler adds .xhtml to the logical outcome of the action, detail and loads that file. In this case, the JavaServer Faces implementation loads the detail.xhtml page after this method returns.

The detail.xhtml uses the outputText component to display the catalog ManagedBean's item properties:

Code Sample from: detail.xhtml

    <h:outputText value="#{catalog.item.name}" title="Name" />
    <h:outputText value="#{catalog.item.description}" title="Description"/>
    <h:graphicImage library="images" name="#{catalog.item.imageurl}" title="Imageurl" />

    <h:outputText value="#{
catalog.item.price}" title="Price" />
    <h:outputText value="#{
catalog.item.address.city}" title="Address" />
    <h:outputText value="#{
catalog.item.contactinfo.email}" title="Address"/>  





Hot Deployment and Session Retention with JSF 2.0 and Glassfish

  • Incremental compile of all JSF 2.0  artifacts when you save.
  • Auto-deploy of all web or Java EE 6 artifacts
  • Session retention: maintain stateful sessions across re-deployments


Conclusion
This concludes the sample application which demonstrates a pet catalog web application which uses JSF 2.0, JPA, GlassFish and MySQL.

Running the Sample Application

  1. If you haven't already done so, download and install NetBeans IDE , GlassFish , and MySQL Community Server . You can download and install GlassFish with NetBeans as a single bundle.
  2. Follow these instructions to install JSF Mojarra 2.0.0 Beta2 on GlassFish v2 or Glassfish v3
  3. Download the sample code.

Create the Pet Catalog database

In order to run the sample code you first have to create the Pet Catalog database and fill in  the Item table.

  1. Start NetBeans IDE
  2. Ensure that GlassFish is registered in the NetBeans IDE, as follows:
    • Click the Services tab in the NetBeans IDE.
    • Expand the Servers node. You should see GlassFish v2 in the list of servers. If not, register GlassFish v2 as follows:
      • Right-click the Servers node and select Add Server. This opens an Add Server Instance wizard.
      • Select GlassFish v2 in the server list of the wizard and click the Next button.
      • Enter the location information for the server and click the Next button.
      • Enter the admin name and password and click the Finish button.

  3. Start the MySQL or Java DB database as follows:
    • Click the Services tab in the NetBeans IDE.
    • Expand the databases node. You should see the Java DB database in the list of databases. If you have installed the MySQL server database, you should also see the MySQL database in the list of databases.. Note:  Java DB  comes bundled with Netbeans, you can  download MySQL separately.

    • Right-mouse click on the Java DB or MySQL server database and select Start.
  4. If you installed MySQL, set the properties of the MySQL server database as follows:
    • Right-click on the MySQL server database and select Properties. This opens the MySQL Server Properties dialog box, as shown in Figure 8.

      MySQL Server Basic Properties
      Figure 8. MySQL Server Basic Properties

    • In the Basic Properties tab, enter the server host name and port number. The IDE specifies localhost as the default server host name and 3306 as the default server port number.
    • Enter the administrator user name, if not displayed, and the administrator password -- the default administrator password is blank.
    • Click the Admin Properties tab.
    • Enter an appropriate path in the Path/URL to admin tool field. You can find the path by browsing to the location of a MySQL Administration application such as the MySQL Admin Tool.
    • Enter an appropriate path in the Path to start command. You can find the path by browsing to the location of the MySQL start command. To find the start command, look for mysqld in the bin folder of the MySQL installation directory.
    • Enter an appropriate path in the Path to stop command field. You can find the path by browsing to the location of the MySQL stop command. This is usually the path to mysqladmin in the bin folder of the MySQL installation directory. If the command is mysqladmin, in the Arguments field, type -u root stop to grant root permissions for stopping the server. The Admin Properties tab should look similar to Figure 9.

      MySQL Server Administration Properties
      Figure 9. MySQL Server Administration Properties

    • Click the OK button.

  5. Right-click on the MySQL server or Java DB database and select Start.
  6. Create the petcatalog database as follows:
    • Right-mouse click on the Java DB or MySQL server database and select Create Database. This will open a create Database window.
    • Enter the database name catalog for Java DB or petcatalog for MySQL.


      For Java DB enter userid password app app as shown below:


       Click O.K. to accept the displayed settings.
  7. Create the tables in the catalog database as follows:
    • Underneath Databases you should see a database connection for the petcatalog database. For example MySQL:

      or Java DB:

    • Right-mouse click on the petcatalog connection and select Connect.
    • Right-mouse click on the petcatalog connection and select Execute Command. This will open up a SQL command window.
    • Copy the contents of the catalog.sql file in the riapetcatalog\\exercises\\exercise0 directory and paste the contents into the SQL command window, as shown in below:

      Creating Tables in the Database
    • Click the Run SQL icon Run SQL icon (Ctrl+Shift+E) above the SQL command window.
    • Note: It is ok to see this: "Error code -1, SQL state 42Y55: 'DROP TABLE' cannot be performed on 'ITEM' because it does not exist. Line 2, column 1" . This just means you are deleting a table that does not exist.  If you need to delete and recreate the tables you will not  see this message the second time.
  8. View the data in the Pet Catalog database Item table as follows:
    • Underneath Databases you should see a database connection for the petcatalog database. For example MySQL:

      or Java DB:

    • If the database connection is broken like in the following diagram:

      • Right-mouse click on the petcatalog connection and select Connect. as shown below:

      • if prompted for a password, for MySQL leave it blank, for JavaDB enter user app password app.
    • Expand the Tables node below the petcatalog database in the Services window. You should see the item table under the Tables node. You can expand the item table node to see the table columns, indexes, and any foreign keys, as shown in below :
      An Expanded Table Node
      Figure 12. An Expanded Table Node

      You can view the contents of a table or column by right-clicking the table or column and selecting View Data as shown  below:

      Viewing the Contents of a Table
      Figure 13. Viewing the Contents of a Table


  9. Follow these instructions to Create a JDBC Connection pool and JDBC resource.Name the  pool mysql_petcatalog_rootPool and the jndi resource jdbc/petcatalog. Note: you do not have to create a JDBC connection pool and resource if you use the Netbeans wizard to generate JPA entities from database tables as described in this article GlassFish and MySQL, Part 2: Building a CRUD Web Application With Data Persistence.

Running the Sample solution:

If you want to run the sample solution, you have to create the catalog database tables first as described above.

  1. If you haven't already download the sample code and start the NetBeans IDE. Unzip the catalog.zip file which you downloaded, this will create a catalog directory with the project code.
  2. Open the catalog/setup/sun-resources.xml file and verify that the property values it specifies match those of the petcatalog database and jdbc resources you created. Edit the property values as necessary.

  3. Open the catalog project as follows:
    • In NetBeans IDE, click Open Project in the File menu. This opens the Open Project dialog.
    • Navigate in the Open Project dialog to the catalog  directory and click the Open Project button.

    In response, the IDE opens the catalog project.  You can view the logical structure of the project in the Projects window (Ctrl-1).
  4. Run the catalog by right-clicking on the catalog project in the Projects window and selecting Run Project. The NetBeans IDE compiles the application, deploys it on Glassfish, and brings up the default page in your browser.  (at http://localhost:8080/catalog/).

For more information see the following resources:



Wednesday Jul 01, 2009

2 JavaOne Hands On Labs , Sun Technology Exchange, Java Technology Day Israel, and Java Day Turkey

jax

June: 2 JavaOne Hands On Labs , Sun Technology Exchange, Java Technology Day Israel, and Java Day Turkey  

I had a very busy June, I gave two Hands on Labs at JavaOne, two sessions at the Sun Technology Exchange, three sessions at Java Technology Day in Tel Aviv Israel, and one session at Java Day in Istanbul Turkey.

JavaOne Hands On Labs:

iguana.jpg iguana.jpg

I co-developed and delivered 2 Hands On Labs for JavaOne this year:

You can download these 2 HOLs documentation and code below:


Sun Technology Exchange:

iguana.jpg iguana.jpg
In Fort Lauderdale as part of the Sun Technology Exchange I gave two educational sessions to learn how:
  • JavaFX can help you build rich internet applications (RIAs) and includes the tools and platform SDK for developers, web developers, and designers to create dynamic applications.
  • GlassFish, an enterprise-quality Java EE 5 application server, offers advanced clustering, centralized administration, and best-in-class performance.
  • download the slides


Java Technology Day Israel

iguana.jpg iguana.jpgiguana.jpg
At the Java Technology Day in Israel I gave the following sessions:
  • WSIT Reliability Security and Transactions in Web Services
    • Metro is a high-performance, extensible, easy-to-use web service stack. You can use it for every type of web service, from simple to reliable, secured, and transacted web services that interoperate with .NET services. Metro bundles stable versions of the JAX-WS (Java API for XML Web Services) reference implementation and WSIT (Web Services Interoperability Technology). JAX-WS is a fundamental technology for developing SOAP-based and RESTful Java technology-based web services. WSIT enables secure, reliable interoperability between Java technology-based web services and Microsoft's Windows Communication Foundation.
    • you can download and try out WSIT in this JavaOne HOL: Metro: Try Out Simple and Interoperable Web Services and with these lab instructions.
    • You can read more about some of the example code for this session at
      GlassFish and MySQL, Part 3: Creating a Pet Catalog Web Service
  • 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 talks about MySQL database design and SQL tuning for developers.
    • download or view a screencast of this presentation
  • OpenESB and Connecting Enterprises
    • This session  explains and demonstrates several concrete technologies that make SOA architecture possible - BPEL (Business Process Execution Language), JBI (Java Business Integration) and OpenESB. The part of of BPEL starts with an explanation of the requirements of standardized business process language. The BPEL language is then described using an example. The relationship between BPEL and WSDL is also explained. Finally, BPEL designer and runtime that comes with NetBeans IDE is demonstrated using Travel reservation sample BPEL project. It also explains the motivation of the JBI and OpenESB as a standardized application integration framework in the same way J2EE architecture standardized how enterprise applications are built and deployed. Finally Sun's solution in SOA and application integration space is discussed. Whenever possible, concrete steps of building, deploying and testing SOA applications will be demonstrated step by step.
  • download the slides for all 3

Java Day Turkey

iguana.jpg iguana.jpg iguana.jpg
At the Java Day in Istanbul Turkey I gave the MySQL for Developers session again, see above for more information.




Friday May 01, 2009

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


I'm Speaking At JavaOne

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

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

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

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


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

Duke



Thursday Apr 16, 2009

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

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

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


You can dowload the StarOffice presentation here

Developing RESTful Web Services with Netbeans and JAX-RS


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

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

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


You can get more information here:

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

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

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

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





Wednesday Mar 25, 2009

Groovy and Grails with Netbeans, Glassfish and MySQL

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

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

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

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

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

RESTful Pet Catalog screencast

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

Glassfish and MySQL part 4

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

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

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

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

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

Tuesday Mar 10, 2009

Glassfish, MySQL, REST, and JavaFX

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

Building a Grails Pet Catalog using Netbeans 6.5 and MySQL

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 : JavaFX Example Application


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

RESTful Pet Catalog using JAX-RS and dojo

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



Friday Dec 05, 2008

JavaFX RESTful Pet Catalog Client

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


About

caroljmcdonald

Search

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