practice jee5 for jdeveloper 11g (tp4) revision 1 - … · 1 practice for jee5 – for jdeveloper...

93
1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model layer and ADF Faces Rich Client as a view layer. Modified by: Dr. Ahmad Taufik Jamil BSc (Med), MD, MPH, MSc(IT) Head, Center of Information Technology UKM Medical Center, Malaysia Revision: 1.1 (13 July 2008) Adapted from: Oracle AS 10g R3: Build J2EE Applications 1, Appendix A, Practice & Solution

Upload: vanbao

Post on 11-Oct-2018

217 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

1

Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model layer and ADF Faces Rich Client as a view layer.

Modified by:

Dr. Ahmad Taufik Jamil BSc (Med), MD, MPH, MSc(IT) Head, Center of Information Technology UKM Medical Center, Malaysia Revision: 1.1 (13 July 2008) Adapted from:

Oracle AS 10g R3: Build J2EE Applications 1, Appendix A, Practice & Solution

Page 2: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

2

Table of Contents Practice 1 Practice 1-1: Create an Application with Two Projects 3 Practice 1-2: Create the EJB Data Model 4 Practice 1-3: Create the Source Code for Session Bean and Data Control 6 Practice 1-4: Create a Data-Aware JSF Page 11 Practice 2 Practice 2-1: Create an Application and a JSF Diagram 13 Practice 2-2: Add a Managed Bean to the Project 15 Practice 3 Practice 3-1: Create a New Application and EJB3.0 17 Practice 4 Practice 4-1: Create and Use a Data Control 30 Practice 4-2: Modify the Binding 33 Practice 5 Practice 5-1: Create a Template jspx 34 Practice 5-2: Create the SREdit Page and Apply the Template 36 Practice 5-3: Add Data-Aware Components to the SREdit Page 37 Practice 6 Practice 6-2: Add Data Components to the Search Page 40 Practice 6-3: Modify the Default Behavior 42 Practice 7 Practice 7-1: Complete the Edit Page 45 Practice 7-2: Add the Commit Function 51 Practice 8 Practice 8-1: Link SRSearch to SREdit 52 Practice 8-2: Add a Delete Page 57 Practice 8-3: Wire the Buttons 58

Page 3: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

3

Practice 1 In this practice you create an application using stateless EJB, data control and ADF Faces Rich Client. The practice includes detailed steps for each of the areas of the application. Practices in later lessons have less detailed instructions, but for this introductory practice, we provide step-by-step instructions.

Practice 1-1: Create an Application with Two Projects All the components for an application in JDeveloper are contained within a structure called an application. It is accessible through the Applications Navigator. The first step in application development using JDeveloper 11g is to create an application structure. In this section, you create an application and rename the default projects.

1) Open JDeveloper 11g. (You may download the latest version of Oracle JDeveloper 11g from here: http://www.oracle.com/technology/products/jdev/11/index.html)

i. Double-click the JDeveloper 11g icon. ii. If JDeveloper prompts you to migrate from a previous version, click No.

2) Create an Application.

i. Select menu File then New…. (Ctrl-N) ii. In the New Gallery dialog box (Current Project Technologies tab), Select General >

Applications, then select Application, in Items column. iii. Click OK. iv. Use EJB-ADFFRC as the Application Name. v. Enter sr as the Application Package Prefix. vi. Select Java EE Web Application for the Application Template. vii. Click OK. This creates the EJB-ADFFRC application and includes two projects: Model

and ViewController.

3) Rename the default projects.

i. Select the Model project in the Applications Navigator. ii. Select menu File > Rename…. iii. Enter DataModel for the new name.

iv. Click Save All.

v. Do the same for the ViewController project in the Applications Navigator, and rename to UserInterface.

Page 4: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

4

vi. Click Save All.

The Applications Navigator now looks like the screenshot shown below:

Page 5: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

5

Practice 1-2: Create the EJB Data Model In this section, you create the EJB data model, which will be the basis of the application.

The first part of this practice is to create a new database connection. 1) In JDeveloper, choose menu View > Database Navigator.

2) Right-click the EJB-ADFFRC node and choose New Connection.

3) In the Connection Name field, enter srconn.

4) Enter the values shown in the following table;

Field Value Connection Type: Oracle (JDBC) Username: SRDEMO Password: Oracle Deploy Password: Select the check box

5) For Oracle (JDBC) setting, enter the following values;

Field Value Driver thin Host Name localhost This is the default host name if the database is run on the same machine as JDeveloper. If the database is on another machine, enter the name (or IP address) of the computer where the database is located.

JDBC Port 1521 SID XE

6) Click Test Connection. If the database is available and the connection details are correct, you will see a success message. If not, check the values.

Page 6: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

6

7) When the connection is successful, click OK to create the connection. Now that you have a connection, you can create the default Data Model for your application.

8) In the Applications Navigator, right-click DataModel and select New….

9) In the New Gallery, select Business Tier, EJB, Session Bean.

Page 7: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

7

10) Click OK. This opens the Create Session Bean Wizard.

11) Step 1 of 5: Select EJB version i. Select Enterprise JavaBeans 3.0 (Java EE 5.0). ii. Click Next.

12) Step 2 of 5: EJB Name and Options.

i. Enter Products for EJB Name. ii. Accept the default values. iii. Click Next.

13) Step 3 of 5: Class Definitions

i. Accept the default values. ii. Click Next.

14) Step 4 of 5: EJB Components Interfaces

i. Accept the default values. ii. Click Next then Finish. iii. Click Save.

15) The Applications Navigator should look like the following:

Page 8: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

8

Page 9: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

9

Practice 1-3: Create the Source Code for Session Bean and Create Data Control

1) Enter the following source code inside ProductsBean.java

//Second Constructor public ProductsBean(int prodId, String name, String image, String description) { this.prodId=prodId; this.name=name; this.image=image; this.description=description; } //Dependancy Injection for datasource @Resource(name="jdbc/srconnDS") private DataSource srconnDataSource; public void setDataSource(DataSource myDB){ this.srconnDataSource = myDB; } //Variable declaration private int prodId; private String name; private String image; private String description; //Getter & Setter methods public void setProdId(int prodId) { this.prodId = prodId; } public int getProdId() { return prodId; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setImage(String image) { this.image = image; } public String getImage() { return image; }

Page 10: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

10

public void setDescription(String description) { this.description = description; } public String getDescription() { return description; } //Connection to Database private Connection connectToDatabase(){ Connection conn=null; int ret_code; try { conn=srconnDataSource.getConnection(); } catch (SQLException se) { ret_code = se.getErrorCode(); System.out.println("SQL Error while connecting to the database : "+ se.toString()); } catch (Exception ne) { System.out.println("Other Error while connecting to the database : "+ ne.toString()); } return conn; } //Insert Method public void insertProducts(int prodId, String name, String image, String description){ Connection conn = null; PreparedStatement pstmtInsert=null; try { conn = connectToDatabase(); String sqlInsert = "INSERT INTO PRODUCTS (PROD_ID, NAME, IMAGE, DESCRIPTION) VALUES (?,?,?,?)"; pstmtInsert = conn.prepareStatement(sqlInsert); pstmtInsert.setInt(1, prodId); pstmtInsert.setString(2, name); pstmtInsert.setString(3, image); pstmtInsert.setString(4, description); pstmtInsert.executeUpdate(); } catch (SQLException e) { System.out.println(e.getSQLState()); System.out.println(e.getMessage()); System.out.println(e.getErrorCode());

Page 11: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

11

