CartBean

I developed a cartBean which works -- almost --  I am supposed to be able to type in a username in the argument and retrieve a list of all the items in the cart. Instead, the only way I get a list is if I type in at least one item to start along with the user name. I have tried reducing the args in the main method to 2 and eliminating the itemID as a parameter yet that won't let me run the program.
Where did I go wrong?
Thanks for any help.
Bette

package bette;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.GregorianCalendar;
import java.util.Iterator;

/**
 * <p>This is the Java bean used to get and display information about
 * a user's cart.
 *
 * @see ItemBean
 * @see DBBeanBase
 */
public class CartBean extends DBBeanBase
{
    /**
     * <p>Default constructor, creates an empty {@link CartBean}.
     */
    public CartBean()
    { super(); }

    /**
     * <p>This constructor creates a {@link CartBean} object associated with the
     * specified username and tiemId.  If there is no record in the data source with the
     * specified username or itemId, an {@link java.lang.Exception} is thrown.
     *
     * @param connection The {@link java.sql.Connection} object used to execute
     * the select statement that will retrieve the cart information.
     * @param iItemId and susername specifies the item id and username used to populate this object.
     *
     * @throws java.sql.SQLException if there is an error selecting the cart 
     * information.
     * @throws java.lang.Exception if there is an invalid username or if there
     * is an invalid itemId specified in the order.
     */
    public CartBean(Connection connection, String susername)
        throws SQLException, Exception
    {
        super();
        String strSQL = "SELECT " +
					        "Cart.itemId, " +
					        "Cart.qty, " +
					        "Item.description, " +
					        "Item.price " +
				        "FROM Cart, Item " +
					        "WHERE Cart.Username =  '" + susername + "'" +
					        " AND Cart.itemid = Item.itemid";
        
        Statement statement = connection.createStatement();
        ResultSet rs = statement.executeQuery(strSQL);
        put("username", susername);
        if (rs.next())
        {
            DBBeanBase newItem = new ItemBean(connection, rs.getInt("itemid"));
            newItem.put("qty", new Integer(rs.getInt("qty")));
            newItem.put("description", (rs.getString("description")));
            newItem.put("price", new Double(rs.getDouble("price")));
            
            m_itemsInCart.add(newItem);
            
        }
        else
       {
        	throw new Exception("Invalid username key: (" + susername + ")");
       }
    }


 
    /**
     * <p>This method returns the username of the user that placed this order.
     * @return the username of the user that placed this order.
     */
    public String getUsername()
    {return get("USERNAME").toString();}

  
    /**
     * <p>This method returns a {@link java.util.Collection} of the
     * {@link ItemBean ItemBeans} in this order.
     * @return a {@link java.util.Collection} of the
     * {@link ItemBean ItemBeans} in this order.
     */
    public Collection getItemsInCart()
    {return m_itemsInCart;}

	public static CartBean createCart(Connection connection, CustomerBean customerBean, ItemBean itemBean) throws SQLException,
																													Exception
	{

		Statement stmt = connection.createStatement();

		String strSQL = "INSERT INTO Cart (username, itemId, qty) " + "VALUES ('" + customerBean.getUsername() +
			"', " + itemBean.getItemId() + ", " + itemBean.getQuantity() + ")";

		stmt.executeUpdate(strSQL);

		return new CartBean(connection, customerBean.getUsername());
	}

    public void emptyCart(Connection connection)throws SQLException, Exception
	{
		// TODO run delete query to delete items from cart
    	m_itemsInCart.clear();
    	String strSQL = "DELETE FROM Cart WHERE username =  '" + getUsername() + "'";
    	Statement stmt = connection.createStatement();
		stmt.executeUpdate(strSQL);
	}

    
	/**
     * <p>This method returns a textual representation of this {@link CartBean}.
     * @return a textual representation of this {@link CartBean}.
     */
    public String toString()
    {
        StringBuffer sb = new StringBuffer();
        sb.append("\tUsername: " + getUsername() + "\n");
        sb.append("\tItems: \n");
        Iterator i = getItemsInCart().iterator();
        while (i.hasNext())
        {
            sb.append("\t\t" + i.next() + "\n");
        }
        return sb.toString();
    }

