Complete Listings


The complete code for the pet store case study can be downloaded from www.wrox.com.

Model Package Complete Listings

The model is the business interface for the system. It is the faade covering the rest of the systems. Most of the tests can be run against the model classes.

 package xptoolkit.petstore.model; public class CategorySystem {     private Category currentCategory;     private Subcategory currentSubcategory;     private Product currentProduct;     public CategorySystem() throws Exception {         currentCategory = Category.getCategory();         currentCategory.setId(777);     }     public Category getCurrentCategory() {         return currentCategory;     }     public Subcategory getCurrentSubcategory() {         return currentSubcategory;     }     public Product getCurrentProduct() {         return currentProduct;     }     public Subcategory getSubcategory(int id) throws Exception {         currentSubcategory = currentCategory.getSubcategory(id);         return currentSubcategory;     }     public Product getProduct(int id) throws Exception {         currentProduct = currentSubcategory.getProduct(id);         return currentProduct;     } } package xptoolkit.petstore.model; import java.util.*; public abstract class Category extends CatalogItem {     protected Subcategory[] subcategories;     public static Category getCategory() throws ClassNotFoundException,                                               InstantiationException,                                               IllegalAccessException {         String className =             System.getProperty("xptoolkit.petstore.category.class",                                "xptoolkit.petstore.dbmodel.CategoryDB");         Class categoryClass = Class.forName(className);         return (Category)categoryClass.newInstance();     }     public Subcategory[] getSubcategories() throws Exception {         return subcategories;     }     public abstract Subcategory getSubcategory(int id) throws Exception;     public String toString() {         return "Category [ " +             super.toString() +             "]";     } } package xptoolkit.petstore.model; public abstract class CatalogItem {     protected int id;     protected String name;     protected String description;     public int getId() {         return id;     }     public void setId(int id) throws Exception {         this.id = id;     }     public String getName() {         return name;     }     public void setName(String name) {         this.name = name;     }     public String getDescription() {         return description;     }     public void setDescription(String description) {         this.description = description;     }     public String toString() {         return "" + id + ", " + name + ", " + description;     } } package xptoolkit.petstore.model; public abstract class Subcategory extends CatalogItem {     protected int fkCategoryId;     protected Product[] products;     public int getFkCategoryId() throws Exception {         return fkCategoryId;     }     public void setFkCategoryId(int fkCategoryId) {         this.fkCategoryId = fkCategoryId;;     }     public Product[] getProducts() throws Exception {         return products;     }     public abstract Product getProduct(int id) throws Exception;     public String toString() {         return "Subcategory [ " +             super.toString() + ", " +             fkCategoryId +             "]";     } } package xptoolkit.petstore.model; public abstract class Product extends CatalogItem {     protected int price;     protected int qty;     protected int fkSubcategoryId;     public int getPrice() {         return price;     }     public void setPrice(int price) {         this.price = price;     }     public int getQty() {         return qty;     }     public void setQty(int qty) {         this.qty = qty;     }     public int getFkSubcategoryId() {         return fkSubcategoryId;     }     public void setFkSubcategoryId(int fkSubcategoryId) {         this.fkSubcategoryId = fkSubcategoryId;     }     public String toString() {         return "Product [ " +             super.toString() + ", " +             price + ", " +             qty + ", " +             fkSubcategoryId +             "]";     } } 

dbmodel Package Complete Listings