System.out.println("ERROR: insertProducts()"); } finally{ try{ pstmtInsert.close(); conn.close(); } catch(SQLException e2) { System.out.println(e2); } } } public void updateProducts(int prodId, String name, String image, String description){ Connection conn = null; PreparedStatement pstmtUpdate=null; try { conn = connectToDatabase(); String sqlUpdate = "UPDATE PRODUCTS SET NAME = ?, IMAGE = ?, DESCRIPTION = ? WHERE PROD_ID = ?"; pstmtUpdate = conn.prepareStatement(sqlUpdate); pstmtUpdate.setString(1, name); pstmtUpdate.setString(2, image); pstmtUpdate.setString(3, description); pstmtUpdate.setInt(4, prodId); pstmtUpdate.executeUpdate(); } catch (SQLException e) { System.out.println(e.getSQLState()); System.out.println(e.getMessage()); System.out.println(e.getErrorCode()); System.out.println("ERROR: updateProducts()"); } finally{ try{ pstmtUpdate.close(); conn.close(); } catch(SQLException e2) { System.out.println(e2); System.out.println("Error from finally block updateProducts");

Page 12: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

12

} } } public List<ProductsBean> findProductsById(int prodId){ List<ProductsBean> retval = new ArrayList<ProductsBean>(); Connection connection = null; PreparedStatement pstmtselect=null; ResultSet rs=null; try { connection = connectToDatabase(); String sql = "SELECT * FROM PRODUCTS WHERE PROD_ID = ? "; pstmtselect = connection.prepareStatement(sql); pstmtselect.setInt(1, prodId); rs = pstmtselect.executeQuery(); CachedRowSetImpl crset = new CachedRowSetImpl(); crset.populate(rs); while (crset.next()) { ProductsBean productsBean = new ProductsBean(crset.getInt("PROD_ID"),crset.getString("NAME"),crset.getString("IMAGE"),crset.getString("DESCRIPTION")); retval.add(productsBean); } } catch (SQLException e) { e.printStackTrace(); System.out.println(e.getSQLState()); System.out.println(e.getMessage()); System.out.println(e.getErrorCode()); System.out.println("ERROR: findProductsById(int productId)"); } catch (Exception e1) { e1.printStackTrace(); } finally { try{ rs.close(); pstmtselect.close(); connection.close(); } catch(SQLException e2) { System.out.println(e2); } }

Page 13: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

13

return retval; } public List<ProductsBean> findAllProducts(){ List<ProductsBean> retval = new ArrayList<ProductsBean>(); Connection connection = null; PreparedStatement pstmtselect=null; ResultSet rs=null; try { connection = connectToDatabase(); String sql = "SELECT * FROM PRODUCTS"; pstmtselect = connection.prepareStatement(sql); rs = pstmtselect.executeQuery(); CachedRowSetImpl crset = new CachedRowSetImpl(); crset.populate(rs); while (crset.next()) { ProductsBean productsBean = new ProductsBean(crset.getInt("PROD_ID"), crset.getString("NAME"), crset.getString("IMAGE"), crset.getString("DESCRIPTION")); retval.add(productsBean); } } catch (SQLException e) { e.printStackTrace(); System.out.println(e.getSQLState()); System.out.println(e.getMessage()); System.out.println(e.getErrorCode()); System.out.println("ERROR: findAllProducts()"); } catch (Exception e1) { e1.printStackTrace(); } finally { try{ rs.close(); pstmtselect.close(); connection.close(); } catch(SQLException e2) { System.out.println(e2); } } return retval; } public void removeProducts(int prodId){

Page 14: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

14

Connection conn = null; PreparedStatement pstmtUpdate=null; try { conn = connectToDatabase(); String sqlDelete = "DELETE FROM PRODUCTS WHERE PROD_ID = ?"; pstmtUpdate = conn.prepareStatement(sqlDelete); pstmtUpdate.setInt(1, prodId); pstmtUpdate.executeUpdate(); } catch (SQLException e) { System.out.println(e.getSQLState()); System.out.println(e.getMessage()); System.out.println(e.getErrorCode()); System.out.println("ERROR: removeProducts(int productId)"); } finally{ try{ pstmtUpdate.close(); conn.close(); } catch(SQLException e2) { System.out.println(e2); System.out.println("Error from finally block removeProducts(int productId)"); } } }

2) Import the following libraries. import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import javax.sql.DataSource;

3) Compile: Right click ProductsBean.java, and click Make.

4) View ProductBean.java – Structure on the lower left panel. You may see like this:

Page 15: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

15

5) Expose all method into Local and Remote interface: a. Inside ProductsBean.java – Structure (Left lower column), right click method

findAllProducts() > EJB > Properties…

b. Check both Expose through Local interface and Expose through Remote interface, then click OK

c. Repeat the same for the other 4 methods (findAllProductsById, insertProducts, updateProducts and removeProducts).

Page 16: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

16

6) Right-click ProductsBean.java in the Applications Navigator and select Create Data Control.

7) Select Local for the interface to use with this EJB data control. Click OK.

8) Click Save All on the JDeveloper toolbar.

Page 17: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

17

Practice 1-4: Create a Data-Aware JSF Page In this section, you create a simple JSF page that displays data from the ProductsBean object. 1) Double click UserInterface project, Inside Project Properties dialog box, click Technology Scope and move ADF Faces from Available Technologies column to Selected Technologies column.

2) Right-click UserInterface in the Applications Navigator and select New. 3) In the New Gallery, select Web Tier > JSF > JSF Page and click OK.

Page 18: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

18

3) In Create JSF Page dialog box:

i. Enter products.jspx as the File Name: ii. Select Create as XML Document (*.jspx). iii. Select Automatically Expose UI Components in a New Managed Bean. Although you will

not use a managed bean in this practice, you can create it anyway. iv. Click OK.

Page 19: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

19

JDeveloper creates the JSF and opens the new JSF in the Visual Editor. In the next few steps, you add a data-aware component that displays product information. 9) In the Data Controls Palette, which is on the middle left of JDeveloper, expand ProductsLocal. 10) Expand findAllProducts() to show the ProductsBean data control.

11) Drag ProductsBean to the Visual Editor. When you drop ProductsBean on the Visual Editor, JDeveloper displays a pop-up menu where you select what type of component you want to use. 12) Select Tables > ADF Table from the pop-up menu.

Page 20: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

20

13) In the Edit Table Columns dialog box, select Row selection and Sorting. Change the Column Display Label to Product Id, Name, Image and Description and then click OK.

Page 21: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

21

14) Select af:table – srtable from products.jspx - Structure, edit Table – srtable - Property Inspector. Set Style > Box > Width and Height to 100 percent.

14) You have now created a data-aware JSF. Right-click anywhere in the Visual Editor and select Run. This starts an internal (or embedded) OC4J instance, and opens your page in a browser. 15) The page should look something like the following:

Page 22: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

22

16) Experiment with the page you have just created. Here are some ideas: i. Click any of the headings (Description, Name, Product Id) to re-sort the data in the table. ii. You may resize the column width. iii. When you are done, close the browser

17) You may get error when trying to resize, sort the table:

Page 23: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

23

18) Locate f:Validator inside product.jspx – Structure, under af:inputText, and delete all(4) of them.

Save All .

Page 24: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

24

19) Run the page again. No more error.

Page 25: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

25

Practice 2 In this practice, you build the JSF Navigation diagram for the course application. The application consists of three pages. You also add Case Navigation rules to the pages. In the last part of this practice, you will add a managed bean that is used to store information about the state of the client such as the current Service Request ID.

Practice 2-1: Create an Application and a JSF Diagram In this first section, you create a new Application, a JSF diagram, and three JSF page references. 1) Open the JSF Navigation diagram. Expand UserInterface project, Web Content, and then Page Flows. Double click faces-config.xml to open it.

2) Create three JSF Pages with the following names:

SRSearch.jsp SREdit.jsp SRDelete.jsp

i. Select JSF Diagram Objects in the Component Palette.

ii. Click JSF Page . iii. Click anywhere in faces-config.xml. iv. Change the default name of the reference. v. Repeat for each of the pages.

Page 26: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

26

3) Add a JSF Navigation Case from /SRSearch.jsp to /SREdit.jsp. Set the name of the case to edit.

i. Click JSF Navigation Case in the Component Palette (JSF Diagram Objects).

ii. Click the /SRSearch.jsp page reference, and then click the /SREdit.jsp page reference. iii. The default name should be success. Click the name and change it to edit.

4) Add a JSF Navigation Case from /SREdit.jsp to /SRSearch.jsp. Accept the default name, which should be success.

i. Click JSF Navigation Case in the Component Palette (JSF Navigation Diagram).

ii. Click the /SREdit.jsp page reference, and then click the /SRSearch.jsp page reference. iii. The default name should be success; if it is not, click the name and change it to success.

5) Add a JSF Navigation Case from /SRSearch.jsp to / SRDelete.jsp. Set the case name to delete.

i. Click JSF Navigation Case in the Component Palette (JSF Navigation Diagram).

ii. Click the /SRSearch.jsp page reference, and then click the /SRDelete.jsp page reference.

Page 27: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

27

iii. The default name should be success. Click the name and change it to delete. 6) Add a JSF Navigation Case from /SRDelete.jsp to /SRSearch.jsp. Set the case name to return.

i. Click JSF Navigation Case in the Component Palette (JSF Navigation Diagram).

ii. Click the /SRDelete.jsp page reference, and then click the /SRSearch.jsp page reference. iii. The default name should be success. Click the name and change it to return.

7) Add one more JSF Navigation Case from /SRDelete.jsp to / SRSearch.jsp. Set the case name to cancel.

i. Click JSF Navigation Case in the Component Palette (JSF Navigation Diagram).

ii. Click the /SRDelete.jsp page reference, and then click the /SRSearch.jsp page reference. iii. The default name should be success. Click the name and change it to cancel.

8) Your diagram should look similar to the following:

Page 28: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

28

Practice 2-2: Create a Managed Bean to the Project In this section, you create a managed bean. 1) Right-click the UserInterface project and select New…. 2) In the New Gallery dilog box, Select General > Simple Files > Java Class and click OK. 3) In the Create Java Class dialog box:

i. Enter UserSystemState for Name. ii. Set the Package to sr.view. iii. Accept the other defaults and click OK.

4) In the Applications Navigator, expand UserInterface > Application Sources > sr.view. 5) The Applications Navigator should look something like:

Page 29: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

29