    /**
     * <p>Test method used to test this class.  This method creates an OrderBean
     * object using the specified DBURL and orderId.  The contents of the
     * OrderBean are printed to the console.
     *
     * <p>This test method assumes that the database is a MySQL database that
     * contains an 'sa' account with no password.
     *
     * <pre>
     *      usage: java DBBean [DBURL] [orderid]
     * </pre>
     *
     * @param args an array of command line arguments.  This test method
     * takes three parameters, one that specifies the DBURL and the other two specify
     * the orderId key.
     */
    public static void main(String[] args)
    {
    	Connection connection = null;
    	try
    	{
            if (args.length != 3)
            {
                System.out.println("usage: java CartBean [DBURL] [username] [itemId");
                System.exit(0);
            }

    		String strDBDriver = "com.mysql.jdbc.Driver";
    		String strDBURL = args[0];
    		String strDBUSER = "user1";
    		String strDBPWD = "user1";

    		Class.forName(strDBDriver);
    		connection = DriverManager.getConnection(strDBURL,
    												 strDBUSER,
    												 strDBPWD);

            CartBean cartBean = new CartBean(connection, args[1]);
            System.out.println("The Cart contains the following items:\n" + cartBean);
            cartBean.emptyCart(connection);
            System.out.println("The Cart is empty:\n" + cartBean);
            
           ItemBean itemBean = new ItemBean(connection, Integer.parseInt(args[2]));
            CustomerBean customerBean = new CustomerBean(connection, args[1]);
            CartBean newCart = CartBean.createCart(connection, customerBean, itemBean);
            System.out.println("New Cart:\n" + newCart);
            
    	}
    	catch (Exception e)
    	{
    		e.printStackTrace();
    	}
    	finally
    	{
    		try
    		{
    			connection.close();
    		}
    		catch (Exception e)
    		{}
    	}
    }

    protected ArrayList m_itemsInCart = new ArrayList();
}

Open in new window

Bette LamoreWeb Designer/Developer/GIS ProfessionalAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

jjardineCommented:
On line 177 you use args[2] to create the ItemBean.  So just changing teh args to 2 should cause an error on this line.

An additional unrelated note.  Think about changing your inline SQL statemnts to prepared statements.  It will help protect against SQL injection in your code.   I have included a link to OWASP's page on this.
http://www.owasp.org/index.php/Preventing_SQL_Injection_in_Java
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Bette LamoreWeb Designer/Developer/GIS ProfessionalAuthor Commented:
What the program is supposed to do is add items to the cart so long as the user clicks on them and remove them if the user clicks on remove items and then pull up all the items in the user cart by username (from the collection) and then delete the cart once the program is done. My program is not doing that. This is a really difficult program for me and I haven't been able to find any prototypes on-line. Lots of JSP scripts -- yet no CartBean examples.
0
Bette LamoreWeb Designer/Developer/GIS ProfessionalAuthor Commented:
Thank you jjardine for finding the one error, yet there were many more in the code. Finally worked them all through myself, yet I am giving you partial credit. Here is correct code:

package bettelamore;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/**
 * <p>
 * This is the Java bean used to get and display information about a user's
 * cart.
 * 
 * @see ItemBean
 * @see DBBeanBase
 */
public class CartBean extends DBBeanBase
{
	/**
	 * <p>
	 * Default constructor, creates an empty {@link CartBean}.
	 */
	public CartBean()
	{
		super();
	}