The dbmodel package is the implementation of the model. It uses JDBC to get rows out of the database and converts them to Java objects that can be manipulated by the JSPs.

 package xptoolkit.petstore.dbmodel; import xptoolkit.petstore.model.Category; import xptoolkit.petstore.model.Subcategory; import xptoolkit.petstore.model.Product; import java.sql.*; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class CategoryDB extends Category implements Entity {     public static final String COLUMNS = "ID, NAME, DESCRIPTION";     private static Connection connCategory;     private static Connection connSubcategory;     private static PreparedStatement prepLoadCategory;     private static PreparedStatement prepLoadSubcategories;     boolean loaded = false;     static     {         try {             String load = "select " + COLUMNS                 + " from CATEGORY where ID = ? ";             connCategory = InitPackage.getConnection();             prepLoadCategory = connCategory.prepareStatement(load);             load = "select " + SubcategoryDB.COLUMNS                 + " from SUBCATEGORY where FK_CATEGORY_ID = ?";             connSubcategory = InitPackage.getConnection();             prepLoadSubcategories =                        connSubcategory.prepareStatement(load);         }         catch (java.lang.Exception e) {             System.err.println(                 "Unable to load prepared statements for CategoryDB.");         }     }     public CategoryDB() {         id = -1;     }     public void setId(int id) throws Exception {         this.id = id;         subcategories = null;         load(this);     }     private void ensureLoaded() throws Exception {         if (!loaded)             load(this);         if (subcategories == null)             loadSubcategories(this);     }     public Subcategory[] getSubcategories() throws Exception {         ensureLoaded();         return subcategories;     }     public Subcategory getSubcategory(int id) throws Exception {         ensureLoaded();         if (subcategories != null) {             for (int x = 0; x < subcategories.length; x++) {                 if (subcategories[x].getId() == id)                     return subcategories[x];             }         }         return null;     }     private void init(ResultSet rs) throws SQLException {         id = rs.getInt(ID);         name = rs.getString(NAME);         description = rs.getString(DESCRIPTION);     }     private void reset() {         name = null;         description = null;     }     private static synchronized void load(CategoryDB category)         throws SQLException {         ResultSet resultSet = null;         try {             prepLoadCategory.setInt(1, category.getId());             resultSet = prepLoadCategory.executeQuery();             if ( resultSet.next() ) {                 category.init(resultSet);                 category.loaded = true;             }             else {                 category.reset();                 category.loaded = false;             }         }         finally {             if (resultSet != null)                 resultSet.close();         }    }     private static synchronized void         loadSubcategories(CategoryDB category) throws SQLException {        ArrayList list = new ArrayList();        ResultSet results = null;        try {             prepLoadSubcategories.setInt(1, category.getId());             results = prepLoadSubcategories.executeQuery();             while( results.next() ) {                 SubcategoryDB subcategory = new SubcategoryDB(results);                 Integer key = new Integer(subcategory.getId());                 list.add(subcategory);             }        }        finally{             if(results!=null)results.close();        }        category.subcategories = new SubcategoryDB[list.size()];        category.subcategories = (Subcategory[])                          list.toArray(category.subcategories);     } } package xptoolkit.petstore.dbmodel; import java.sql.*; import java.util.*; import xptoolkit.petstore.model.*; public class SubcategoryDB extends Subcategory implements Entity {     public static final String COLUMNS =         "ID, NAME, DESCRIPTION, FK_CATEGORY_ID";     private static final String FK_CATEGORY_ID = "FK_CATEGORY_ID";     private static Connection connSubcategory;     private static Connection connProducts;     private static PreparedStatement prepLoadSubcategory;     private static PreparedStatement prepLoadProducts;     boolean loaded = false;     Product[] products = null;     static {         try {             String load = "select " + COLUMNS                 + " from SUBCATEGORY where ID = ?";             connSubcategory = InitPackage.getConnection();             prepLoadSubcategory = connSubcategory.prepareStatement(load);             load = "select " + ProductDB.COLUMNS                 + " from PRODUCT where FK_SUBCATEGORY_ID = ?";             connProducts = InitPackage.getConnection();             prepLoadProducts = connProducts.prepareStatement(load);         }         catch (java.lang.Exception e){             System.err.println(                 "Unable to load prepared statements for SubcategoryDB.");             e.printStackTrace();         }     }     SubcategoryDB(ResultSet rs) throws SQLException {         init(rs);     }     SubcategoryDB() {         id = -1;     }     public void setId(int id) throws Exception{         this.id = id;         load(this);     }     private void ensureLoaded() throws Exception {         if (!loaded)             load(this);         if (products == null)             loadProducts(this);     }    public Product[] getProducts() throws Exception {         ensureLoaded();         return products;     }     public Product getProduct(int id) throws Exception {         ensureLoaded();         if (products != null) {             for (int x = 0; x < products.length; x++) {                 if (products[x].getId() == id)                     return products[x];             }         }         return null;     }     private void init(ResultSet rs) throws SQLException {         this.id = rs.getInt(ID);         this.name = rs.getString(NAME).trim();         this.description = rs.getString(DESCRIPTION).trim();         this.fkCategoryId = rs.getInt(FK_CATEGORY_ID);     }     private void reset() {         this.name = null;         this.description = null;         this.fkCategoryId = -1;     }     private static synchronized void load(SubcategoryDB subcategory)         throws SQLException {         ResultSet resultSet = null;         try {             prepLoadSubcategory.setInt(1, subcategory.getId());             resultSet = prepLoadSubcategory.executeQuery();             if ( resultSet.next() ) {                 subcategory.init(resultSet);                 subcategory.loaded = true;             }             else {                 subcategory.reset();                 subcategory.loaded = false;             }         }         finally {             if (resultSet != null)                 resultSet.close();         }     }     private static synchronized void loadProducts(                                    SubcategoryDB subcategory)         throws SQLException {         ArrayList list = new ArrayList();         ResultSet resultSet = null;         try {             prepLoadProducts.setInt(1, subcategory.getId());             resultSet = prepLoadProducts.executeQuery();             while( resultSet.next() ) {                 ProductDB product = new ProductDB(resultSet);                 Integer key = new Integer(product.getId());                 list.add(product);             }         }         finally {             if (resultSet != null) resultSet.close();         }         subcategory.products = new Product[list.size()];         subcategory.products =                     (Product[])list.toArray(subcategory.products);     } } package xptoolkit.petstore.dbmodel; import java.sql.*; public interface Entity {     public static final String ID = "ID";     public static final String NAME = "NAME";     public static final String DESCRIPTION = "DESCRIPTION";     public void setId(int id) throws Exception; } package xptoolkit.petstore.dbmodel; import java.sql.*; public class InitPackage extends java.lang.Object {     private static String url;     static {         url = System.getProperty("petstore.jdbc.url",                                   "jdbc:odbc:petstore");         try {             String driver =                 System.getProperty("petstore.jdbc.driver",                                    "sun.jdbc.odbc.JdbcOdbcDriver");             Class.forName(driver);         }         catch (Exception e){             System.err.println("unable to load driver");         }     }     static Connection getConnection() throws SQLException {        return DriverManager.getConnection(url);     }     private InitPackage() {} } 

