ejb exercises

23
CD5480 - Component Technologies, 5 credits 1-1 EJB Exercise 1 - Implementing the shop with EJB 1.1 Overview We want to build a web based fruit store, you are free to decide details, but here is a scenario describing how it should work. 1. The web page is created up by a JSP page 2. The JSP page locates/creates the shop bean 3. The JSP page creates the shopping cart bean, for the specific client 4. The contents in the shop are displayed on the web page 5. The user selects one or several articles 6. The article(s) is placed in the shopping cart 7. The user decides to buy 8. The contents in the cart is removed from the shop, and the cutomer is requsted to pay the amount for the selected articles There is also an application client that can be used by the shop assitants to fill the shop with articles, upon a delivery etc. 1.1.1 Goals: After completing this exercise you should be able to: Give an overview of the EJB component technology Create web clients through JSP pages. Create application clients. Use session beans to store session specific data. Use entity beans, for persistent data. Use the Java database support to write code that uses a database. Compare the amount and quality of work needed to accomplish the same task in the different technologies we have discussed during the course. 1.1.2 Requirements Software (free of charge) Should be installed in the sheduled lab-room, but for home usage etc! We need j2ee, which requires j2se, and to compile in a reasonable way we need ant;

Upload: teresa-carter

Post on 20-Jul-2016

235 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: EJB Exercises

CD5480 - Component Technologies, 5 credits

1-1

EJB Exercise 1 - Implementing the shop with EJB

1.1 Overview

We want to build a web based fruit store, you are free to decide details, but here is a scenario describing how it should work.

1. The web page is created up by a JSP page

2. The JSP page locates/creates the shop bean

3. The JSP page creates the shopping cart bean, for the specific client

4. The contents in the shop are displayed on the web page

5. The user selects one or several articles

6. The article(s) is placed in the shopping cart

7. The user decides to buy

8. The contents in the cart is removed from the shop, and the cutomer is requsted to pay the amount for the selected articles

• There is also an application client that can be used by the shop assitants to fill the shop with articles, upon a delivery etc.

1.1.1 Goals:

After completing this exercise you should be able to:

• Give an overview of the EJB component technology

• Create web clients through JSP pages.

• Create application clients.

• Use session beans to store session specific data.

• Use entity beans, for persistent data.

• Use the Java database support to write code that uses a database.

• Compare the amount and quality of work needed to accomplish the same task in the different technologies we have discussed during the course.

1.1.2 Requirements

Software (free of charge)

Should be installed in the sheduled lab-room, but for home usage etc! We need j2ee, which requires j2se, and to compile in a reasonable way we need ant;

Page 2: EJB Exercises

CD5480 - Component Technologies, 5 credits

1-2

• J2ee, Java 2 Platform, Enterprise Edition; j2sdkee1.3.1, http://java.sun.com/j2ee/sdk_1.3/ ;

• J2se, Java 2 Platform, Standard Edition j2sdk1.4.1_02, http://java.sun.com/products/archive/j2se/1.4.1_02/index.html ;

• Ant, ant build tool, (make for java) jakarta-ant-1.3, http://archive.apache.org/dist/ant/binaries/jakarta-ant-1.3-bin.zip

Installation

J2ee and J2se are Windows installation wizards, e.g., press next until they are installed. But it is important to unistall previous versions of j2se! Ant is just to unpack to the prefered directory.

System variables, System -> Advanced -> System variables

Add the following variables

Variable Value

JAVA_HOME Path to the J2se installation

J2EE_HOME Path to the J2ee installation

ANT_HOME Path to the Ant installation

Update the path variable

PATH include the ’bin’ folder for j2se, j2ee and ant

1.1.3 Prerequisites

You should be famialair with Java, or similair object oriented languages. Use the lecture slides and (not or) tuturials etc avaliable at http://java.sun.com. You may buy the recommended book, but it won’t be necessary to completete this excersice.

1.1.4 Examination