	/**
	 * <p>
	 * This constructor creates a {@link CartBean} object associated with the
	 * specified username. If there is no record in the data source
	 * with the specified username or there is an incorrect itemId put into the cart, 
	 * an {@link java.lang.Exception} is thrown.
	 * 
	 * @param connection The {@link java.sql.Connection} object used to execute the
	 * select statement that will retrieve the cart information.
	 * @param susername specifies the username used to populate this object.
	 * 
	 * @throws java.sql.SQLException if there is an error selecting the cart information.
	 * @throws java.lang.Exception if there is an invalid username or if there is an invalid
	 *             itemId specified in the cart.
	 */
	public CartBean(Connection connection, String susername) throws SQLException, Exception
	{

		super();
		String strSQL = "SELECT " + "Cart.itemId, " + "Cart.qty, " + "Item.description, " + 
						"Item.price " + "FROM Cart, Item " + "WHERE Cart.Username =  '" + 
						susername + "'" + " AND Cart.itemid = Item.itemid";

		Statement statement = connection.createStatement();
		ResultSet rs = statement.executeQuery(strSQL);
		put("username", susername);
		while (rs.next())
		{
			DBBeanBase newItem = new ItemBean(connection, rs.getInt("itemid"));
			newItem.put("qty", new Integer(rs.getInt("qty")));
			newItem.put("description", (rs.getString("description")));
			newItem.put("price", new Double(rs.getDouble("price")));
			m_itemsInCart.add(newItem);
		}
	}

	/**
	 * <p>
	 * This method returns the username of the user that placed this order.
	 * 
	 * @return the username of the user that placed this order.
	 */
	public String getUsername()
	{
		return get("USERNAME").toString();
	}

	/**
	 * <p>
	 *  This method returns a {@link java.util.Collection} of the
	 * {@link ItemBean ItemBeans} in this cart.
	 * 
	 * @return a {@link java.util.Collection} of the {@link ItemBean ItemBeans}
	 *         in this cart.
	 */
	public Collection getItemsInCart()
	{
		return m_itemsInCart;
	}


	public static CartBean createCart(Connection connection, CustomerBean userBean) 
														throws SQLException, Exception
	{
		return new CartBean(connection, userBean.getUsername());
	}

	/**
	 * <p>
	 * This method iterates through the ItemBean to determine if the currentItem
	 * exists as an item in the ItemBean and is returned as foundItem.
	 * If item not found, the new item is added to itemBean 
	 * by using an INSERT statement.
	 * @throws SQLException if there is an error selecting the cart information.
	 * @throws Exception if itemId not found
	 * @param connection The {@link java.sql.Connection} object used to execute 
	 * the select statement that will retrieve the cart information.
	 * @param itemBean specifies the itemBean used to populate this object.
	 * @throws SQLException if there is an error selecting the cart information.
	 * @throws Exception if more than 1 item at a time was added to cart
	 */
	public void addItem(Connection connection, ItemBean itemBean) 
											throws SQLException, Exception
	{
		Statement stmt = connection.createStatement();

		ItemBean foundItem = findItem(itemBean);

		if (foundItem == null)
		{
			String strSQL = "INSERT INTO Cart (username, itemId, qty) " + 
							"VALUES ('" + getUsername() + "', " + itemBean.getItemId() + ", 1)";
			int numInserted = stmt.executeUpdate(strSQL);
			if (numInserted == 1)
			{
				itemBean.put("QTY", 1);
				m_itemsInCart.add(itemBean);
			}
			else
			{
				throw new Exception("Could not add new item " + itemBean + " for customer " + 
						getUsername());
			}
		}
		else
		{
			int newQty = foundItem.getQuantity() + 1;
			String strSQL = "UPDATE Cart SET qty = " + newQty + " WHERE username = '" + 
							getUsername() + "' AND itemId=" + foundItem.getItemId();
			int numUpdated = stmt.executeUpdate(strSQL);
			if (numUpdated == 1)
			{
				foundItem.put("QTY", newQty);
			}
			else
			{
				throw new Exception("More than one cart item updated for " + itemBean + 
									" and customer " + getUsername());
			}
		}
	}

	
	/**
	 * <p>
	 * This method iterates through the ItemBean to determine if the currentItem
	 * exists as an item in the ItemBean and is returned as foundItem.
	 * If not, the foundItem is returned as null. As this iteration code was performed
	 * several times in this Bean, it was refactored as a method.
	 * 
	 * @param itemBean specifies the itemBean used to populate this object.
	 * @return foundItem returns the currentItem as foundItem or it is
	 * returned as null.
	 */
	private ItemBean findItem(ItemBean itemBean)
	{
		Iterator it = m_itemsInCart.iterator();
		ItemBean foundItem = null;
		while (it.hasNext())
		{
			ItemBean currentItem = (ItemBean) it.next();
			if (currentItem.getItemId().equals(itemBean.getItemId()))
			{
				foundItem = currentItem;
				break;
			}
		}
		return foundItem;
	}
	
	/**
     * <p>
     * This method searches for item to be removed and if item not in cart, throws an exception
     * If item is found and the quantity = 1 then the item is removed from the cart
     * by a SQL statement.   If the item is found and quantity is greater than one, a SQL DELETE
     * statement reduces the item's quantity by 1 in the itemBean.
     * @param connection The connection to the database
     * @param itemBean The itemBean of which you want to remove
     * @throws Exception If item not found or if user tries to remove more than one item at a time 
     * from the cart, an Exception is thrown
     */
	public void removeItem(Connection connection, ItemBean itemBean) throws Exception
	{
		Statement stmt = connection.createStatement();

		ItemBean foundItem = findItem(itemBean);

		if (foundItem == null)
		{
			throw new Exception("Item " + itemBean + " is not in user " + getUsername() + 
								"'s cart.");
		}
		else
		{

			if (foundItem.getQuantity() == 1)
			{
				String strSQL = "DELETE FROM Cart WHERE username = '" + getUsername() + 
								"' and itemId = " + itemBean.getItemId();
				int numDeleted = stmt.executeUpdate(strSQL);
				if (numDeleted == 1)
				{
					m_itemsInCart.remove(foundItem);
				}
				else
				{
					throw new Exception("Could not delete item " + itemBean + 
										" for customer " + getUsername());
				}
			}
			else
			{
				int newQty = foundItem.getQuantity() - 1;
				String strSQL = "UPDATE Cart SET qty = " + newQty + " WHERE username = '" + 
								getUsername() + "' AND itemId=" + foundItem.getItemId();
				int numUpdated = stmt.executeUpdate(strSQL);
				if (numUpdated == 1)
				{
					foundItem.put("QTY", newQty);
				}
				else
				{
					throw new Exception("More than one cart item updated for " + itemBean + 
										" and customer " + getUsername());
				}
			}
		}
	}

	
	/**
	 * <p>
	 * This method empties the cart by using a DELETE statement.
	 * 
	 * @return the Cart as empty.
	 */
	public void emptyCart(Connection connection) throws SQLException, Exception
	{
		m_itemsInCart.clear();
		System.out.println(get("USERNAME"));
		String strSQL = "DELETE FROM Cart WHERE username =  '" + getUsername() + "'";
		Statement stmt = connection.createStatement();
		stmt.executeUpdate(strSQL);
	}

	/**
	 * 
	 * This method returns a textual representation of this {@link CartBean}.
	 * 
	 * @return a textual representation of this {@link CartBean}.
	 */
	public String toString()
	{
		StringBuffer sb = new StringBuffer();
		sb.append("\tUsername: " + getUsername() + "\n");
		sb.append("\tItems: \n");
		Iterator i = getItemsInCart().iterator();
		while (i.hasNext())
		{
			sb.append("\t\t" + i.next() + "\n");
		}
		return sb.toString();
	}

	/**
	 * <p> Test method used to test this class. This method created a CartBean object using 
	 * the specified DBURL and user name/ The contents of the Cart are printed to
	 * the console.
     * 
	 * Next the cartBean is emptied and the items in the cart are again printed out (0). 
	 * @emptyCart empties the cart.
	 * 
	 * Next one each of the array of items that were in the CartBean before it was emptied
	 * is added back into the cart and printed out.
	 * @addItem where items are added back in.
	 * 
	 * Next the first item is added into the cart and the cart updated and contents printed out.
	 * @addItem where an item is added back in.
	 * 
	 * Next an item is reduced in quantity or removed if quantity = 0 and contents of cart
	 * printed out.
	 * @removeItem where an item is reduced in quantity or removed if quantity = 0.
	 * 
	 * Next the same item is reduced in quantity or removed if quantity = 0 and contents
	 * of cart printed out.
	 * @removeItem where an item is reduced in quantity or removed if quantity = 0.
	 * 
	 * Next the CartBean is refreshed and printed to console.
	 * 
	 * Next an invalid username is submitted and the exception thrown.
	 * @throws java.lang.Exception if there is an invalid username or if there is an invalid
	 *             itemId specified in the cart.
	 *             
	 * <p> This test method assumes that the database is a MySQL database that 
     * contains an 'user1' account with a password 'user1'.
	 * 
	 * <pre>
	 *      usage: java DBBean [DBURL] [username]
	 * </pre>
	 * 
	 * @param args an array of command line arguments. This test method takes
	 * two parameters, one that specifies the DBURL and the other that
	 * specifies the username.
	 * 
	 */
	public static void main(String[] args)
	{
		Connection connection = null;
		try
		{
			if (args.length != 2)
			{
				System.out.println("usage: java CartBean [DBURL] [username]");
				System.exit(0);
			}

			String strDBDriver = "com.mysql.jdbc.Driver";
			String strDBURL = args[0];
			String strDBUSER = "user1";
			String strDBPWD = "user1";

			Class.forName(strDBDriver);
			connection = DriverManager.getConnection(strDBURL, strDBUSER, strDBPWD);

			CustomerBean customerBean = new CustomerBean(connection, args[1]);
			CartBean cartBean = CartBean.createCart(connection, customerBean);

			Collection itemsInCart = new ArrayList(cartBean.getItemsInCart());
			System.out.println("The Cart contains the following items:\n" + itemsInCart);

			cartBean.emptyCart(connection);
			System.out.println("After cartBean.emptyCart(): " + cartBean.getItemsInCart());

			Iterator it = itemsInCart.iterator();
			while (it.hasNext())
			{
				ItemBean itemBean = (ItemBean) it.next();
				cartBean.addItem(connection, itemBean);
				System.out.println("Adding item to the cart: " + itemBean);
			}
			System.out.println("The Cart contains the following items after adding the items back: \n"
								+ cartBean.getItemsInCart());

			if (itemsInCart.size() > 0)
			{

				ItemBean itemBean = (ItemBean) itemsInCart.iterator().next();

				cartBean.addItem(connection, itemBean);
				System.out.println("Adding the first item again: \n" + cartBean.getItemsInCart());

				cartBean = new CartBean(connection, customerBean.getUsername());
				System.out.println("Refreshing cart from DB: \n" + cartBean);

				cartBean.removeItem(connection, itemBean);
				System.out.println("Removing the first item: \n" + cartBean.getItemsInCart());

				cartBean.removeItem(connection, itemBean);
				System.out.println("Removing the first item again: \n" + cartBean.getItemsInCart());
				
				cartBean = new CartBean(connection, customerBean.getUsername());
				System.out.println("Refreshing cart from DB: " + cartBean);


				// Test an invalid user:
				CustomerBean cb = new CustomerBean(connection, "invalid user");
				cartBean = CartBean.createCart(connection, cb);
			}

		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				connection.close();
			}
			catch (Exception e)
			{
			}
		}
	}

	protected ArrayList m_itemsInCart = new ArrayList();
}

Open in new window

0
Bette LamoreWeb Designer/Developer/GIS ProfessionalAuthor Commented:
The first comment of jjardine was only one error -- there were many in the code. I gave jjardine time to reply to my comments about his solution not being complete and explained what I needed. While waiting for some additional assistance, I kept working on the code until it finally worked for me -- I found my own solution. I prorated the points according to what I thought was fair.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Programming Languages-Other

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.