Test Package Complete Listings

The test package tests each class in the model class; these classes are really implemented in the dbmodel. The concepts in these classes will be covered in detail in Chapter 13.

 package test.xptoolkit.petstore.model; import xptoolkit.petstore.model.CategorySystem; import junit.framework.*; public class CategorySystemTest extends TestCase {     CategorySystem system;          public CategorySystemTest(java.lang.String testName) {         super(testName);     }          public static void main(java.lang.String[] args) {         junit.textui.TestRunner.run(suite());     }          public static Test suite() {         TestSuite suite = new TestSuite(CategorySystemTest.class);                  return suite;     }          protected void setUp()throws Exception {         system = new CategorySystem();     }               /** Test of getCurrentCategory method, of class          xptoolkit.petstore.model.CategorySystem. */     public void testGetCurrentCategory() throws Exception{         assertNotNull(system.getCurrentCategory());     }          /** Test of getSubcategory method, of class          xptoolkit.petstore.model.CategorySystem. */     public void testGetSubcategory() throws Exception{         assertNotNull(system.getSubcategory(111));     }          /** Test of getProduct method, of class          xptoolkit.petstore.model.CategorySystem. */     public void testGetProduct() throws Exception {         testGetSubcategory();         assertNotNull(system.getProduct(1));     }              /** Test of getCurrentSubcategory method, of class              xptoolkit.petstore.model.CategorySystem. */     public void testGetCurrentSubcategory() throws Exception{         testGetSubcategory();         assertNotNull(system.getCurrentSubcategory());     }          /** Test of getCurrentProduct method, of class          xptoolkit.petstore.model.CategorySystem. */     public void testGetCurrentProduct() throws Exception{         testGetSubcategory();         testGetProduct();                 assertNotNull(system.getCurrentProduct());     }          } package test.xptoolkit.petstore.model; import java.util.*; import junit.framework.*; import xptoolkit.petstore.model.Category; import xptoolkit.petstore.model.Subcategory; public class CategoryTest extends TestCase {          Category category; //object under test          public CategoryTest(java.lang.String testName) {         super(testName);     }          public static void main(java.lang.String[] args) {         junit.textui.TestRunner.run(suite());     }          public static Test suite() {         TestSuite suite = new TestSuite(CategoryTest.class);                  return suite;     }               public void setUp()throws Exception{         category = Category.getCategory();         category.setId(777);     }     /** Test of getCategory method, of class          xptoolkit.petstore.model.Category. */     public void testGetCategory() throws Exception{         System.out.println("testGetCategory");         Category category = Category.getCategory();         category.setId(777);         this.assertNotNull("category", category);              }          /** Test of getSubcategories method, of class         xptoolkit.petstore.model.Category. */     public void testGetSubcategories() throws Exception {         Subcategory [] categories = category.getSubcategories();         assertNotNull("categories", categories);         for (int index=0; index < categories.length; index++){             assertNotNull("subcategory", categories[index]);         }     }              /** Test of getSubcategory method, of class              xptoolkit.petstore.model.Category. */     public void testGetSubcategory() throws Exception {         Subcategory [] categories = category.getSubcategories();         assertNotNull("categories", categories);         for (int index=0; index < categories.length; index++){             Subcategory subcat=categories[index];             int id = subcat.getId();             assertNotNull("subcategory", category.getSubcategory(id));         }     }          public void testGetters() throws Exception {         assertNotNull("name", category.getName());         assertNotNull("description", category.getDescription());           }      } package test.xptoolkit.petstore.model; import junit.framework.*; import xptoolkit.petstore.model.*; public class SubcategoryTest extends TestCase {     CategorySystem system;     Subcategory category;          protected void setUp()throws Exception{         system = new CategorySystem();         category = system.getCurrentCategory().getSubcategory(111);     }               public SubcategoryTest(java.lang.String testName) {         super(testName);     }          public static void main(java.lang.String[] args) {         junit.textui.TestRunner.run(suite());     }          public static Test suite() {         TestSuite suite = new TestSuite(SubcategoryTest.class);                  return suite;     }          /** Test of getFkCategoryId method, of class          xptoolkit.petstore.model.Subcategory. */     public void testGetters() {         assertNotNull("name", category.getName());         assertNotNull("description", category.getDescription());     }               /** Test of getProducts method, of class         xptoolkit.petstore.model.Subcategory. */     public void testGetProducts() throws Exception{         String [] testDataExpected = new String []                           {"Poodle", "Scottie", "Schnauzer"};         Product products [] = category.getProducts();         for (int index = 0; index < products.length; index++){             Product product = products[index];             assertEquals("check Name", testDataExpected[index], product.getName());         }     }               } package test.xptoolkit.petstore.model; import xptoolkit.petstore.model.*; import junit.framework.*; public class ProductTest extends TestCase {          CategorySystem system;     Product product;          protected void setUp()throws Exception{         system = new CategorySystem();         system.getSubcategory(111);         product = system.getProduct(1);     }               public ProductTest(java.lang.String testName) {         super(testName);     }          public static void main(java.lang.String[] args) {         junit.textui.TestRunner.run(suite());     }          public static Test suite() {         TestSuite suite = new TestSuite(ProductTest.class);                  return suite;     }          /** Test of getPrice method          of class xptoolkit.petstore.model.Product. */     public void testSetters() {         product.setName("Boo");         product.setDescription("Designer");         product.setPrice(5);         product.setQty(5);     }     /** Test of getPrice method          of class xptoolkit.petstore.model.Product. */     public void testGetters() {         this.assertEquals("name", product.getName(), "Poodle");         this.assertEquals("description",                            product.getDescription(),                            "Poodle description");         testSetters();         this.assertEquals("name", product.getName(), "Boo");         this.assertEquals("description",                            product.getDescription(),                            "Designer");              }          } package xptoolkit.petstore.dbmodel; import java.sql.*; import junit.framework.*; public class InitPackageTest extends TestCase {          public InitPackageTest(java.lang.String testName) {         super(testName);     }          public static void main(java.lang.String[] args) {         junit.textui.TestRunner.run(suite());     }          public static Test suite() {         TestSuite suite = new TestSuite(InitPackageTest.class);                  return suite;     }          /** Test of getConnection method, of class          xptoolkit.petstore.dbmodel.InitPackage. */     public void testGetConnection() throws SQLException{         System.out.println("testGetConnection");         Connection connection=InitPackage.getConnection();         assertNotNull("connection", connection);              }      } 

JSPs and Web.xml Complete Listings

The JSPs dont have a corresponding test like the model. They will be added after we cover the HttpUnit in Chapter 16.

 <%@ include file="category_sys.jsp" %> <html>     <head>         <title>             AAA Pets: <%= request.getParameter("title")%>     </title> </head> <body>     <h1>AAA Pets</h1>          <table border="1" width="100%">         <tr>             <td width="20%" align="center">                 <a href="index.jsp">Company</a>             </td>             <td width="20%" align="center">                 <a href="under_construction.html">Mission</a>             </td>             <td width="20%" align="center">                 <a href="under_construction.html">Shopping Cart</a>             </td>             <td width="20%" align="center">                 <a href="under_construction.html">Links</a>             </td>     </table>          <table border="1" width="100%">         <tr>         <%             Category category = categorySystem.getCurrentCategory();             Subcategory [] subcategories = category.getSubcategories();             for (int index=0; index < subcategories.length; index++){                 Subcategory subcategory = subcategories[index];         %>             <td width="20%" align="center">                 <a href="subcategory.jsp?id=<%=subcategory.getId()%>">                     <%=subcategory.getName()%>                 </a>                 <br />             </td>         <%}%>     </table>     <table width="100%">         <tr>             <td width="100%" align="left">             </td>         </tr>     </table>     <p align="center">         <font size="-1">             Copyright 2004, Rick Hightower<br>             AAA Pets is a fictional company any similarities to a real company is coincidental.         </font>     </p>     </body> </html> <%@page import="xptoolkit.petstore.model.*" %> <jsp:useBean id="categorySystem" class="CategorySystem" scope="session"/> <jsp:include page="header.jsp" flush="true">       <jsp:param name="title" value="Welcome"/> </jsp:include>     <div align="center">         <b>Welcome to AAA Pets</b>     </div> <jsp:include page="footer.jsp" flush="true" /> <jsp:include page="header.jsp" flush="true">       <jsp:param name="title" value="Welcome"/> </jsp:include>     <div align="center">         <b>Sorry, I could not find that page.</b>     </div> <jsp:include page="footer.jsp" flush="true" /> <%@ include file="category_sys.jsp" %> <%     String categoryId = request.getParameter("id");     Category category = categorySystem.getCurrentCategory();     category.setId( Integer.parseInt(categoryId) ); %> <jsp:include page="header.jsp" flush="true">       <jsp:param name="title" value="<%= category.getName() %>"/> </jsp:include>     <table border="1" width="100%">         <tr>             <td width="100%" colspan="2" align="center">                 <b>                     <%= category.getName() %>                 </b>                 <br>                 <%= category.getDescription() %>             </td>         </tr>         <tr>             <td width="20%"> <%     Subcategory[] subcategories = category.getSubcategories();     for (int index = 0; index < subcategories.length; index++) {         Subcategory subcategory = subcategories[index]; %> <a href="subcategory.jsp?id=<%=subcategory.getId()%>"> <%=subcategory.getName()%></a>         <br> <%     } %>             </td>             <td>&nbsp;</td>         </tr>     </table> <jsp:include page="footer.jsp" flush="true" /> <%@ include file="category_sys.jsp" %> <%     Category category = categorySystem.getCurrentCategory();     Subcategory[] subcategories = category.getSubcategories();     String subcategoryId = request.getParameter("id");     int id = Integer.parseInt(subcategoryId);     Subcategory subcategory = categorySystem.getSubcategory(id);          String title = category.getName() + " : " + subcategory.getName(); %> <jsp:include page="header.jsp" flush="true">       <jsp:param name="title" value="<%= title %>"/> </jsp:include>     <table border="1" width="100%">         <tr>             <td width="100%" colspan="2" align="center">                 <b>                     <%= category.getName() %>                 </b>                 <br>                 <%= category.getDescription() %>                 <br>                 <b>                     <%= subcategory.getName() %>                 </b>                 <br>                 <%= subcategory.getDescription() %>             </td>         </tr>         <tr>             <td width="20%" valign="top"> <%     for (int index = 0; index < subcategories.length; index++) {         Subcategory subcat = subcategories[index]; %> <a href="subcategory.jsp?id=<%=subcat.getId()%>"> <%=subcat.getName()%></a>         <br> <%     } %>             </td>             <td valign="top"> <%     Product[] products = subcategory.getProducts();     for (int pindex = 0; pindex < products.length; pindex++) {         Product product = products[pindex]; %>         <a href="product.jsp?id=<%= product.getId()%>" target="_blank"><%= product.getName() %></a>         <br> <%     } %>             </td>         </tr>     </table> <jsp:include page="footer.jsp" flush="true" /> <%@ page import="java.text.NumberFormat,java.util.Locale" %> <%@ include file="category_sys.jsp" %> <%     Category category = categorySystem.getCurrentCategory();     Subcategory subcategory = categorySystem.getCurrentSubcategory();     String productId = request.getParameter("id");     Product product = subcategory.getProduct( Integer.parseInt(productId) );      String title = category.getName() +                     " : " + subcategory.getName() +                     " : " + product.getName(); %> <jsp:include page="header.jsp" flush="true">       <jsp:param name="title" value="<%= title %>"/> </jsp:include> <%     Locale locale = request.getLocale();     NumberFormat format = NumberFormat.getCurrencyInstance(locale);      String price = format.format(product.getPrice()); %>     <div align="center">         <b><%= product.getName() %></b>         <br>                  <%= product.getDescription() %>         <br>                  <STRONG><%= price %></STRONG>         <br>     </div> <jsp:include page="footer.jsp" flush="true" /> <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app   PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"   "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd"> <web-app>     <error-page>         <error-code>404</error-code>         <location>/notfound.jsp</location>     </error-page>   <!-- The Usual Welcome File List -->   <welcome-file-list>     <welcome-file>index.jsp</welcome-file>   </welcome-file-list>   <servlet-mapping url-pattern='/servlet/*' servlet-name='invoker'/> </web-app> 



Professional Java Tools for Extreme Programming
Professional Java Tools for Extreme Programming: Ant, XDoclet, JUnit, Cactus, and Maven (Programmer to Programmer)
ISBN: 0764556177
EAN: 2147483647
Year: 2003
Pages: 228

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net