You should be able to explain all parts of your produced software. The application should be zipped and sent to the lab-teacher together with your ID (YYYYMMDD-XXXX) and name. You are allowed to be maximum two persons in each group. Both must know and be able to answer questions on all parts of the produced software.

1.2 Exercise

This excersice description, actually gives an almost full solution to the excersice. The solution will include a session bean, an entity bean, a database, a web client, and an application client. An overwiev picture is shown in figure 1. The described solution shall be treated as a help to solve the problem with EJB

Page 3: EJB Exercises

Course CD5480 - Component Technologies, 5 credits

1-3

technology, you may come up with an own solution different from this at any point, as long as it solve the same task.

1.2.1 File organization

The file organization for the example solution is shown in figure 2. Folders are in bold face and files have a file extension, this structure is suppoeted by the build file and later during the deployment step. All files are included in the appendix.

Figure 1, general architechture

Files and folders: Description: root-catalog build.xml build-file build ejb TheShoppersChoice sql stock.sql database definition src ejb TheShoppersChoice index.jsp web client shop.java shopBean.java shop bean shopHome.java shopInitStock.java application client shoppingCart.java shoppingCartBean.java shopping cart bean shoppingCartHome.java

Figure 2, the file organization

J2EE Compliant Application Server

EJB Container

Database

Shopping Cart Session bean

Shop Entity bean

JSP pageHtml page

Page 4: EJB Exercises

CD5480 - Component Technologies, 5 credits

1-4

1.3 Deploy and run the application

1.3.1 Compile, start tools, database and server

1. Start the server, open a terminal window or the start-run field and type:

j2ee –verbose

2. The database must be started before the applications can access it, type in a terminal window or in the start-run field:

cloudscape -start

3. Compile the application, start by opening an MS DOS prompt, open the start run-filed and type:

command (It does not work with typing cmd!)

4. Compile the program, step to the root folder of your application and type:

ant TheShoppersChoice

5. Create entries in the database by typing:

ant create-stock-table

6. Start the deploytool, open a terminal window or the srart-run field and type:

deploytool

When desired, stop the database bt typing:

cloudscape –stop

To stop the j2ee server type:

J2ee -stop

1.3.2 Create beans, clients and specify references

1. Create the application

• In deploytool, select File -> New -> Application.

• Click Browse.

• In the file chooser, navigate to ../build/ejb/TheShopperChoice

• In the File Name field, enter TheShoppersChoice.ear

• Click New Application.

Page 5: EJB Exercises

Course CD5480 - Component Technologies, 5 credits

1-5

• Click OK.

2. Package the entity bean

• select File -> New -> Enterprise Bean.

• Read the explanatory text for an overview of the wizard’s features.

• Click Next.

• Select the Create New JAR File In Application button.

• In the combo box, select TheShoppersChoice.

• In the JAR Display Name field, enter ShopJAR.

• Click Edit.

• In the tree under Available Files, locate the ../build/ejb/TheShopperChoice directory. Select the following classes from the Available Files tree and click Add: shop.class, shopBean,.class shopHome.class.

• Click OK.

• Click Next.

• Under Bean Type, select the Entity radio button.

• In the Enterprise Bean Class combo box, select shopBean.

• In the Enterprise Bean Name field, enter shopEJB..

• In the Remote Home Interface combo box, select shopHome.

• In the Remote Interface combo box, select shop.

• Click Next.

• In the Entity Settings screen, select Bean-Managed Persistance under Persitance Management, set and java.lang.String as Primary Key Class.

• Click Next.

• Select the Container-Managed radio button under Transaction Management.

• You may skip the remaining dialog boxes, click Finish.

3. Package the session bean

• select File -> New -> Enterprise Bean.

• Read the explanatory text for an overview of the wizard’s features.

• Click Next.

• Select the Create New JAR File In Application button.

• In the combo box, select TheShoppersChoice.

Page 6: EJB Exercises

CD5480 - Component Technologies, 5 credits

1-6

• In the JAR Display Name field, enter ShoppingCartJAR.

• Click Edit.

