UsingVWICEfacesWithNetBeans

Revision as of 17:51, 5 November 2009 by Admin (Talk | contribs)
(diff) ← Older revision | Current revision (diff) | Newer revision → (diff)

Using Java Persistence API in a Visual Web ICEfaces framework and NetBeans including Ajax Push

Contributed By; Bilal Ahamed


[[{TableOfContentsTitle=TableOfContents} | {TableOfContents title='Table of Contents'}]]

Getting Started


To follow this tutorial, you need the following softwares;

  • NetBeans IDE 6.5
  • MySQL
  • Creating a Database
    1. Open up the MySQL Command Line Client from your Start > All Programs > MySQL menu. The Command Line
    2. Client displays prompting you to enter your root password.
    3. Enter the password , and a brief welcome message displays, introducing you to the MySQL monitor.
    4. Copy the SQL code shown below at the prompt;
 
SET FOREIGN_KEY_CHECKS=0;

CREATE DATABASE `userdb`
CHARACTER SET 'latin1'
COLLATE 'latin1_swedish_ci';
USE `userdb`;
CREATE TABLE `user` (
`user_id` int(11) NOT NULL auto_increment,
`user_firstname` varchar(50) NOT NULL,
`user_lastname` varchar(50) NOT NULL,
`add1` varchar(50) NOT NULL,
`add2` varchar(50) NOT NULL,
`city` varchar(50) NOT NULL,
`state` varchar(50) NOT NULL,
`postal_code` varchar(50) NOT NULL,
PRIMARY KEY  (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;

INSERT INTO `user` (`user_id`, `user_firstname`, `user_lastname`, `add1`, `add2`, `city`, `state`, `postal_code`) VALUES
(1,'Anjum','MM','96/2','Krishna Buildings','Bangalore','Karnataka','5670098'),
(2,'Jinad','Ahamed','Hima','Meppayur','Calicut','Kerala','8977676'),
(3,'Jesbel','Ahamed','Hima','Meppayur','Calicut','Kerala','8977676'),
(4,'Lamiya','Fathima','Tranquilinne','Meppayur','Calicut','Kerala','5353535345');
COMMIT;
  • After database is created, goto Windows > Services and expand Drivers.
  • Right-click MySQL(Connector/J driver) and select Connect using following details;
Host                 localhost
Port                  3306
Database          pmdb
User                 root
Password          "Your password"
  • Click OK to finish.

File:db-connection_UsingVWICEfacesWithNetBeans.gif

Creating Projects


  1. Create the Java SE application project called UserModelApp You also need to set the package to com.user.model. You can do this by changing the default Create Main Class entry from usermodelapp.Main to com.user.model.Main. Click Finish.
  2. Create the Visual Web ICEfaces project called UserWebApp.

Linking the Projects Together

Now you want to link the two projects together. Specifically, you want the
UserModelApp
project to be a dependency of the {UserWebApp} project. To make UserModelApp a dependent project of UserWebApp, you need to add the UserModelApp.jar file to the UserWebApp project.

Here's how to do this;

  1. In the Projects window, right Click the UserWebApp project node and select Properties from its context menu.
  2. In the Project Properties dialog, click the Libraries node in the Categories section on the left. Then, click Add Project.
  3. In the Add Project window, browse to the location with the UserModelApp project and select it. Then click Add Project JAR Files. This step adds the UserModelApp jar file to the compile-time libraries for the UserWebApp project, and UserModelApp appears in the Project Properties screen.
  4. Click OK in the Project Properties screen to complete the process.

Creating a Java Persistence Entity Class Representing the Users Database Table

  • In the Projects (or Files) window, right click the UserModelApp project. From the context menu, select New > Entity Classes from Database.
  • The New Entity Classes from Database Database Tables dialog displays. If the Database Connection field is blank, then select the Select "jdbc:mysql://localhost:3306/pmdb[[[rootOnDefaultSchema | [root on Default schema]] from the pull-down list.
The Available Tables column displays all the tables in the pmdb database, including the users table.
  • Select the user table and click Add to move user to the Selected Tables column. Click Next after moving the user table.

File:Persistence-Entity-1_UsingVWICEfacesWithNetBeans.gif

  • The Entity Classes dialog displays. The IDE displays the database table name user, and suggests a class name of Users. (Double click this class name to change it.)

Creating a Persistence Unit

In the Create Persistence Unit dialog, set the Persistence Unit Name to UserPU.

  1. Select Persistence Library as TopLink.
  2. Click Create, then click Finish in the Entity Classes screen to complete the operation and create the UserPU persistence unit.

File:Persistence-Entity-2_UsingVWICEfacesWithNetBeans.gif

Generating JPA Controller Classes From Entity Classes

  1. In the Projects (or Files) window, right click the UserModelApp project.
  2. From the context menu, goto New > Other and select Persistence from Categories then select JPA Controller Classes From Entity Classes, then click Next.
  3. Select "com.user.model.User” and click Add to move to Selected Entity Classes, then click Next.

File:jpa-cantroller-1_UsingVWICEfacesWithNetBeans.gif

  1. Change Package com.userController.model then click Finish.

File:jpa-cantroller-2_UsingVWICEfacesWithNetBeans.gif

Binding the Entity Bean to the Table Component


Creating a Property in the Session Bean

  1. First, create a property in SessionBean1 that returns an list of User objects
  2. Add a property called user to SessionBean1. Type in the following line of code;
     private List<User> user;
  3. Use the source editor's context menu Fix Imports function to fix error. To fix the error, the IDE adds the following imports;
    com.user.model.User
    and {java.util.List}
  4. Generate get and set methods for the user property. Right click the line of code you typed in and select the action Insert Code. Choose Getter and Setter from the popup menu.
  5. Then, select
    user: List<User>
    The Insert Code action adds public get and set methods. When finished, SessionBean1 should include the following code.
public List<User> getUser() {
        return user;
    }

    public void setUser(List<User> user) {
        this.user = user;
    }

Creating the Initialization Method

Add a method called updateUser to SessionBean1. This method will be used to initialize the user property. Here's the code for the method;

public void updateUser(){
     UserJpaController usersController = new UserJpaController();
     user = usersController.findUserEntities();
     }
  • Use the Fix Imports function to fix the import needed for updateUser. If there are errors in the code, do a Save All files to clear them.
  • Add a call to the updateUsers method in the SessionBean1 init method: updateUser();.

The SessionBean1 init method should look as follows (comment lines not shown);

public void init() {
        // Perform initializations inherited from our superclass
        super.init();
        try {
            _init();
        } catch (Exception e) {
            log("SessionBean1 Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e: new FacesException(e);
        }
        updateUser();
    }
  • Save all the files.
  • Build both the UserModelApp and UserWebApp projects.

Binding the Property to the Table Component

  1. In the Visual Design Editor, you see the template for an ICEfaces page called Page1. Delete the default InputTextarea, and from the ICEfaces Palette drag an
    ice:DataTable
    onto the page .
  2. Add Row Selector using the context menu for the
    ice:DataTable
    .
  3. When the row selector binding dialog appears, simply accept the defaults and close(don’t

click Apply), as illustrated below. Later you will use the rowSelectior1processAction listener to implement the editing logic for selected rows.

File:rowSelection_UsingVWICEfacesWithNetBeans.gif

  1. Expand the Page 1 > dataTable1 node. Right click dataTable1 node and select Bind to Data. You need to create the binding #{SessionBean1.user} as illustrated below.

File:bindingData_UsingVWICEfacesWithNetBeans.gif

Page1.jsp
should look as follows;
                    <ice:dataTable id="dataTable1" style="position: absolute; left: 96px; top: 24px" value="#{SessionBean1.user}" var="currentRow">
                        <ice:column id="column1">
                            <ice:outputText id="outputText1" value="#{currentRow[COLUMN1]}"/>
                            <f:facet name="header">
                                <ice:outputText id="outputText2" value="Table_Column1"/>
                            </f:facet>
                            <ice:rowSelector id="rowSelector1" selectionListener="#{Page1.rowSelector1_processAction}"/>
                        </ice:column>
                        <ice:column id="column2">
                            <ice:outputText id="outputText3" value="#{currentRow[COLUMN2]}"/>
                            <f:facet name="header">
                                <ice:outputText id="outputText4" value="Table_Column2"/>
                            </f:facet>
                        </ice:column>
                        <ice:column id="column3">
                            <ice:outputText id="outputText5" value="#{currentRow[COLUMN3]}"/>
                            <f:facet name="header">
                                <ice:outputText id="outputText6" value="Table_Column3"/>
                            </f:facet>
                        </ice:column>
                    </ice:dataTable>
When using JPA in Visual Web ICEfaces framework you have to edit the data table binding code. With Page1 displayed in the Design window, click the JSP tab to open the jsp code in the source editor and make following changes.
<ice:dataTable id="dataTable1" style="left: 14px; top: 14px; position: absolute" value="#{SessionBean1.user}" var="currentRow">
                        <ice:column id="column1">
                            <ice:outputText id="outputText1" value="#{currentRow[userFirstname]}"/>
                            <f:facet name="header">
                                <ice:outputText id="outputText2" value="First Name"/>
                            </f:facet>
                            <ice:rowSelector id="rowSelector1" selectionListener="#{Page1.rowSelector1_processAction}"/>
                        </ice:column>
                        <ice:column id="column2">
                            <ice:outputText id="outputText3" value="#{currentRow[userLastname]}"/>
                            <f:facet name="header">
                                <ice:outputText id="outputText4" value="Last Name"/>
                            </f:facet>
                        </ice:column>
                        <ice:column id="column3">
                            <ice:outputText id="outputText5" value="#{currentRow[add1]}"/>
                            <f:facet name="header">
                                <ice:outputText id="outputText6" value="Address 1"/>
                            </f:facet>
                        </ice:column>
                        <ice:column id="column4">
                            <ice:outputText id="outputText7" value="#{currentRow[add2]}"/>
                            <f:facet name="header">
                                <ice:outputText id="outputText8" value="Address 2"/>
                            </f:facet>
                        </ice:column>
                        <ice:column id="column5">
                            <ice:outputText id="outputText9" value="#{currentRow[city]}"/>
                            <f:facet name="header">
                                <ice:outputText id="outputText10" value="City"/>
                            </f:facet>
                        </ice:column>
                        <ice:column id="column6">
                            <ice:outputText id="outputText11" value="#{currentRow[state]}"/>
                            <f:facet name="header">
                                <ice:outputText id="outputText12" value="State"/>
                            </f:facet>
                        </ice:column>
                        <ice:column id="column7">
                            <ice:outputText id="outputText13" value="#{currentRow[postalCode]}"/>
                            <f:facet name="header">
                                <ice:outputText id="outputText14" value="Pin No"/>
                            </f:facet>
                        </ice:column>
                    </ice:dataTable>
You can find column value (example-
ice:outputText id="outputText3" value="#{currentRow[userLastname]
}) userLastname from UserModelApp > com.user.model> User.java

private String userFirstname;

Click Design window and drag and drop six OutputLabel,six OutputText ,six InputText and a CommandButton.

Set OutputText id properties to

outputTextFname
outputTextLname
outputTextAdd1
outputTextAdd2.
outputTextCity
outputTextStae.
outputTextPin

Set inputText id properties to

nputTextFname.
inputTextLname
inputTextAdd1
inputTextAdd2
inputTextCity
inputTextState
inputTextPin

Set Button id properties to saveButton With Page1 displayed in the Design window, click the Java tab to open the Java code in the source editor. add the bold text Code given below

protected SessionBean1 getSessionBean1() {
        return (SessionBean1) getBean("SessionBean1");
    }

    public void rowSelector1_processAction(RowSelectorEvent rse) {
        int selectedRowIndex = rse.getRow();

        List<User> user = (List<User>) getSessionBean1().getUser();
        User usr = user.get(selectedRowIndex);
        outputTextFname.setValue(usr.getUserFirstname());
        outputTextLname.setValue(usr.getUserLastname());
        outputTextAdd1.setValue(usr.getAdd1());
        outputTextAdd2.setValue(usr.getAdd2());
        outputTextCity.setValue(usr.getCity());
        outputTextStae.setValue(usr.getState());
        outputTextPin.setValue(usr.getPostalCode());

    }

    public void saveButton_processAction(ActionEvent ae) {
        User newUser = new User();
        newUser.setUserFirstname((String) inputTextFname.getText());
        newUser.setUserLastname((String) inputTextLname.getText());
        newUser.setAdd1((String) inputTextAdd1.getText());
        newUser.setAdd2((String) inputTextAdd2.getText());
        newUser.setCity((String) inputTextCity.getText());
        newUser.setState((String) inputTextState.getText());
        newUser.setPostalCode((String) inputTextPin.getText());
        UserJpaController userController = new UserJpaController();
        userController.create(newUser);
        inputTextFname.changeText("");
        inputTextLname.changeText("");
        inputTextAdd1.changeText("");
        inputTextAdd2.changeText("");
        inputTextCity.changeText("");
        inputTextState.changeText("");
        inputTextPin.changeText("");
    }


You can now build and run the application. When a row is selected it should look something like this.

File:outputscreen_UsingVWICEfacesWithNetBeans.gif

Note: some times server will through mysql driver not found error,then do the following A JDBC driver translates an application’s JDBC calls into the protocol of the database server. To integrate the JDBC driver into an administrative domain, do either of the following:

  • Make the driver accessible to the common class loader.
    1. Copy the driver’s JAR and ZIP files into the domain-dir/lib directory or copy its class files into the domain-dir/lib/ext directory.
    2. Restart the domain.
  • Make the driver accessible to the system class loader.
    1. Select Application Server.
    2. Click the JVM Settings tab.
    3. Click the Path Settings tab.
    4. In the Classpath Suffix field, enter the fully-qualified path name for the driver’s JAR file.
    5. Click Save.
    6. Restart the server.

Add Ajax Push


The Ajax Push infrastructure in ICEfaces is organized under an application scope bean called RenderManager. To add this bean to your application open the faces-config.xml in XML view in the editor.

Right click an existing managed bean definition and from the context menu select JavaServer Faces > Add Managed Bean.

Define a managed bean called RenderManager with the class com.icesoft.faces.async.render.RenderManager in applications scope as illustrated below.

Bean Name    renderManager
Bean Class     com.icesoft.faces.async.render.RenderManager
Scope             application

File:renderMang1_UsingVWICEfacesWithNetBeans.gif

This will result in the following code being added to your faces-config.xml.

<managed-bean>
        <managed-bean-name>renderManager</managed-bean-name>
        <managed-bean-class>com.icesoft.faces.async.render.RenderManager </managed-bean-class>
        <managed-bean-scope>application</managed-bean-scope>
    </managed-bean>

You will need access to the RenderManager from your page bean so add it as a managed property with the following bold text code.

   <managed-bean>
        <managed-bean-name>Page1</managed-bean-name>
        <managed-bean-class>userwebapp.Page1</managed-bean-class>
        <managed-bean-scope>request</managed-bean-scope>
        <managed-property>
            <property-name>renderManager</property-name>
            <property-class>com.icesoft.faces.async.render.RenderManager</property-class>
            <value>#{renderManager}</value>
        </managed-property>
    </managed-bean>
Next you need your page bean to implement the
Renderable
interface as shown below.
public class Page1 extends AbstractPageBean implements Renderable {

Now, right click and select Fix Imports. Also, if you right click the page, and select Insert Code from the context menu, you will see a dialog from which you can select Implement Method. You can now select the Renderable interface and generated the members as shown below.

File:Implement-Method_UsingVWICEfacesWithNetBeans.gif

Before you complete the implementation, you need to add some state to your page bean as shown below. You will need access to the PersistentFacesState, RenderManager, and an OnDemandRenderer to hold the list of Renderables (1 per client session). The OnDemandRenderer is a named singleton that will be created by the RenderManager.

private PersistentFacesState state = null;
    private RenderManager renderManager;
    private OnDemandRenderer userGroup = null;

    public void setRenderManager(RenderManager renderManager){
        if(renderManager != null){
            this.renderManager = renderManager;
           userGroup= renderManager.getOnDemandRenderer("userGroup");
            useerGroup.add(this);
        }
    }
   
    public RenderManager getRenderManager(){
        return renderManager;
    }
Make sure the
persistentFacesState
is initialized in the page bean init() member.

init()

    public void init() {
        ...
        // Perform application initialization that must complete
        // *after* managed components are initialized
        // TODO - add your own initialization code here
        state = PersistentFacesState.getInstance(); 
    }
Now you can complete the implementation of the
Renderable
interface with the following code.
    public PersistentFacesState getState() {
       return state;
    }

    public void renderingException(RenderingException re) {
        userGroup.remove(this);
    }
Finally, you need to request a render whenever changes are committed to the database. This is done in the action listener for the
saveButton
button as shown below;

saveButton_processAction(ActionEvent ae)

public void saveButton_processAction(ActionEvent ae) {
        User newUser = new User();
        newUser.setUserFirstname((String) inputTextFname.getText());
        newUser.setUserLastname((String) inputTextLname.getText());
        newUser.setAdd1((String) inputTextAdd1.getText());
        newUser.setAdd2((String) inputTextAdd2.getText());
        newUser.setCity((String) inputTextCity.getText());
        newUser.setState((String) inputTextState.getText());
        newUser.setPostalCode((String) inputTextPin.getText());
        // Add the new Entity to the database using UserController
        UserJpaController userController = new UserJpaController();
        userController.create(newUser);
        inputTextFname.changeText("");
        inputTextLname.changeText("");
        inputTextAdd1.changeText("");
        inputTextAdd2.changeText("");
        inputTextCity.changeText("");
        inputTextState.changeText("");
        inputTextPin.changeText("");
        userGroup.requestRender();
    }
You can now build and run the application. If you view it in two different browsers you should see changes pushed to both when add new data. The application will also work from multiple windows in the same browser instance, but first you will need to turn on
concurrentDOMViews
in the {web.xml} as shown below.
    <context-param>
        <param-name>com.icesoft.faces.concurrentDOMViews</param-name>
        <param-value>true</param-value>
    </context-param>
Not logged in. Log in, Register

By use of this website, you agree to the NetBeans Policies and Terms of Use. © 2012, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo