The Product and Category Classes

I l @ ve RuBoard

The Product and Category Classes

Before you can actually display the product and category pages, you need to create the underlying beans that the JSP pages depend on, much as you did with the Customer class in Chapter 8. These beans are a bit different, however, because they don't handle form input. Instead, they get their content by reading from the database (similar to the findCustomer method).

You can start with the product bean because the category bean will need to use it. You can find it in Listing 9.6.

Listing 9.6 Product.java
 package com.bfg.product; import java.util.Vector; import java.util.HashMap; import java.util.Iterator; import java.text.SimpleDateFormat; import java.text.NumberFormat; import org.apache.turbine.services.db.TurbineDB; import org.apache.turbine.util.db.pool.DBConnection; import org.apache.turbine.util.TurbineConfig; import com.bfg.exceptions.ProductActivityException; import java.sql.*; import java.util.ResourceBundle; import org.apache.turbine.util.Log; public class Product {     private static ResourceBundle sql_bundle =      ResourceBundle.getBundle("com.bfg.product.SQLQueries");     protected String pISBN;     protected String pTitle;     protected Vector pAuthors = new Vector();     protected float pPrice;     protected java.sql.Date pPubDate;     protected String pDescription;     protected static HashMap products = new HashMap();     public String getISBN() {      return pISBN;     }     public String getTitle() {      return pTitle;     }     public Vector getAuthors () {          return pAuthors;      }     public String getAuthorString() {     Vector authors = getAuthors();     if (authors.size() == 1) {         return ((Author)authors.elementAt(0)).getName();     }     StringBuffer s = new StringBuffer();     Iterator i = authors.iterator();     while (i.hasNext()) {         Author author = (Author) i.next();         if (author == authors.firstElement()) {             s.append(author.getName());         }  else {              s.append("; " + author.getName());         }     }     return(s.toString());     }     public float getPrice() {      return pPrice;     }     public String getPriceString() {      NumberFormat nf = NumberFormat.getCurrencyInstance();      return nf.format(pPrice);     }     public java.sql.Date getPubDate() {      return pPubDate;     }     public String getPubDateString() {      SimpleDateFormat df = new SimpleDateFormat("MMM dd, yyyy");     return(df.format(getPubDate()));     }     public String getDescription() {      return pDescription;     }     public void setISBN(String ISBN) {      pISBN = ISBN;     }     public void setTitle(String Title) {      pTitle = Title;     }     public void setAuthors (Vector Authors) {          pAuthors = Authors ;     }     public void setPrice(float Price) {      pPrice = Price;     }     public void setPubDate(java.sql.Date PubDate) {      pPubDate = PubDate;     }     public void setDescription(String Description) {      pDescription = Description;     }     public static Product findProduct(String ISBN)      throws ProductActivityException {          if (products.get(ISBN) != null) {              return (Product) products.get(ISBN);          }          DBConnection dbConn = null;          Product prod = null;          try              {                  dbConn = TurbineDB.getConnection();                  if (dbConn == null) {                      Log.error("jdbc", "Can't get database connection");                      throw new ProductActivityException();                  }                  PreparedStatement pstmt =                       dbConn.prepareStatement(sql_bundle.getString("findQuery"));                  pstmt.setString(1, ISBN);                  ResultSet rs = pstmt.executeQuery();                  if (rs.next()) {                        prod = new Product();                        prod.setISBN(rs.getString("ISBN"));                        prod.setTitle(rs.getString("TITLE"));                        prod.setPrice(rs.getFloat("PRICE"));                        prod.setPubDate(rs.getDate("PUB_DATE"));                        prod.setDescription(rs.getString("DESCRIPTION"));                   }                   rs.close();                   pstmt.close();                   products.put(ISBN, prod);                   if (prod != null) {                       pstmt =                            dbConn.prepareStatement(sql_bundle.getString("authorQuery"));                       pstmt.setString(1, ISBN);                       rs = pstmt.executeQuery();                       while (rs.next()) {                           Author author =                                Author.findAuthor(rs.getString("AUTHOR_NAME"));                           prod.getAuthors().add(author);                           author.getBooks().add(prod);                       }                       rs.close();                       pstmt.close();                   }                }            catch (Exception e)                {                    Log.error("jdbc", "Error during findProduct", e);                    e.printStackTrace();                    throw new ProductActivityException();                }           finally               {                    try                        {                             TurbineDB.releaseConnection(dbConn);                        }                    catch (Exception e)                        {                            Log.error("jdbc", "Error during releaseConnection", e);                  }          }      return prod; } public static void main(String[] args) {     TurbineConfig tc = new TurbineConfig("com/bfg/props/",                                            "TurbineResources.properties");     tc.init();     try {         Product p =             findProduct("672320959");         if (p != null) {             System.out.println("Good Test: Find Real Product");             System.out.println("Author string is: " +                                p.getAuthorString());             System.out.println("Price is " + p.getPrice());         }  else {              System.out.println("Failed Test: Find Real Product");         }         }  catch (Exception e) {          System.out.println("Failed Test: Find Real Product");          e.printStackTrace();         }         try {             Product p =                 findProduct("notanisbn");             if (p != null) {                 System.out.println("Bad Test: Find Fake Product");             }  else {                  System.out.println("Good Test: Find Fake Product");             }         }  catch (Exception e) {              System.out.println("Failed Test: Find Fake Product");              e.printStackTrace();         } }} 

The top of this file looks a lot like Customer.java ”it contains all the accessors for the various bean properties that you need to get at. One difference is the HashMap called products. Unlike the Customer object, you don't want to read the product data from the database every time you need to look at it. The data rarely changes, and this is very costly in terms of performance. Instead, cache the data as you read it and use the cached value from that point forward.

One pitfall of taking this approach is that if you do change the product data and want to refresh things, you need to have a mechanism in place to accomplish this. With a vendor such as a book seller, whose inventory doesn't change every day, it's probably acceptable to just restart the server in the wee hours of the morning and let it reread everything. In a more dynamic retail environment, such as Wal-Mart, you would need to have some way of signaling the server to periodically update the caches. You would also need to build this kind of dynamic refreshing capability into the site if high availability was an issue.

I l @ ve RuBoard


MySQL and JSP Web Applications. Data-Driven Programming Using Tomcat and MySQL
MySQL and JSP Web Applications: Data-Driven Programming Using Tomcat and MySQL
ISBN: 0672323095
EAN: 2147483647
Year: 2002
Pages: 203
Authors: James Turner

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