• In the tree under Available Files, locate the ../build/ejb/TheShopperChoice directory. Select the following classes from the Available Files tree and click Add: shoppingCart.class, shoppingCartBean,.class shoppingCartHome.class.

• Click OK.

• Click Next.

• Under Bean Type, select the Session radio button.

• Select the Stateful radio button.

• In the Enterprise Bean Class combo box, select shoppingCartBean.

• In the Enterprise Bean Name field, enter shoppingCartEJB.

• In the Remote Home Interface combo box, select shoppingCartHome.

• In the Remote Interface combo box, select shoppingCart.

• Click Next.

• You may skip the remaining dialog boxes, click Finish.

4. Package the application client

• To start the New Application Client wizard, select File -> New −> Application Client.

• Read the explanatory text for an overview of the wizard’s features.

• Click Next.

• In the combo box, select TheShoppersChoice.

• Click Edit.

• In the tree under Available Files, locate the ../build/ejb/TheShopperChoice directory.

• Select the shopInitStock.class file and click Add.

• Click OK.

• Click Next.

• In the Main Class combo box, select shopiInitStock.

• In the Callback Handler Class combo box, select container-managed authentication.

• Click Next.

• Click Finish.

5. Package the web client

Page 7: EJB Exercises

Course CD5480 - Component Technologies, 5 credits

1-7

• select File -> New -> Web Component.

• Read the explanatory text for an overview of the wizard’s features.

• Click Next.

• Select Create New WAR File In Application.

• In the combo box, select TheShoppersChoice.

• In the WAR Display Name field, enter TheShoppersChoiceWAR.

• Click Edit.

• In the tree under Available Files, locate the../build/ejb/TheShopperChoice directory.

• Select index.jsp and click Add.

• Click OK.

• Click Next.

• Choose Component Type dialog box

• Select the JSP radio button.

• Click Next.

• In the JSP Filename combo box, select index.jsp.

• Click Finish.

6. Specify all loose references

• Specifying the Web Client’s Enterprise Bean References

o In the tree, select TheShoppersChoiceWAR.

o Select the EJB Refs tab.

o Click Add.

o In the Coded Name column, enter ejb/TheShop.

o In the Type column, select Entity.

o In the Interfaces column, select Remote.

o In the Home Interface column, enter shopHome.

o In the Local/Remote Interface column, enter shop.

o Click Add.

o In the Coded Name column, enter ejb/TheShoppingCart.

o In the Type column, select Session.

o In the Interfaces column, select Remote.

o In the Home Interface column, enter shoppingCartHome.

Page 8: EJB Exercises

CD5480 - Component Technologies, 5 credits

1-8

o In the Local/Remote Interface column, enter shoppingCart.

• Specifying the Application Client’s Enterprise Bean Reference

o In the tree, select shopInitStock.

o Select the EJB Refs tab.

o Click Add.

o In the Coded Name column, enter ejb/TheShop.

o In the Type column, select Entity.

o In the Interfaces column, select Remote.

o In the Home Interface column, enter shopHome.

o In the Local/Remote Interface column, enter shop.

• Specifying the Entity Beans Database Reference

o In the tree, expand shopJar.

o Select the shopBean.

o Select the Resource Refs tab.

o Click Add.

o In the Coded Name column, enter jdbc/TheShoppersChoiceDB.

• Specify JNDI Names

o In the tree, select TheShoppersChoice.

o Select the JNDI Names tab.

o To specify the JNDI names for the beans, in the Application table locate the shopEJB component and the shoppingCartEJB component and enter MyShop and MyShoppingCart in the JNDI Name columns respectively.

o To map the references, in the References table JNDI Name field enter MyShop for those refernce names that are ejb/TheShop (should be 2), and MyShoppingCart for those that are named ejb/TheShoppingCart (should be 1).

o Finally there is a resource reference made by the shopBean, with a coded name jdbc/TheShoppersChoiceDB; enter jdbc/Cloudscape in the JNDI name column.

1.3.3 Deploy the application on the j2ee server

1. In the tree select TheShoppersChoice application.

2. Select Tools −> Deploy.

3. In the Introduction dialog box, confirm that TheShoppersChoice is shown for the Object To Deploy and select localhost for the Target Server.

4. Select the checkbox labeled Return Client Jar.

Page 9: EJB Exercises

Course CD5480 - Component Technologies, 5 credits

1-9

5. In the text field that appears, enter the full path name for the file TheShoppersChoiceClient.jar, so that it will reside in the ..\build\ejb\TheShoppersChoice directory.

6. Click Next.

7. In the JNDI Names dialog box, verify the names you entered in the previous section.

8. Click Next.

9. In the WAR Context Root dialog box, enter TheShoppersChoice in the Context Root field. When you run the web client, the context root will be part of the URL.

10. Click Next.

11. In the Review dialog box, click Finish.

1.3.4 Run the application client

1. In a terminal window, go to the ../build/ejb/TheShoppersChoice directory.

2. Set the APPCPATH environment variable to TheShoppersChoiceClient.jar:

3. set APPCPATH=TheShoppersChoice.jar

4. Type the following command:

5. runclient –client TheShoppersChoice.ear –name shopInitStock -textauth

6. The client prompts you to log in. Enter guest for the user name and guest123 for the password.

7. The database (or the stock) in the store is now filled with some fruits.

1.3.5 Run the Web Client

1. To run the web client, open your web browser and type the following in the URL field: http://localhost:8000/TheShoppersChoice

2. Now it should appear a login field, type whatever you want and start to pick fruits; thats it!

1.3.6 Modify the j2EE application

Whenever a source file is modified, recompile the source files with ant, then undeploy and redeploy the application. This can be done by selcting localhost in the tree in the deploytool, then undeploy TheShoppersChoice, and select TheShoppersChoice in the treee and choose tools -> update files and then tools -> deploy.

The same procedure (undeploy – update files – deploy) shall be performed when a deployment parameter or setting has been changed.

Page 10: EJB Exercises

1C:\javab\src\ejb\TheShoppersChoice\shoppingCartBean.java

/************************ cart bean** Mikael Åkerholm*************************/

import java.util.*;import javax.ejb.*;import java.math.BigDecimal;

public class shoppingCartBean implements SessionBean{ String id; Vector contents;

public void ejbCreate(String id) throws CreateException{ this.id=id; contents = new Vector(); } public void addArticle(String id){ contents.addElement(id); }

public void removeArticle(String id){ contents.removeElement(id); }

public Vector getContents(){ return contents; }

public shoppingCartBean() {} public void ejbRemove() {} public void ejbActivate() {} public void ejbPassivate() {} public void setSessionContext(SessionContext sc) {}

public BigDecimal test2(){ return new BigDecimal("1.43"); }

public BigDecimal test(){ BigDecimal r = new BigDecimal("1.43"); return r; }}

Page 11: EJB Exercises

1C:\javab\src\ejb\TheShoppersChoice\shoppingCart.java

/************************ Remote Interface, cart bean** Mikael Åkerholm*************************/

import java.util.*;import javax.ejb.EJBObject;import java.rmi.RemoteException;import java.math.BigDecimal;

public interface shoppingCart extends EJBObject{ public void addArticle(String id) throws RemoteException; public void removeArticle(String id) throws RemoteException; public Vector getContents() throws RemoteException; public BigDecimal test() throws RemoteException; public BigDecimal test2() throws RemoteException;}

Page 12: EJB Exercises

1C:\javab\src\ejb\TheShoppersChoice\shopInitStock.java

/************************ shop fill database** Mikael Åkerholm*************************/

import java.util.*;import javax.rmi.PortableRemoteObject;import javax.ejb.*;import javax.naming.*;import java.math.BigDecimal;

public class shopInitStock{ public static void main(String[] args){ try{ shop shopO; Iterator i; Collection col; Context initial = new InitialContext(); Object objref = initial.lookup("java:comp/env/ejb/TheShop"); shopHome sHome = (shopHome)PortableRemoteObject.narrow(objref, shopHome.class); shopO = sHome.create(new String("001"), new String("pineapple"), new BigDecimal("15

"), new BigDecimal("400")); shopO.insertArticle(new String("002"), new String("Chinese gooseberry"), new

BigDecimal("6"), new BigDecimal("200")); shopO.insertArticle(new String("003"), new String("Melon"), new BigDecimal("8"),

new BigDecimal("140")); shopO.insertArticle(new String("004"), new String("Apple"), new BigDecimal("9.50"),

new BigDecimal("210")); shopO.insertArticle(new String("005"), new String("Orange"), new BigDecimal("2.30")

, new BigDecimal("200")); shopO.insertArticle(new String("006"), new String("Tomato"), new BigDecimal("6"),

new BigDecimal("900")); shopO.insertArticle(new String("007"), new String("Grapefruit"), new BigDecimal("12

"), new BigDecimal("119")); shopO.insertArticle(new String("008"), new String("Pear"), new BigDecimal("4"), new

BigDecimal("200")); shopO.insertArticle(new String("009"), new String("Banana"), new BigDecimal("8"),

new BigDecimal("200")); shopO.insertArticle(new String("010"), new String("Mango"), new BigDecimal("12.50")

, new BigDecimal("230")); shopO.insertArticle(new String("011"), new String("Peach"), new BigDecimal("10"),

new BigDecimal("450")); col = shopO.getStockList(); i= col.iterator(); while( i.hasNext() ){ System.out.println((String)i.next()); } System.exit(0); }catch( Exception ex){ System.out.println("exception: " + ex.getMessage()); } }}

Page 13: EJB Exercises

1C:\javab\src\ejb\TheShoppersChoice\shopHome.java

/************************ Home Interface, cart bean** Mikael Åkerholm*************************/import java.util.Collection;import java.rmi.RemoteException;import java.math.BigDecimal;import javax.ejb.*;

public interface shopHome extends EJBHome{ public shop create(String id, String articleName, BigDecimal price, BigDecimal

quantity) throws RemoteException, CreateException; public shop findByPrimaryKey(String id) throws FinderException, RemoteException;

}

Page 14: EJB Exercises

1C:\javab\src\ejb\TheShoppersChoice\shopBean.java

/************************ shop bean** Mikael Åkerholm*************************/

import java.sql.*;import javax.sql.*;import java.util.*;import java.rmi.RemoteException;import javax.ejb.*;import javax.naming.*;import java.math.BigDecimal;

public class shopBean implements EntityBean{ private String id; private EntityContext context; private Connection con; private String databaseName ="java:comp/env/jdbc/TheShoppersChoiceDB"; private String articleName; private BigDecimal stPrice; private BigDecimal quantity;

public String ejbCreate(String id, String articleName, BigDecimal price, BigDecimal quantity) throws CreateException{

this.id = id; try { insertRow(id, articleName, price, quantity); } catch (Exception ex) { throw new EJBException("ejbCreate: " + ex.getMessage()); } this.id = id; this.articleName = articleName; this.stPrice = price; this.quantity = quantity; return id; }

public BigDecimal test(){ BigDecimal ret=new BigDecimal("1.76"); return ret; }

public void insertArticle(String id, String ArticleName, BigDecimal price, BigDecimal quantity){

try{ insertRow(id, ArticleName, price, quantity); }catch(Exception ex){ throw new EJBException("insertArticle: " + ex.getMessage()); } } public Collection getStockList(){ Collection ret; try{ ret = getStock(); }catch(Exception ex){ throw new EJBException("getStockList: " +ex.getMessage()); } return ret; }

public void removeArticlesFromStock(Collection articles){ Iterator i = articles.iterator(); try{ while( i.hasNext() ){ id=selectByArticleName((String)i.next()); loadRow(); quantity= quantity.add(new BigDecimal("-1")); storeRow();

Page 15: EJB Exercises

2C:\javab\src\ejb\TheShoppersChoice\shopBean.java

} }catch(Exception ex){ throw new EJBException("removeArticlesFromStock: " +ex.getMessage()); } }

public BigDecimal getPrice(Collection articles){ BigDecimal ret = new BigDecimal("0.0"); Iterator i = articles.iterator(); try{ while( i.hasNext() ){ id=selectByArticleName((String)i.next()); loadRow(); ret = ret.add(stPrice); } }catch(Exception ex){ throw new EJBException("getPrice: " +ex.getMessage()); } return ret; }

public void setEntityContext(EntityContext c){ this.context = c; try{ makeConnection(); }catch(Exception ex){ throw new EJBException("Cannot connect to database! " +ex.getMessage()); } } public void unsetEntityContext(){ try{ con.close(); }catch(Exception ex){ throw new EJBException("Cannot disconnect from database! " +ex.getMessage()); } } public String ejbFindByPrimaryKey(String primaryKey) throws FinderException{ boolean found; try{ found=selectByPrimaryKey(primaryKey); this.id = primaryKey; }catch(Exception ex){ throw new EJBException("findex: " +ex.getMessage()); } if(!found){ throw new ObjectNotFoundException("find by primary key! :"); } return primaryKey; }

public void ejbActivate(){ id = (String)context.getPrimaryKey(); }

public void ejbPassivate(){ id = null; }

public void ejbLoad(){ try{ loadRow(); }catch(Exception ex){ throw new EJBException("ejbLoad: " +ex.getMessage()); } }

public void ejbStore(){ try{ storeRow(); }catch(Exception ex){

Page 16: EJB Exercises

3C:\javab\src\ejb\TheShoppersChoice\shopBean.java

throw new EJBException("ejbLoad: " +ex.getMessage()); } }

public void ejbRemove(){ try{ deleteRow(id); }catch(Exception ex){ throw new EJBException("ejbRemove " +ex.getMessage()); } }

public void ejbPostCreate(String id, String articleName, BigDecimal price, BigDecimal

quantity) {} /************ Private Database Routines **********************/

private void makeConnection() throws NamingException, SQLException { InitialContext ic = new InitialContext(); DataSource ds = (DataSource) ic.lookup(databaseName); con = ds.getConnection(); }

private void insertRow(String id, String articleName, BigDecimal stPrice, BigDecimal

quantity) throws SQLException { String insertStatement = "insert into stock values ( ? , ? , ? , ? )"; PreparedStatement prepStmt = con.prepareStatement(insertStatement); prepStmt.setString(1, id); prepStmt.setString(2, articleName); prepStmt.setBigDecimal(3, stPrice); prepStmt.setBigDecimal(4, quantity); prepStmt.executeUpdate(); prepStmt.close(); }

private void deleteRow(String id) throws SQLException { String deleteStatement = "delete from stock where id = ? "; PreparedStatement prepStmt = con.prepareStatement(deleteStatement); prepStmt.setString(1, id); prepStmt.executeUpdate(); prepStmt.close(); }

private boolean selectByPrimaryKey(String primaryKey) throws SQLException { String selectStatement = "select id " + "from stock where id = ? "; PreparedStatement prepStmt = con.prepareStatement(selectStatement); prepStmt.setString(1, primaryKey); ResultSet rs = prepStmt.executeQuery(); boolean result = rs.next(); prepStmt.close(); return result; }

private String selectByArticleName(String articleName) throws SQLException { String selectStatement = "select id " + "from stock where articlename = ? "; PreparedStatement prepStmt = con.prepareStatement(selectStatement); prepStmt.setString(1, articleName); ResultSet rs = prepStmt.executeQuery(); prepStmt.close(); return rs.getString(1); }

private void loadRow() throws SQLException { String selectStatement = "select articlename, stprice, quantity " + "from stock

where id = ? "; PreparedStatement prepStmt = con.prepareStatement(selectStatement); prepStmt.setString(1, this.id); ResultSet rs = prepStmt.executeQuery(); if (rs.next()) { this.articleName = rs.getString(1);

Page 17: EJB Exercises

4C:\javab\src\ejb\TheShoppersChoice\shopBean.java

this.stPrice = rs.getBigDecimal(2); this.quantity = rs.getBigDecimal(3); prepStmt.close(); } else { prepStmt.close(); throw new NoSuchEntityException("Row for id " + id + " not found in database."); } }

private void storeRow() throws SQLException { String updateStatement = "update stock set articlename = ? ," + "stprice = ? ,

quantity = ? " + "where id = ?"; PreparedStatement prepStmt = con.prepareStatement(updateStatement); prepStmt.setString(1, articleName); prepStmt.setBigDecimal(2, stPrice); prepStmt.setBigDecimal(3, quantity); prepStmt.setString(4, id); int rowCount = prepStmt.executeUpdate(); prepStmt.close(); if (rowCount == 0) { throw new EJBException("Storing row for id " + id + " failed."); } }

private Collection getStock() throws SQLException{ String selectAllStatement = "select articlename from stock "; PreparedStatement prepStmt = con.prepareStatement(selectAllStatement); ResultSet rs = prepStmt.executeQuery(); ArrayList a = new ArrayList(); while (rs.next()) { String id = rs.getString(1); a.add(id); } prepStmt.close(); return a; }

}

Page 18: EJB Exercises

1C:\javab\src\ejb\TheShoppersChoice\shop.java

/************************ Remote Interface, shop bean** Mikael Åkerholm*************************/

import java.util.*;import javax.ejb.EJBObject;import java.rmi.RemoteException;import java.math.BigDecimal;

public interface shop extends EJBObject{ public Collection getStockList() throws RemoteException; public void removeArticlesFromStock(Collection articles) throws RemoteException; public BigDecimal getPrice(Collection articles) throws RemoteException; public BigDecimal test() throws RemoteException; public void insertArticle(String id, String ArticleName, BigDecimal price, BigDecimal

quantity) throws RemoteException;}

Page 19: EJB Exercises

1C:\javab\src\ejb\TheShoppersChoice\shoppingCartHome.java

/************************ Home Interface, cart bean** Mikael Åkerholm*************************/

import java.io.Serializable;import java.rmi.RemoteException;import javax.ejb.CreateException;import javax.ejb.EJBHome;import java.util.*;

public interface shoppingCartHome extends EJBHome{ shoppingCart create(String id) throws RemoteException, CreateException;}

Page 20: EJB Exercises

1C:\javab\src\ejb\TheShoppersChoice\index.jsp

<%-- Web client Mikael Åkerholm--%> <%@ page import="javax.ejb.*, java.util.*, java.math.*, javax.naming.*, javax.rmi.

PortableRemoteObject, java.rmi.RemoteException, shoppingCart, shoppingCartHome, shop, shopHome" %>

<%! private shoppingCart shoppingCartO = null; private shop shopO = null; Iterator i; Collection col; String uName; shoppingCartHome sCHome; public void jspInit() { try { InitialContext ic = new InitialContext(); Object objRef = ic.lookup("java:comp/env/ejb/TheShoppingCart"); sCHome = (shoppingCartHome)PortableRemoteObject.narrow(objRef, shoppingCartHome.

class); InitialContext ic2 = new InitialContext(); Object objRef2 = ic2.lookup("java:comp/env/ejb/TheShop"); shopHome sHome = (shopHome)PortableRemoteObject.narrow(objRef2, shopHome.class); shopO = sHome.findByPrimaryKey("001"); } catch (RemoteException ex) { System.out.println("Couldn't create shop bean."+ ex.getMessage()); } catch (FinderException ex) { System.out.println("Couldn't create shopbean."+ ex.getMessage()); } catch (NamingException ex) { System.out.println("Unable to lookup home: "+ " shop "+ ex.getMessage()); } }

public void jspDestroy() { shoppingCartO = null; shopO = null; }%>

<html><head> <title>The Shoppers' Choice</title></head> <body bgcolor="White"><h1><b><center>The Shoppers' Choice</center></b></h1>

<p><center>Enter your name:<form method="get"><input type="text" name="username" size="30"><br><input type="submit" value="Submit"><p></form><hr><% uName=request.getParameter("username"); if(uName != null && uName.length() > 0){ if(shoppingCartO==null){ try{ shoppingCartO = sCHome.create(uName); } catch (CreateException ex) { System.out.println("Couldn't create shoppingCart bean."+ ex.getMessage

()); } catch (RemoteException ex) { System.out.println("Couldn't create shoppingCart bean."+ ex.getMessage

()); }

Page 21: EJB Exercises

2C:\javab\src\ejb\TheShoppersChoice\index.jsp

}%> <p>Fruit stock:</p>

<% col = shopO.getStockList(); i= col.iterator(); %> <ol> <% while( i.hasNext() ){ String s = (String)i.next(); %> <li> <%= s %> <form method="get" > <input type="submit" value="Add To Cart" > <input type="hidden" name="fruit" value="<%= s %>" > <input type="hidden" name="username" value="<%= uName %>" > </form> <% } %> </ol> < String fruitToAdd = request.getParameter("fruit"); shoppingCartO.addArticle(fruitToAdd); col=shoppingCartO.getContents(); i= col.iterator(); %> <p> Your shopping cart: <% while( i.hasNext() ){ String s = (String)i.next(); if(s != null) %> <%= s %>, <% } %> </p><%}%> </body></html>

Page 22: EJB Exercises

1C:\javab\build.xml

<project name="The Shoppers Choice" default="about" basedir="."> <target name="init"> <tstamp/> <property name="build" value="build" /> <property name="src" value="src" /> <property name="TheShoppersChoice" value="src/TheShoppersChoice" /> <property name="ejb" value="ejb" /> <property name="sql" value="sql" /> <property environment="myenv" /> <property name="j2eepath" value="${myenv.J2EE_HOME}/lib/j2ee.jar" /> <property name="connector-lib" value="${myenv.J2EE_HOME}/lib/connector" /> <property name="cloud-lib" value="${myenv.J2EE_HOME}/lib/cloudscape" /> <property name="system-lib" value="${myenv.J2EE_HOME}/lib/system" /> <property name="cloudpath" value=".:${cloud-lib}/cloudclient.jar:${cloud-lib}/

RmiJdbc.jar:${system-lib}/cloudutil.jar:${system-lib}/cloudscape.jar" /> <property name="cloud-jvmargs" value="-ms16m -mx32m -Dij.connection.CloudscapeDB=

jdbc:rmi://localhost:1099/jdbc:cloudscape:CloudscapeDB;create=true -Dcloudscape.system.home=${myenv.J2EE_HOME}/cloudscape" />

</target>

<target name="prepare" depends="init"> <mkdir dir="${build}" /> </target>

<target name="clean" depends="init"> <delete dir="${build}" /> </target> <target name="all" depends="init"> </target>

<target name="ejb" depends="init, TheShoppersChoice" > <chmod perm="go+r" type="both"> <fileset dir=".." /> </chmod> </target> <target name="TheShoppersChoice" depends="init"> <mkdir dir="${build}/${ejb}/TheShoppersChoice" /> <javac srcdir="${src}/${ejb}/TheShoppersChoice" destdir="${build}/${ejb}/TheShoppersChoice" classpath="${j2eepath}" /> <copy todir="${build}/${ejb}/TheShoppersChoice" > <fileset dir="${src}/${ejb}/TheShoppersChoice" > <include name="**/*.jsp" /> </fileset> </copy> </target> <target name="create-stock-table" depends="init"> <java classname="COM.cloudscape.tools.ij" fork="yes"> <arg value="${sql}/stock.sql" /> <jvmarg line="${cloud-jvmargs}" /> <classpath path="${cloudpath}" /> </java> </target></project>

Page 23: EJB Exercises

1C:\javab\sql\stock.sqldrop table stock;

create table stock (id varchar(3) constraint pk_stock_ primary key, articlename varchar(24), stprice numeric(10,2), quantity numeric(10,2));exit;