Now that the directory structure is built, you can delete the Java class. 6) Add source code below to UseSystemState.java. private HashMap _settings = new HashMap(7); private static final String CURRENT_SVR_ID = "CURRENT_SVR_ID"; private static final String REFRESH = "REFRESH"; private static final String EDIT_REFRESH = "EDIT_REFRESH"; public UserSystemState() { //define some defaults } public boolean isRefresh(){ Boolean refresh = (Boolean)_settings.get(REFRESH); if (refresh == null){ refresh = false; } return refresh.booleanValue(); } public boolean isEditRefresh(){ Boolean refresh = (Boolean)_settings.get(EDIT_REFRESH); if (refresh == null){ refresh = false; } return refresh.booleanValue();

Page 30: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

30

} public Integer getCurrentSvrId(){ return (Integer)_settings.get(CURRENT_SVR_ID); } public void setRefresh(boolean flag){ _settings.put(REFRESH, new Boolean(flag)); } public void setEditRefresh(boolean flag){ _settings.put(EDIT_REFRESH, new Boolean(flag)); } public void setCurrentSvrId(Integer svrId){ _settings.put(CURRENT_SVR_ID,svrId); _settings.put(REFRESH,false); } public static void storeCurrentSvrID(Integer svrId){ FacesContext ctx = FacesContext.getCurrentInstance(); setManagedBeanValue(ctx,"userState.currentSvrId",svrId); } public static void refreshNeeded(){ FacesContext ctx = FacesContext.getCurrentInstance(); setManagedBeanValue(ctx,"userState.refresh",true); } public static void setManagedBeanValue(FacesContext ctx, String beanName, Object newValue) { StringBuffer buff = new StringBuffer("#{"); buff.append(beanName); buff.append("}"); setExpressionValue(ctx, buff.toString(), newValue); } public static void setExpressionValue(FacesContext ctx, String expression, Object newValue) { Application app = ctx.getApplication(); ValueBinding bind = app.createValueBinding(expression); Class bindClass = bind.getType(ctx); if (bindClass.isPrimitive()||bindClass.isInstance(newValue)) {

Page 31: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

31

bind.setValue(ctx, newValue); } }

7) Save All and compile.

Now that the Java class is in the project structure, you can add it as a managed bean. 8) Open the JSF Case Navigation diagram (faces-config.xml). 9) Add the UserSystemState class as a managed bean.

i. Click the Overview tab, which is at the bottom of the diagram. ii. Select Managed Beans. iii. Click “+” (New). iv. Bean Name: userState. v. Click the Browse button for the Class. vi. On the Search tab, enter sr.view as the Match Class Name. vii. Select sr.view.UserSystemState and click OK . viii. Change the scope to Session. ix. Make sure the Generate Class check box is not selected. x. Click OK to register this class as a managed bean.

Page 32: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

32

Practice 3 In this practice, you will create a default data model using stateless session EJB 3.0.

Practice 3-1: Create a New Application and EJB3.0 In this first section, you add a set of EJB 3.0 to the DataModel project you have already been using. 1) Create EJB 3.0:

a. In the Applications Navigator, right-click DataModel and select New…. b. In the New Gallery dialog box, select Business Tier, EJB, Session Bean. c. Click OK. This opens the Create Session Bean Wizard. d. Step 1 of 5: Select EJB version

i. Select Enterprise JavaBeans 3.0 (JEE 5.0). ii. Click Next.

e. Step 2 of 5: EJB Name and Options.

i. Enter ServiceRequests for EJB Name. ii. Accept the default values. iii. Click Next.

f. Step 3 of 5: Class Definitions

i. Accept the default values.

ii. Click Next.

g. Step 4 of 5: EJB Components Interfaces i. Accept the default values. ii. Click Next then Finish. iii. Click Save.

2) Repeat steps 1) a – g, to create another EJB, named Users. 3) Enter the following source code for ServiceRequestsBean.java and import all necessary libraries.

i. Libraries import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.sql.Date; import java.util.List; import javax.annotation.Resource; import javax.ejb.Stateless; import javax.sql.DataSource;

ii. Source code

Page 33: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

33

//Second Constructor public ServiceRequestsBean(int svrId,String status,Date requestDate,String problemDescription,int prodId,int createdBy,int assignedTo,Date assignedDate) { this.svrId=svrId; this.status=status; this.requestDate=requestDate; this.problemDescription=problemDescription; this.prodId=prodId; this.createdBy=createdBy; this.assignedTo=assignedTo; this.assignedDate=assignedDate; } //Variable declaration private int svrId; private String status; private Date requestDate; private String problemDescription; private int prodId; private int createdBy; private int assignedTo; private Date assignedDate; //Dependancy Injection for datasource @Resource(name="jdbc/srconnDS") private DataSource srconnDataSource; public void setDataSource(DataSource myDB){ this.srconnDataSource = myDB; } //Getter & setter methods public void setSvrId(int svrId) { this.svrId = svrId; } public int getSvrId() { return svrId; } public void setStatus(String status) { this.status = status; } public String getStatus() { return status; } public void setRequestDate(Date requestDate) {

Page 34: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

34

this.requestDate = requestDate; } public Date getRequestDate() { return requestDate; } public void setProblemDescription(String problemDescription) { this.problemDescription = problemDescription; } public String getProblemDescription() { return problemDescription; } public void setProdId(int prodId) { this.prodId = prodId; } public int getProdId() { return prodId; } public void setCreatedBy(int createdBy) { this.createdBy = createdBy; } public int getCreatedBy() { return createdBy; } public void setAssignedTo(int assignedTo) { this.assignedTo = assignedTo; } public int getAssignedTo() { return assignedTo; } public void setAssignedDate(Date assignedDate) { this.assignedDate = assignedDate; } public Date getAssignedDate() { return assignedDate; } //Connection to Database private Connection connectToDatabase(){ Connection conn=null; int ret_code;

Page 35: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

35

try { conn=srconnDataSource.getConnection(); } catch (SQLException se) { ret_code = se.getErrorCode(); System.out.println("SQL Error while connecting to the database : "+ se.toString()); } catch (Exception ne) { System.out.println("Other Error while connecting to the database : "+ ne.toString()); } return conn; } public void insertServiceRequests(int svrId,String status,Date requestDate,String problemDescription,int prodId,int createdBy,int assignedTo,Date assignedDate){ Connection conn = null; PreparedStatement pstmtInsert=null; //java.sql.Date sqlRequestDate = new java.sql.Date(requestDate.getTime()); //java.sql.Date sqlAssignedDate = new java.sql.Date(assignedDate.getTime()); try { conn = connectToDatabase(); String sqlInsert = "INSERT INTO SERVICE_REQUESTS (SVR_ID, STATUS, REQUEST_DATE, PROBLEM_DESCRIPTION, PROD_ID, CREATED_BY, ASSIGNED_TO, ASSIGNED_DATE) VALUES (?,?,?,?,?,?,?,?)"; pstmtInsert = conn.prepareStatement(sqlInsert); pstmtInsert.setInt(1, svrId); pstmtInsert.setString(2, status); pstmtInsert.setDate(3, requestDate); pstmtInsert.setString(4, problemDescription); pstmtInsert.setInt(5, prodId); pstmtInsert.setInt(6, createdBy); pstmtInsert.setInt(7, assignedTo); pstmtInsert.setDate(8, assignedDate); pstmtInsert.executeUpdate(); } catch (SQLException e) { System.out.println(e.getSQLState()); System.out.println(e.getMessage());

Page 36: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

36

System.out.println(e.getErrorCode()); System.out.println("ERROR: insertServiceRequests()"); } finally{ try{ pstmtInsert.close(); conn.close(); } catch(SQLException e2) { System.out.println(e2); } } } public void updateServiceRequests(int svrId,String status,Date requestDate,String problemDescription,int prodId,int createdBy,int assignedTo,Date assignedDate){ Connection conn = null; PreparedStatement pstmtUpdate=null; //java.sql.Date sqlRequestDate = new java.sql.Date(requestDate.getTime()); //java.sql.Date sqlAssignedDate = new java.sql.Date(assignedDate.getTime()); try { conn = connectToDatabase(); String sqlUpdate = "UPDATE SERVICE_REQUESTS SET STATUS = ?,REQUEST_DATE = ?,PROBLEM_DESCRIPTION = ?,PROD_ID = ?,CREATED_BY = ?,ASSIGNED_TO = ?,ASSIGNED_DATE = ? WHERE SVR_ID = ?"; pstmtUpdate = conn.prepareStatement(sqlUpdate); pstmtUpdate.setString(1, status); pstmtUpdate.setDate(2, requestDate); pstmtUpdate.setString(3, problemDescription); pstmtUpdate.setInt(4, prodId); pstmtUpdate.setInt(5, createdBy); pstmtUpdate.setInt(6, assignedTo); pstmtUpdate.setDate(7, assignedDate); pstmtUpdate.setInt(8, svrId); pstmtUpdate.executeUpdate(); } catch (SQLException e) {

Page 37: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

37

System.out.println(e.getSQLState()); System.out.println(e.getMessage()); System.out.println(e.getErrorCode()); System.out.println("ERROR: updateServiceRequests()"); } finally{ try{ pstmtUpdate.close(); conn.close(); } catch(SQLException e2) { System.out.println(e2); System.out.println("Error dari finally block updatePatient"); } } } public List<ServiceRequestsBean> findServiceRequestsById(int svrId){ List<ServiceRequestsBean> retval = new ArrayList<ServiceRequestsBean>(); Connection connection = null; PreparedStatement pstmtselect=null; ResultSet rs=null; try { connection = connectToDatabase(); String sql = "SELECT * FROM SERVICE_REQUESTS WHERE SVR_ID = ? "; pstmtselect = connection.prepareStatement(sql); pstmtselect.setInt(1, svrId); rs = pstmtselect.executeQuery(); CachedRowSetImpl crset = new CachedRowSetImpl(); crset.populate(rs); while (crset.next()) { ServiceRequestsBean serviceRequestsBean = new ServiceRequestsBean(crset.getInt("SVR_ID"),crset.getString("STATUS"),crset.getDate("REQUEST_DATE"),crset.getString("PROBLEM_DESCRIPTION"),crset.getInt("PROD_ID"),crset.getInt("CREATED_BY"),crset.getInt("ASSIGNED_TO"),crset.getDate("ASSIGNED_DATE")); retval.add(serviceRequestsBean); } }

Page 38: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

38

catch (SQLException e) { e.printStackTrace(); System.out.println(e.getSQLState()); System.out.println(e.getMessage()); System.out.println(e.getErrorCode()); System.out.println("ERROR: findServiceRequestsById()"); } catch (Exception e1) { e1.printStackTrace(); } finally { try{ rs.close(); pstmtselect.close(); connection.close(); } catch(SQLException e2) { System.out.println(e2); } } return retval; } public List<ServiceRequestsBean> findServiceRequestsByStatus(String status){ List<ServiceRequestsBean> retval = new ArrayList<ServiceRequestsBean>(); Connection connection = null; PreparedStatement pstmtselect=null; ResultSet rs=null; try { connection = connectToDatabase(); String sql = "SELECT * FROM SERVICE_REQUESTS WHERE STATUS = ? "; pstmtselect = connection.prepareStatement(sql); pstmtselect.setString(1, status); rs = pstmtselect.executeQuery(); CachedRowSetImpl crset = new CachedRowSetImpl(); crset.populate(rs); while (crset.next()) {

Page 39: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

39

ServiceRequestsBean serviceRequestsBean = new ServiceRequestsBean(crset.getInt("SVR_ID"),crset.getString("STATUS"),crset.getDate("REQUEST_DATE"),crset.getString("PROBLEM_DESCRIPTION"),crset.getInt("PROD_ID"),crset.getInt("CREATED_BY"),crset.getInt("ASSIGNED_TO"),crset.getDate("ASSIGNED_DATE")); retval.add(serviceRequestsBean); } } catch (SQLException e) { e.printStackTrace(); System.out.println(e.getSQLState()); System.out.println(e.getMessage()); System.out.println(e.getErrorCode()); System.out.println("ERROR: findServiceRequestsByStatus()"); } catch (Exception e1) { e1.printStackTrace(); } finally { try{ rs.close(); pstmtselect.close(); connection.close(); } catch(SQLException e2) { System.out.println(e2); } } return retval; } public List<ServiceRequestsBean> findAllServiceRequests(){ List<ServiceRequestsBean> retval = new ArrayList<ServiceRequestsBean>(); Connection connection = null; PreparedStatement pstmtselect=null; ResultSet rs=null; try { connection = connectToDatabase(); String sql = "SELECT * FROM SERVICE_REQUESTS";

Page 40: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

40

pstmtselect = connection.prepareStatement(sql); rs = pstmtselect.executeQuery(); CachedRowSetImpl crset = new CachedRowSetImpl(); crset.populate(rs); while (crset.next()) { ServiceRequestsBean serviceRequestsBean = new ServiceRequestsBean(crset.getInt("SVR_ID"),crset.getString("STATUS"),crset.getDate("REQUEST_DATE"),crset.getString("PROBLEM_DESCRIPTION"),crset.getInt("PROD_ID"),crset.getInt("CREATED_BY"),crset.getInt("ASSIGNED_TO"),crset.getDate("ASSIGNED_DATE")); retval.add(serviceRequestsBean); } } catch (SQLException e) { e.printStackTrace(); System.out.println(e.getSQLState()); System.out.println(e.getMessage()); System.out.println(e.getErrorCode()); System.out.println("ERROR: findAllServiceRequests()"); } catch (Exception e1) { e1.printStackTrace(); } finally { try{ rs.close(); pstmtselect.close(); connection.close(); } catch(SQLException e2) { System.out.println(e2); } } return retval; } public List<ServiceRequestsBean> searchServiceRequests(String status, String problemDescription){

Page 41: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

41

List<ServiceRequestsBean> retval = new ArrayList<ServiceRequestsBean>(); Connection connection = null; PreparedStatement pstmtselect=null; ResultSet rs=null; /* if(status==null){ status="%"; } if(problemDescription==null){ problemDescription="%"; } */ String statusP = "%"+status+"%"; String problemDescriptionP ="%"+problemDescription+"%"; try { connection = connectToDatabase(); String sql = "SELECT * FROM SERVICE_REQUESTS WHERE (STATUS LIKE UPPER(?) OR STATUS LIKE LOWER(?) OR STATUS LIKE INITCAP(?)) AND (PROBLEM_DESCRIPTION LIKE LOWER(?) OR PROBLEM_DESCRIPTION LIKE UPPER(?) OR PROBLEM_DESCRIPTION LIKE INITCAP(?))"; pstmtselect = connection.prepareStatement(sql); pstmtselect.setString(1, statusP); pstmtselect.setString(2, statusP); pstmtselect.setString(3, statusP); pstmtselect.setString(4, problemDescriptionP); pstmtselect.setString(5, problemDescriptionP); pstmtselect.setString(6, problemDescriptionP); rs = pstmtselect.executeQuery(); CachedRowSetImpl crset = new CachedRowSetImpl(); crset.populate(rs); while (crset.next()) { ServiceRequestsBean serviceRequestsBean = new ServiceRequestsBean(crset.getInt("SVR_ID"),crset.getString("STATUS"),crset.getDate("REQUEST_DATE"),crset.getString("PROBLEM_DESCRIPTION"),crset.getInt("PROD_ID"),crset.getInt("CREATED_BY"),crset.getInt("ASSIGNED_TO"),crset.getDate("ASSIGNED_DATE")); retval.add(serviceRequestsBean); } } catch (SQLException e) { e.printStackTrace(); System.out.println(e.getSQLState()); System.out.println(e.getMessage());

Page 42: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

42

System.out.println(e.getErrorCode()); System.out.println("ERROR: searchServiceRequests()"); } catch (Exception e1) { e1.printStackTrace(); } finally { try{ rs.close(); pstmtselect.close(); connection.close(); } catch(SQLException e2) { System.out.println(e2); } } return retval; } public void removeServiceRequests(int svrId){ Connection conn = null; PreparedStatement pstmtUpdate=null; try { conn = connectToDatabase(); String sqlDelete = "DELETE FROM SERVICE_REQUESTS WHERE SVR_ID = ?"; pstmtUpdate = conn.prepareStatement(sqlDelete); pstmtUpdate.setInt(1, svrId); pstmtUpdate.executeUpdate(); } catch (SQLException e) { System.out.println(e.getSQLState()); System.out.println(e.getMessage()); System.out.println(e.getErrorCode()); System.out.println("ERROR: removeServiceRequests()");

Page 43: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

43

} finally{ try{ pstmtUpdate.close(); conn.close(); } catch(SQLException e2) { System.out.println(e2); System.out.println("Error from finally block removeServiceRequests"); } } } public List<ServiceRequestsBean> findServiceRequestsByCreatedBy(int createdBy){ List<ServiceRequestsBean> retval = new ArrayList<ServiceRequestsBean>(); Connection connection = null; PreparedStatement pstmtselect=null; ResultSet rs=null; try { connection = connectToDatabase(); String sql = "SELECT * FROM SERVICE_REQUESTS WHERE CREATED_BY = ? "; pstmtselect = connection.prepareStatement(sql); pstmtselect.setInt(1, createdBy); rs = pstmtselect.executeQuery(); CachedRowSetImpl crset = new CachedRowSetImpl(); crset.populate(rs); while (crset.next()) { ServiceRequestsBean serviceRequestsBean = new ServiceRequestsBean(crset.getInt("SVR_ID"),crset.getString("STATUS"),crset.getDate("REQUEST_DATE"),crset.getString("PROBLEM_DESCRIPTION"),crset.getInt("PROD_ID"),crset.getInt("CREATED_BY"),crset.getInt("ASSIGNED_TO"),crset.getDate("ASSIGNED_DATE")); retval.add(serviceRequestsBean); } } catch (SQLException e) {

Page 44: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

44

e.printStackTrace(); System.out.println(e.getSQLState()); System.out.println(e.getMessage()); System.out.println(e.getErrorCode()); System.out.println("ERROR: findServiceRequestsByCreatedBy()"); } catch (Exception e1) { e1.printStackTrace(); } finally { try{ rs.close(); pstmtselect.close(); connection.close(); } catch(SQLException e2) { System.out.println(e2); } } return retval; }

4) Enter the following source code for UsersBean.java and import all necessary libraries.

i. Libraries import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import javax.ejb.Stateless; import javax.sql.DataSource;

ii. Source code private int userId; private String userRole; private String email;

Page 45: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

45

private String firstName; private String lastName; private String streetAddress; private String city; private String stateProvince; private String postalCode; private String countryId; public UsersBean(int userId, String userRole, String email, String firstName, String lastName, String streetAddress, String city, String stateProvince, String postalCode, String countryId) { this.userId=userId; this.userRole=userRole; this.email=email; this.firstName=firstName; this.lastName=lastName; this.streetAddress=streetAddress; this.city=city; this.stateProvince=stateProvince; this.postalCode=postalCode; this.countryId=countryId; } //Dependancy Injection for datasource @Resource(name="jdbc/srconnDS") private DataSource srconnDataSource; public void setDataSource(DataSource myDB){ this.srconnDataSource = myDB; } public void setUserId(int userId) { this.userId = userId; } public int getUserId() { return userId; } public void setUserRole(String userRole) { this.userRole = userRole; } public String getUserRole() { return userRole; } public void setEmail(String email) { this.email = email; }

Page 46: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

46

public String getEmail() { return email; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getFirstName() { return firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getLastName() { return lastName; } public void setStreetAddress(String streetAddress) { this.streetAddress = streetAddress; } public String getStreetAddress() { return streetAddress; } public void setCity(String city) { this.city = city; } public String getCity() { return city; } public void setStateProvince(String stateProvince) { this.stateProvince = stateProvince; } public String getStateProvince() { return stateProvince; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } public String getPostalCode() { return postalCode; }

Page 47: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

47

public void setCountryId(String countryId) { this.countryId = countryId; } public String getCountryId() { return countryId; } private Connection connectToDatabase(){ Connection conn=null; int ret_code; try { conn=srconnDataSource.getConnection(); } catch (SQLException se) { ret_code = se.getErrorCode(); System.out.println("SQL Error while connecting to the database : "+ se.toString()); } catch (Exception ne) { System.out.println("Other Error while connecting to the database : "+ ne.toString()); } return conn; } public void insertUsers(int userId, String userRole, String email, String firstName, String lastName, String streetAddress, String city, String stateProvince, String postalCode, String countryId){ Connection conn = null; PreparedStatement pstmtInsert=null; try { conn = connectToDatabase(); String sqlInsert = "INSERT INTO USERS (USER_ID, USER_ROLE, EMAIL, FIRST_NAME, LAST_NAME, STREET_ADDRESS, CITY, STATE_PROVINCE, POSTAL_CODE, COUNTRY_ID) VALUES (?,?,?,?,?,?,?,?,?,?)"; pstmtInsert = conn.prepareStatement(sqlInsert); pstmtInsert.setInt(1, userId); pstmtInsert.setString(2, userRole);

Page 48: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

48

pstmtInsert.setString(3, email); pstmtInsert.setString(4, firstName); pstmtInsert.setString(5, lastName); pstmtInsert.setString(6, streetAddress); pstmtInsert.setString(7, city); pstmtInsert.setString(8, stateProvince); pstmtInsert.setString(9, postalCode); pstmtInsert.setString(10, countryId); pstmtInsert.executeUpdate(); } catch (SQLException e) { System.out.println(e.getSQLState()); System.out.println(e.getMessage()); System.out.println(e.getErrorCode()); System.out.println("ERROR: insertUsers()"); } finally{ try{ pstmtInsert.close(); conn.close(); } catch(SQLException e2) { System.out.println(e2); } } } public void updateUsers(int userId, String userRole, String email, String firstName, String lastName, String streetAddress, String city, String stateProvince, String postalCode, String countryId){ Connection conn = null; PreparedStatement pstmtUpdate=null; try { conn = connectToDatabase(); String sqlUpdate = "UPDATE USERS SET USER_ROLE = ?,EMAIL = ?,FIRST_NAME = ?,LAST_NAME = ?,STREET_ADDRESS = ?,CITY = ?,STATE_PROVINCE = ? POSTAL_CODE = ?,COUNTRY_ID=? WHERE USER_ID = ?"; pstmtUpdate = conn.prepareStatement(sqlUpdate); pstmtUpdate.setString(1, userRole);

Page 49: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

49

pstmtUpdate.setString(2, email); pstmtUpdate.setString(3, firstName); pstmtUpdate.setString(4, lastName); pstmtUpdate.setString(5, streetAddress); pstmtUpdate.setString(6, city); pstmtUpdate.setString(7, stateProvince); pstmtUpdate.setString(8, postalCode); pstmtUpdate.setString(9, countryId); pstmtUpdate.setInt(10, userId); pstmtUpdate.executeUpdate(); } catch (SQLException e) { System.out.println(e.getSQLState()); System.out.println(e.getMessage()); System.out.println(e.getErrorCode()); System.out.println("ERROR: updateUsers()"); } finally{ try{ pstmtUpdate.close(); conn.close(); } catch(SQLException e2) { System.out.println(e2); System.out.println("Error from finally block updateUsers"); } } } public List<UsersBean> findAllUsers(){ List<UsersBean> retval = new ArrayList<UsersBean>(); Connection connection = null; PreparedStatement pstmtselect=null; ResultSet rs=null; try { connection = connectToDatabase(); String sql = "SELECT * FROM USERS"; pstmtselect = connection.prepareStatement(sql); rs = pstmtselect.executeQuery();

Page 50: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

50

CachedRowSetImpl crset = new CachedRowSetImpl(); crset.populate(rs); while (crset.next()) { UsersBean usersBean = new UsersBean(crset.getInt("USER_ID"),crset.getString("USER_ROLE"),crset.getString("EMAIL"),crset.getString("FIRST_NAME"),crset.getString("LAST_NAME"),crset.getString("STREET_ADDRESS"),crset.getString("CITY"),crset.getString("STATE_PROVINCE"), crset.getString("POSTAL_CODE"), crset.getString("COUNTRY_ID")); retval.add(usersBean); } } catch (SQLException e) { e.printStackTrace(); System.out.println(e.getSQLState()); System.out.println(e.getMessage()); System.out.println(e.getErrorCode()); System.out.println("ERROR: findAllUsers()"); } catch (Exception e1) { e1.printStackTrace(); } finally { try{ rs.close(); pstmtselect.close(); connection.close(); } catch(SQLException e2) { System.out.println(e2); } } return retval; } public void removeUser(int userId){ Connection conn = null; PreparedStatement pstmtUpdate=null; try {

Page 51: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

51

conn = connectToDatabase(); String sqlDelete = "DELETE FROM USERS WHERE USER_ID = ?"; pstmtUpdate = conn.prepareStatement(sqlDelete); pstmtUpdate.setInt(1, userId); pstmtUpdate.executeUpdate(); } catch (SQLException e) { System.out.println(e.getSQLState()); System.out.println(e.getMessage()); System.out.println(e.getErrorCode()); System.out.println("ERROR: removeUsers()"); } finally{ try{ pstmtUpdate.close(); conn.close(); } catch(SQLException e2) { System.out.println(e2); System.out.println("Error from finally block removeUsers"); } } } public List<UsersBean> findUsersByUserId(int userId){ List<UsersBean> retval = new ArrayList<UsersBean>(); Connection connection = null; PreparedStatement pstmtselect=null; ResultSet rs=null; try { connection = connectToDatabase(); String sql = "SELECT * FROM USERS WHERE USER_ID=?"; pstmtselect = connection.prepareStatement(sql); pstmtselect.setInt(1, userId); rs = pstmtselect.executeQuery();

Page 52: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

52

CachedRowSetImpl crset = new CachedRowSetImpl(); crset.populate(rs); while (crset.next()) { UsersBean usersBean = new UsersBean(crset.getInt("USER_ID"),crset.getString("USER_ROLE"),crset.getString("EMAIL"),crset.getString("FIRST_NAME"),crset.getString("LAST_NAME"),crset.getString("STREET_ADDRESS"),crset.getString("CITY"),crset.getString("STATE_PROVINCE"), crset.getString("POSTAL_CODE"), crset.getString("COUNTRY_ID")); retval.add(usersBean); } } catch (SQLException e) { e.printStackTrace(); System.out.println(e.getSQLState()); System.out.println(e.getMessage()); System.out.println(e.getErrorCode()); System.out.println("ERROR: findAllUsers()"); } catch (Exception e1) { e1.printStackTrace(); } finally { try{ rs.close(); pstmtselect.close(); connection.close(); } catch(SQLException e2) { System.out.println(e2); } } return retval; } 5) Exposed all methods through Local & Remote interface for both ServiceRequestsBean.java and UsersBean.java, using steps mentioned previously. 6) Compile both ServiceRequestsBean.java and UsersBean.java.

Page 53: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

53

Practice 4 In this practice, you create a data control based on the Session EJB. You then create a simple ADF Faces Rich Client page and use the data control to bind data to the page. Practice 4-1: Create and Use a Data Control In this section, you create a data control based on an existing EJB model. You then create a simple master-detail page that consumes the data control. The page is based on Users as the master and displays all the ServiceRequests that belong to the user as the detail. 1) Create a data control based on the ServiceRequestsBean.java and UsersBean.java in the DataModel project.

i. Right-click ServiceRequestsBean.java in the DataModel project and select Create Data Control.

ii. Select Local for the EJB interface type. iii. Click OK. iv. Notice the files that are created in the DataModel project.

v. Save All your work. vi. Do the same for UsersBean.java vii. This is what you will see.

Page 54: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

54

2) Open the JSF Navigation diagram in the UserInterface project by double-click faces-config.xml, inside folder Page flows. 3) Add a JSF Page reference to the diagram and name it usersServiceRequests.jspx.

i. Click JSF Page on the Component Palette and click anywhere on the diagram. ii. Enter the name usersServiceRequests.jspx.

4) Create the JSF.

i. Double-click the JSF reference on the JSF Navigation diagram. ii. Name it usersServiceRequests. iii. Make it a JSP Document (*.jspx) iv. Include an automatic backing bean.

5) Add an ADF Read-only Form based on the Users collection.

i. Open the Visual Editor for the usersServiceRequests.jspx. ii. From the Data Control Palette, drag UsersLocal >findAllUsers >UsersBean to the

usersServiceRequests.jspx (in design view). iii. Select Forms >ADF Read-only Form from the pop-up menu. iv. In the Edit Form Fields dialog box, select Include Navigation Controls and click OK. v. Save your work.

6) Run the page to see the User data. Right-click anywhere in the Visual Editor and click Run. 7) Your page should look something like:

Page 55: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

55

8) Add a data control for the detail portion of the page.

i. In the Data Control Palette, drag ServiceRequestsLocal > findServiceRequestsByCreatedBy > ServiceRequestsBean to the bottom of the form on your page.

ii. Select Tables> ADF Read-only Table, then OK. iii. In the Action Binding Editor, click pulldown button, button inside Value column and click Show EI

Expression Builder…

iv. In the Variable dialog box, expand ADF Bindings > Bindings, select userId and click button ‘Insert Into Expression’ to move it to the expression column, then OK and OK (Action Binding Editor).

9) Run the page. You have to scroll through some Users to find one with Requests. 10) Your page should look something like:

Page 56: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

56

Page 57: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

57

Practice 5 In this practice, you use various ADF Faces Layout components to create a template that you use in all the other pages you create.

Practice 5-1: Create a Template jspx In this section, you create a template.jspx page and add layout components that help make all your pages look the same. Start this practice with your application from the previous practice. 1) In Windows Explorer (or the equivalent if you are using another operating system), navigate to the MiscFiles directory, which is in the same directory as the practice workspaces. 2) Copy the images subdirectory and paste it in EJB-JSF > ViewController > public_html. 3) The directory structure should look like:

4) Click the refresh button on the Applications Navigator to see the properties file. It will be under a Resources node. 5) Right-click on UserInterface project > New…, in New Gallery dialog box, Web Tier > JSF and select JSF Page Template, then OK. 6) Create the page with the following attributes:

File Name: template.jspx Page Template Name: template For Facet Definitions tab, Add 4 entry: Name Descriptions Header for logo etc Left for link/menu button Main for tab Footer for copyright etc

Page 58: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

58

Click OK.

9) Add an ADF Faces > Layout > Panel Splitter component to the page. i. Click the ADF Faces > Layout page in the Component Palette.

ii. Click, drag & drop Panel Splitter . 10) In the Panel Splitter - Property Inspector, enter:

Common > Orientation: vertical Common > Splitter position: 320 Style > Box > Width: 100 percent Style > Box > Hight: 100 percent

Page 59: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

59

11) Add second Panel Splitter and drop inside first facet. In the Panel Splitter - Property Inspector, enter:

Common > Orientation: vertical Common > Splitter position: 70 Style > Box > Width: 100 percent Style > Box > Width: 100 percent

Page 60: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

60

12) Add third Panel Splitter and drop inside second (middle) facet. In the Property Inspector, enter:

Style > Box > Width: 100 percent Style > Box > Height: 100 percent

Page 61: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

61

13) Click, drag & drop Facet Ref from ADF Faces > Common Components to header facet (top most panel). Inside Insert Facet Ref dialog box, choose Header for Facet Name. Do the same for the other 3 panel/facet and choose Left, Main and Footer for Facet Name.

Page 62: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

62

14) Add image from ADF Faces > Common Components to header facet. For Source, choose file /images/banner3.jpg from image folder.

15) Add Output Text from ADF Faces > Common Components to footer. In Property Inspector, add: Common > Value: Copyright PPUKM, 2008 (Pusat Teknologi Maklumat, PPUKM), all right reserved.

Style > Text > Color: Blue Style > Text > Size: Small Style > Text > Bold: Bold

16) Drag & drop Panel Group Layout from ADF Faces > Layout, to Left facet. Set Common >Layout to vertical in the Property Inspector.

17) Drag & drop Spacer from ADF Faces > Layout to Panel Group Layout. Set Common > Height to 4, in the Property Inspector.

18) Drag & drop Toolbar Button from ADF Faces > Layout beneath Spacer. Repeat steps 17 & 18 two times.

19) Change Common > Text for each button, in the Property Inspector to Laboratory Order,

Radiology Order and Diet Order respectively.

20) Save All .

Page 63: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

63

Page 64: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

64

Practice 5-2: Create the SREdit Page and Apply the Template In this section, you create the SREdit page and apply the template you just created. 1) Open the JSF Navigation diagram (faces-config.xml). 2) Create the SREdit.jspx with the following attributes: i. Double-click /SREdit.jsp on the JSF Navigation diagram. ii. Use Page Template: template iii. Select Create as XML Document (*.jspx). iv. Select Automatically Expose UI Components in a New Managed Bean. v. Click OK to create the page.

3) Drag & drop Panel Tabbed from ADF Faces > Layout to Main facet/panel. 4) Select af:panelTabbed inside SREdit.jspx – structure pane. In the Property Inspector, change

Style>Box>Width: to 100, so as Height: to 100. 5) Right Click at ShowDetailItem 1 > Insert after Show Detail Item – ShowDetailItem 1 >

ShowDetailItem. This will add new tab (ShowDetailItem 2). From the Property Inspector, change Common > Text from ShowDetailItem 2 to View All. Do the same to ShowDetailItem 1 to Edit.

6) Save All . The page should look something like this:

Page 65: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

65

Practice 5-3: Add Data-Aware Components to the SREdit Page In this section, you add an ADF Form component that will display a service request. 1) Inside the Data Control palette and expand ServiceRequestsLocal. Scroll down to select findServiceRequestById(int) > ServiceRequestsBean and drag it to the Edit tab, inside the Main panel/facet. 2) In the pop-up menu, select Forms > ADF Form. 3) In the Edit Form Fields dialog box, reorder the columns as follows: svrId, requestDate, status, assignedDate, and problemDescription. Do not close the dialog box yet. 4) Still in the dialog box, click the Component to Use field to the right of svrId, and from the drop-down list, select ADF Output Text w/Label. Do the same for the requestDate field. Click OK. 5) In the Action Binding Editor dialog box, set the value for svrId to 100. This is temporary so that it queries a row when you test the page. Click OK. 6) Select the problemDescription field and, in the Property Inspector, set the Appearance > Rows property to 4 to make this a multiline item so that a user has space to provide a textual description of the appliance problem. 7) Change the Appearance > Columns property to 40. 8) In the Structure pane, expand /template.jspx facets > Main > af:panelTabbed>af:showDetailItem

– Edit>Panel Form Layout facets > footer. Select Panel Group Layout , in the ADF Faces > Layout palette, and drag it to the footer facet of the Panel Form Layout facets.

Page 66: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

66

In the Property Inspector, change Common > Layout to horizontal.

Select Spacer from ADF Faces > Layout palette, and drag it to Panel Group Layout. Change the Common > Width to 40 in Property Inspector.

Select Button in the ADF Faces> Common Component palette, and drag it to the Panel

Group Layout. Select another Spacer from ADF Faces > Layout palette, and drag it to Panel Group Layout. Change the Common > Width to 40 in Property Inspector. 9) Add second Button to Panel Group Layout. In the Property Inspector, set their properties to the values in the following:

ID Text cancelButton Cancel commitButton Save

10) The Structure pane should look like:

11) The design view should look like this:

Page 67: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

67

12) Right-click anywhere on the page and select Run. The page should run and display Service Request 100 and look something like:

Page 68: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

68

Practice 6 In this practice, you add a form to the SRSearch page. The form is based on a method in EJB.

Practice 6-1: Add Data Components to the Search Page In this section, you create the SRSearch page and add a Parameter Form that uses the searchServiceRequests method to the Search page. 1) Open the JSF Navigation diagram. 2) Create the SRSearch.jspx with the following attributes:

i. Double-click /SRSearch.jsp on the JSF Navigation diagram. ii. Use Page Template: Template. iii. Select Create as XML Document (*.jspx). iv. Select Automatically Expose UI Components in a New Managed Bean. v. Click OK to create the page.

3) Add Panel Tabbed , as what you have done in step 5-2, 3-5. But the first tab you define as Search and second tab you defined as View All.

Next, add a parameterized form to the page. 4) On the Data Control Palette, expand the ServiceRequestsLocal Data control, and locate searchServiceRequests(String, String).

Page 69: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

69

5) Add the searchServiceRequests as a Parameter Form. i. Select searchServiceRequests(String, String) and drag it to Search tab. ii. Select Parameters | ADF Parameter Form from the pop-up menu. iii. Click OK in the Edit Form Fields dialog box to accept the defaults. iv. Click OK in the Edit Action Binding dialog box. These actions add a form with two fields and a

Search button. 6) Change the Label property (Common > Label) of the description af:inputText component to Problem Description:. You can either enter the value or use the Binding Editor. 7) Change the Label property (Common > Label) of the status af:inputText component to Status:. 8) Change the Text property (Common > Text) of the Search button to Search.

Now that you have a form that executes the query, you need to add a component to display the results. 9) In the Data Control Palette, expand searchServiceRequests(String, String) and drag the subnode ServiceRequestsBean below the form in the Search tab. 10) In the pop-up menu, select Tables > ADF Read-only Table . This table displays the search results. You see the Edit Table Columns window, where you can change the display label, the binding value, and the type of component used to display it. The default values originate from those defined in the data model.

11) Using the Top, Up, Down, and Bottom buttons, reorder the columns of the table to the following: srvId , problemDescription, status, requestDate, and assignedDate. Delete the last 3 column (prodId, createdBy and assignedTo).

Page 70: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

70

11) Select the Row selection check box and accept the defaults. Click OK to continue. 12) With the af:table selected in the Structure window, change the Id (Common > Id) property to srtable. Set size of the af:table by setting this parameter: Style > Box >Width: 100 percent 13) Click View All tab to activate it.

14) Drag & drop Output Label from ADF Faces > Common Components to the View All tab. In the Property Inspector, change Common>Value to Service Request, Style > Text > Color: Navy, Style > Text>Size: medium & Style > Text > Bold: bold.

15) Drag & drop Separator , below Output Label, just now.

16) In the Data Control Palette, expand findAllServiceRequests() and drag the subnode ServiceRequestsBean to the View All tab.

17) In the pop-up menu, select Tables > ADF Read-only Table. In the Edit Table Columns, select the

Sorting check box and accept the defaults. Click OK to continue.

Page 71: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

71

18) With the af:table selected in the Structure window, set size of the af:table by setting this parameter:Style > Box >Width: 100 percent

19) Save All .

Page 72: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

72

Practice 6-2: Modify the Default Behavior The default behavior of the parameter form is to simply accept the values the user enters and execute the query. This means the user must put a value or a wildcard in each of the fields for the query to return results. That is probably fine if it is a two-field form, but more than that would present usability issues to users.

In this section, you add Expression Language (EL) to the page-definition parameters that insert a wildcard if the user does not enter a value in the field. You add this code to each of the parameters so that the user can enter either or both parameters. 1) Select the page definition for the SRSearch page in the Applications Navigator. You could also right-click anywhere on the SRSearch page and select Go to Page Definition and go to Source view. 2) In the Structure window, expand bindings > searchServiceRequests . 3) Click the problemDescription and see the Property Inspector. 4) For the NDValue in the NamedData Properties dialog box, click the arrow button then edit…. The expression is what populates the parameter before it is passed to the query for execution. By default, the parameter is populated from the related field on the parameter form. The code you are about to add checks for a value and returns a wildcard (“%”) if the parameter is either null or blank. 5) Replace the default expression for problemDescription with the following code: ${((bindings.searchServiceRequests_problemDescription== null) || (bindings.searchServiceRequests_problemDescription== '')) ? '%' : bindings.searchServiceRequests_problemDescription}

Page 73: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

73

The preceding code tests problemDescriptionfor null and for blank (''). If either is true, the expression returns a wildcard ('%'). If problemDescription is not null, the expression returns the value that the user entered. 6) Click OK to accept the changes and to close the dialog box. 7) Click the status property. 8) For the NDValue in the NamedData Properties dialog box, click the arrow button then edit…. 9) Replace the default expression for status with the following code: ${((bindings.searchServiceRequests_status== null) || (bindings.searchServiceRequests_status== '')) ? '%' : bindings.searchServiceRequests_status}

Page 74: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

74

Click OK to accept the changes and to close the dialog box 10) Run the page. Right-click SRSearch.jspx in the Applications Navigator and select Run, or right-click anywhere in the SRSearch.jspx Visual Editor and select Run. 11) Click the Search button without entering values in either of the fields. The result should show all the service requests. 12) Enter open in the status field and click Search. The result should be all the open service requests. 13) Enter a value in the description field (for example, “wash”), and then click Search. You should now see the rows with “wash” somewhere in the description with a status of open. 14) Clear the status field and click Search. You should now see all the rows with “wash” somewhere in the description.

Page 75: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

75

When you first ran the page, the query was executed when the page was loaded. Because you added the code to substitute wildcards for null values, the initial query returns and displays all rows. In the final few steps, you add a refresh condition that keeps the form from executing the query until the user clicks the Search button. 15) Select the page definition for the SRSearch page in the Applications Navigator. 16) In the Structure pane, expand executables. 17) Click searchServiceRequestsIterator. 18) In the Properties Inspector, change the Advanced > RefreshCondition to ${adfFacesContext.postback}. This prevents the Iterator from executing unless the request is a postback. 19) Go back to SRSearch.jspx, select af:table – srtable on the Structure pane, in the Property Inspector, set value for Behaviour > ContentDelivery to immediate. 19) Run the page. Right-click SRSearch.jspx in the Applications Navigator and select Run, or right-click anywhere in the SRSearch.jspx Visual Editor and select Run.

Page 76: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

76

20) Notice that the detail table does not display any rows until you click Search.

Page 77: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

77

Practice 7 In this practice, you complete the Edit page by adding some lookup fields and adding the commit functionality.

Practice 7-1: Complete the Edit Page

In this section, you complete the SREdit page. You add some lookup fields that make the page more user-friendly. You also add a button that will commit any changes you make to the displayed row.

In the next few steps, you add a couple of lookup fields that shows the user that created the requests and the technician that is assigned to the request. The and attributes of the ServiceRequest object are actually createdBy, assignedTo child-object accessors. In the following steps, you bind the relevant name attributes from these child objects into the page. Start this practice with your application from the previous practice. 1) Open the SREdit.jspx page in the Visual Editor.

2) Click Edit tab to activate it. Drag & drop Output Label from ADF Faces > Common Components beneath af:showDetailItem – Edit. In the Property Inspector, change Common>Value to Search Service Request, Style > Text > Color: Navy, Style >Text> Size: medium & Style > Text > Bold: bold.

3) Drag & drop Separator , below Output Label, just now.

4) The first component you add contains the first and last names of the user who created the service

request. Select PanelLabelAndMessage in the ADF Faces > Common Component palette, and in the Visual Editor, drag it to the page beneath the svrId field.

5) The second component contains the first and last names of the technician to whom the service

request is assigned. Drag and drop a second PanelLabelAndMessage component beneath the requestDate field.

Page 78: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

78

6) Drop a Panel Group Layout inside each af:panelLabelAndMessage component. This ensures that the firstName and lastName attributes appear side by side instead of vertically. Set Common > Layout to horizontal, inside Property Inspector.

In the next few steps, you add and bind data components for the first and last name of the created by and assigned to users to the user interface. 7) In the Data Control Palette, expand the UsersLocal >findUsersByUserId(Int) > UsersBean node, and select the firstName attribute.

i. Drag it to the first panelGroupLayout, and drop it as Texts > ADF Output Text. ii. Action Binding Editor dialog box will appear, click […] button inside Value field, iii. Inside Variables dialog box, expand ADF Bindings > bindings and select assignedTo,

click button ‘>’ to move it to column Expression and click OK and iv. Click OK in Action Binding Editor dialog box

Page 79: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

79

8) Select a Spacer from the ADF Faces > Layout palette. Drag it to the Panel Group Layout separator facet of the Structure window (expand the Panel Group Layout facets node if necessary). Set its Width property to 4. 9) Repeat the step 7 with the lastName attribute, placing it in the af: panelGroupLayout component.

10) In the Data Control Palette, expand the UsersLocal >findUsersByUserId(Int) > UsersBean node, and select the firstName attribute. Drag it into the second af: panelGroupLayout, and drop it as Texts > ADF Output Text.

11) Add a Spacer to the separator facet of this Panel Group Layout as you did earlier. Again, set its width to 4. 12) Repeat step 10 above with the lastName attribute, placing it in the af: panelGroupLayout

component.

Next, change the labels of the panelLabelAndMessage components. 13) Select the first panelLabelAndMessage component and change the Label property to Created By:. 14) Select the second panelLabelAndMessage component and change the Label property to Assigned To:. 15) Save the page. At this point, the page should look something like the following:

Page 80: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

80

16) Run the page to see the results. The page should look something like:

Page 81: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

81

The status field should offer the user a drop-down list of the different statuses available. The last few steps in this section change the status field from a plain text field to a drop-down list. 17) Delete both the label and input text for the existing status field from the page. 18) In the Data Control Palette, expand ServiceRequestLocal > findServiceRequestById > ServiceRequestsBean, and select the status attribute. Drag it to its old position in the page, and drop it as Single Selections > ADF Select One Choice. The selectOneChoice component creates a menu-style component that enables the user to select a single value from a list of items. 19) In the List Binding Editor, select the Fixed List option. Set the Base Data Source Attribute to status. 20) In the Set of Values box, enter the following values, each on a new line:

Open Pending Closed

Page 82: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

82

These values are displayed at run time. 21) Set the “No Selection” Item field to Selection Required. Click OK.

Page 83: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

83

22) In the Property Inspector, for the new af:selectOneChoice, set the ID property of the new list component to statusSelection, and save the page. 23) Change the Label property to Status:.

24) Run the page to see the results. The page should look something like the following:

Page 84: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

84

Page 85: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

85

Practice 7-2: Add the Commit Function The buttons you added are just buttons that are not linked to any action or method. In this section, you bind the Save button to the action you want to perform when the user clicks Save. When the user clicks the Save button, you need to save the changes to the database. 1) In the Data Control Palette, expand ServiceRequestLocal and locate the updateServiceRequest(int, String, Date, String, int, int, int, Date) method. Drag it to the Visual Editor and drop it on the Save button that you have created earlier. 2) In the Action Binding Editor, click in the Value field, and then click the […] that appear. In the Variables dialog box, expand the ADF Bindings node and then the bindings node. Enter Value column according to table below. Click OK. Name Value svrId ${binding.svrId} status ${binding.status.selectedValue} requestDate ${binding. requestDate } problemDescription ${binding. problemDescription } prodId ${binding. prodId} createdBy ${binding. createdBy} assignedTo ${binding. assignedTo} assignedDate ${binding. assignedDate} For Confirm Component Rebinding, check the first row, then OK.

Page 86: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

86

3) Save the page. 4) Run the page and change the status value from Closed to Open. 5) Click Save. 6) In JDeveloper, click the Connections tab. 7) Expand Database > srconn > SRDEMO table. 8) Double-click SERVICE_REQUESTS to open the database table viewer. 9) Click the Data tab to see that the first row (SVR_ID 100) has a status of Open.

Page 87: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

87

Practice 8

In this practice, you wire-up the SRSearch page to the SREdit page. When users query rows on the Search page, they can click the Edit button, which directs them to the Edit page. In addition to directing them to the Edit page, the Edit button also stores the current serviceRequestId in a managed bean. The Edit page retrieves the row using the stored serviceRequestId. You also add a delete function and page to the application. Practice 8-1: Link SRSearch to SREdit In this section, you edit the SRSearch page to add functionality to the Edit button. You need to add code to the backing bean that retrieves the ServiceRequests ID from the currently selected row and stores it in the UserState managed bean. You also add a return statement that specifies which JSF Navigation Case to use. Start this practice with your application from the previous practice. 1) Open SRSearch.jspx in the Visual Editor. 2) In the structure window, find af:table – srtable. 3) Right-click af:table – srtable > Insert After af:table – srtable > Panel Group Layout

. Set Common > Layout to horizontal. 4) Right-click Panel Group Layout > Insert Inside af: PanelGroupLayout - horizontal > Button. Repeat the previous step to add a second Button. 5) Select the first Button either in the Visual Editor or the Structure window. 6) In the Properties Inspector, change the ID to editButton. 7) Change the Text property to Edit. 8) Select the second Button either in the Visual Editor or the Structure window. 9) In the Properties Inspector, change the ID to deleteButton. 10) Change the Text property to Delete.

Page 88: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

88

Next, you add code to the Edit button that will store the current serviceRequestId in the userState managed bean and return the navigation case. 11) In the Visual Editor, double-click the Edit button to invoke the backing bean. 12) In the Bind Action Property dialog box, click OK to add the editButton_action method to the backing bean. 13) In the backing bean file, replace the generated code in the editButtonAction method with the following code to specify its navigation path. Note: You can use the Structure window to find the editButton_action()method.

setCurrentSvrIdFromRow(); return "edit";

14) The setCurrentSvrIdFromRow method does not yet exist. Click the CodeAssist icon (the light bulb in the left margin) to create it. 15) Implement the setCurrentSvrIdFromRow method by adding the following code:

RichTable table = getSrtable(); Iterator selection = table.getSelectedRowKeys().iterator(); FacesCtrlHierNodeBinding obj = (FacesCtrlHierNodeBinding)table.getSelectedRowData(); DCIteratorBinding rowiter = obj.getDCIteratorBinding();

Object oldKey = table.getRowKey(); Row row=null; Integer svrId =null; while (selection.hasNext()) {

List rowKey = (List)selection.next(); row = rowiter.findRowByKeyString(((Key)rowKey.get(0)).toStringFormat(true)); svrId = (Integer)row.getAttribute("svrId"); System.out.println(svrId); table.setRowKey(rowKey);

Page 89: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

89

}

UserSystemState.storeCurrentSvrID(svrId);

16) Accept the default import statements. Next, you need to add an action that will refresh the table when the user returns from the Edit page. 17) Open the Page Definition for the SRSearch page. 18) In the Structure window, right-click the executables node, and choose Insert inside executables > invokeAction. 19) In the Insert invokeAction dialog box, enter tableRefresh as the id, and in the Binds field, choose searchServiceRequests from the drop-down list. Click Finish. 20) In the Property Inspector, set the Refresh property is to IfNeeded. This controls whether a refresh should take place. 21) In the RefreshCondition property, enter ${!adfFacesContext.postback}. 22) Save the page definition file. 23) Run the page. Right-click SRSearch.jspx in the Applications Navigator and select Run, or right-click anywhere in the SRSearch.jspx Visual Editor and select Run. 24) Enter values for the query, or just click Search. 25) If you click Edit, you will navigate to the Edit page but because you have not changed the default value in the Edit page query, it will return row 100. Next, you need change the SREdit page to retrieve the svrId from the userState managed bean. The calling page (SRSearch) sets the svrId value in the userState bean from the currently selected row. The SREdit page executes a query using the value of that bean property. Earlier, you set it to 100 just for temporary testing. Now you set it to the bean property value.

27) Open the SREdit page definition. 28) Expand bindings > findServiceRequestById. 29) Select svrId and change the NDValue to ${userState.currentSvrId}. You can either enter the value in the Properties Inspector, or use the EL editor. 30) Run the page and test that when you select a row and click Edit, the Edit page displays that row.

When a user clicks the Cancel button on the Edit page, you discard the changes by not “saving” them. You then need to take the user back to the Search page. 31) Open SREdit Page Definition. 32) In the Structure window, right-click the executables node, and choose Insert inside executables >

Page 90: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

90

invokeAction. 33) In the Insert invokeAction dialog box, enter explicitRefresh as the id, and in the Binds field, choose findServiceRequestById from the drop-down list. Click Finish. 34) Inside Property Inspector, set the Refresh property is set to IfNeeded. This controls whether a refresh should take place. 35) In the RefreshCondition property, enter ${!adfFacesContext.postback}. 36) Save the page definition file. Set an actionListener to fire when the user clicks the Cancel button, and trigger the refresh. 38) On the SREdit page, right-click the Cancel button and, from the shortcut menu, choose Insert inside Button - Cancel > ADF Faces… > Set Action Listener, click OK. In the Insert Set Action Listener dialog box, enter #{true} in the From* field and #{userState.refresh} in the To* field. When fired, this listener populates the user state refresh property with the value of #{true}. Click Finish. 39) In the Property Inspector, for the Cancel button, set the Action property to success. Now repeat the same process for the Save button. 40) In the Property Inspector, for the Save button, set the Action property to success. 41) As in the previous section, set an actionListener to fire when the user clicks the Save button and trigger a refresh. 42) Right-click the Save button and, from the shortcut menu, choose Insert inside Button - Save > ADF Faces… > SetActionListener . 43) In the Insert SetActionListener dialog box, enter #{true} in the From* field and #{userState.refresh} in the To* field. Click Finish. 44) You can now test the page. Right-click anywhere on the SRSearch page and select Run. 45) Enter values for the query, or just click Search. 46) Select any row and click Edit. 47) Change a value and click Save. Notice that you are directed back to the SRSeach page and that your changes are shown. 48) Repeat the testing in any combination you choose.

Page 91: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

91

Practice 8-2: Add a Delete Page In this section, you create the SRDelete page and apply the template. 1) Open the JSF Navigation diagram. 2) Create the SRDelete.jspx with the following attributes:

i. Double-click /SRDelete.jsp on the JSF Navigation diagram. ii. Use Page Template: template. iii. Select Create as XML Document (*.jspx). iv. Select Automatically Expose UI Components in a New Managed Bean. v. Click OK to create the page.

3) Now add the data to the page. Select the Data Control Palette and expand ServiceRequestsLocal. Scroll down to select findServiceRequestById(Int) > ServiceRequestsBean and drag it to the Main facet/panel. 4) In the pop-up menu, select Forms > ADF Read-only Form. 5) Accept the defaults in the Edit Form Fields dialog box and click OK. 6) In the Edit Action Binding dialog box, set the value for svrId to ${userState.currentSvrId}. You can either enter the value directly or use the Binding Editor. Click OK.

7) In the Structure pane, find af:panelFormLayout. Select Panel Group Layout in the ADF Faces > Layout palette, and drag it to the af:panelFormLayout. 8) Drag two Buttons from the ADF Faces > Common Components palette to the af:panelGroupLayout. 9) Change the Text properties of the first button to Cancel, and the second button to Delete. 10) The page should look something like:

Page 92: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

92

Practice 8-3: Wire the Buttons In this section, you bind the Delete button to the removeServiceRequests(int) method to complete the delete. You also specify the navigation case for the Cancel button. In the last few steps of this section, you edit the Delete button on the Search page to have it store the current service request ID so the Delete page can query the current row. 1) In the Data Control Palette, inside ServiceRequestLocal, locate the removeServiceRequests(int) method. Drag it to the Visual Editor and drop it on the Delete button. 2) In the Edit Action Binding, in the Value field, enter ${userState.currentSvrId}. Click OK, and then click OK again.

In the Confirm Component Rebinding, check the first row, OK. 3) Select the Delete button and change the Action property to return. 4) Select the Cancel button and change its Action property to cancel. In these last few steps, you add code to the Delete button on the SRSearch page to set the currentSvrId in the userState bean to the currently selected row and return the navigation case to go to the Delete page. 5) Open the SRSearch page in the Visual Editor. 6) Double-click the Delete button and click OK to accept the proposed method. 7) Replace the default code with the following:

Page 93: Practice JEE5 for JDeveloper 11g (TP4) Revision 1 - … · 1 Practice for JEE5 – for JDeveloper 11g Using stateless session EJB 3.0 as a business layer, ADF data Model as a model

93

setCurrentSvrIdFromRow(); return "delete";

You can now run and test the application. 8) Run the SRSearch page and search using any criteria you choose. 9) Select a row and click Edit. 10) Change something on the row and click Save. 11) Repeat the test, only this time deletes a row.