Saturday, May 16, 2009

Shopping Cart Web Application - Part 4 - Build

Introduction
What is the benefit of running build scripts? As a developer you may at first think it is a waste of time. After all most IDE’s are able to build package and deploy your projects with the click of a button. So why go through all the hassle of writing a build script?

A build process becomes essential when developing in a team and where the application you are working on requires other projects that are not necessarily built by you but by another team in your organization. It is also a good idea to automate your build process so that the build is started automatically by another service. There are a couple of tools available that can be used to manage your build process. One I am familiar with and like very much is Hudson continuous integration tool.

What you need before we get started
  • I use Eclipse as my IDE. Eclipse comes with a built in Ant plug-in so if you have Eclipse installed you have almost everything you need to get started.
  • You will need the previous third party libraries that were mentioned and used in earlier parts to this tutorial

What we will cover
  • Which build tool to use?
  • The build script

Level
  • Beginner

Which build tool to use?
There are a number of tools available that you can use to write build scripts. Two of the most popular are:
  1. Apache Ant
  2. Apache Maven

Ant has been around a lot longer than Maven however the Maven framework is growing in popularity every day. They both are very good tools to use. I like Ant because it is very simple to use and you can do pretty much anything you want with it. I also like Maven for a number of reasons one of them being Maven’s dependency management framework. Ant also has its own dependency management framework called Ivy which is very similar to Maven’s dependency management.

I have chosen to use Ant for my examples as I think it is quicker to get up and running then Maven and the full extent of Maven and Ivy is out of the scope for this tutorial.

The build script
Please download the ShoppingCartPart4.zip and import the shopping-cart-core-build-part4 project into Eclipse. I created a build file called build.xml and saved it to a new folder called build in the project root.

To run the Ant script targets within Eclipse you need to open the Ant View, you can do this by selecting Window -> Show View -> Other -> Ant -> Ant. An Ant tab will appear in your workspace. Right click in the Ant view window and select Add Buildfiles. Navigate to the build.xml file in the shopping-cart-core-build-part4 project and select Ok. You should see the following targets in the Ant view:

  • build – builds the whole project
  • clean – deletes compilation directory
  • compile – compiles the source files
  • package – packages the classes into a JAR
  • test – runs the JUnit tests we created in the previous tutorial

You can run any of them by double clicking on their name. If you double click on build all the targets will be run and you should see build information displayed in your Console view.








































































Monday, May 11, 2009

Shopping Cart Web Application - Test cases - Part 3

Introduction
Software testing is a very important aspect to any software development lifecycle. It provides stakeholders with information about the quality of the product that is being tested.


What you need before we get started
  • You will need to install the Sun JDK on your local pc in order to compile the projects code. The version I used was JDK1.6.0_07. I recommend using this version or the latest in case you run into any problems with the different versions that are available.
  • I use Eclipse as my IDE to develop in. You don’t need Eclipse if you are just going to read this tutorial but if you intend to test the application then I would recommend it.
  • You can import the project I created for this tutorial into Eclipse and run the unit test case.
  • You will need the following third party libraries in order to run the test:


What we will cover
  • What is unit testing?
  • Code generation
  • Import generated source into Eclipse
  • JUnit
  • Create the unit test
  • Annotations
  • Running the test


Level
  • Beginner


Testing
There are a number of different software testing methods, namely:
  • Unit testing - tests the minimal software component, or module. Each unit (basic component) of the software is tested to verify that the detailed design for the unit has been correctly implemented.
  • Integration testing - exposes defects in the interfaces and interaction between integrated components. Progressively larger groups of tested software components corresponding to elements of the architectural design are integrated and tested until the software works as a system.
  • System testing - tests a completely integrated system to verify that it meets its requirements.
  • System integration testing - verifies that a system is integrated to any external or third party systems defined in the system requirements.

This tutorial will only focus on unit testing. Unit testing is a software design and development method where the programmer verifies that individual units of source code are working properly. Unit testing is a simple and effective process that improves delivery, quality and flexibility of a project. Having unit tests makes it easier and safer to modify the code because the tests document and protect the intended behavior and will instantly catch any regressions. A unit is the smallest testable part of an application

The goal of unit testing is to isolate each part of the program and show that the individual parts are correct. A unit test provides a strict, written contract that the piece of code must satisfy. As a result, it affords several benefits. Unit tests find problems early in the development cycle.

The goal for this tutorial is to show you how to write a unit test for a particular class using a third party library called JUnit.


Code Generation
I was able to take the class diagram we created in the previous exercise and generate Java source from it using ArgoUML. I used the generated source as my base project to work from and modified the code slightly. I also created a unit test class. Please download the file ShoppingCartTestCasesPart3.zip that contains the shopping-cart-core-test-cases-part3 Eclipse project I created for this tutorial.


Import existing project into Eclipse
You can follow these steps to import the shopping-cart-core-test-cases-part3 project into Eclipse:
  • Open Eclipse
  • Select File from the top navigation menu
  • Select Import
  • Select Existing Projects into Workspace under the General folder
  • Select the Select archive file radio button
  • Browse to where you saved the ShoppingCartTestCasesPart3.zip file
  • Make sure the shopping-cart-core-test-cases-part3 project is selected
  • Click the Finish button

The shopping-cart-core-test-cases-part3 project should be imported into your Eclipse workspace. The project may not compile because it may require a library that isn't part of the project. The next section talks a little about configuring your project so that it is pointing to the required libraries.


JUnit
I have chosen to use JUnit as a framework to build my tests. JUnit is a unit testing framework for the Java programming language. I added the JUnit library we are going to need for our test case to our project. How did I do this you ask? I chose to create a simple project called LIBS where I will store all my libraries inside. I copied the JUnit library to the LIBS project. I than included the library in the projects classpath by right clicking on the project -> Properties -> Java Build Path -> Libraries -> Add JARs -> LIBS -> JUnit4.5.


Create the unit test
1. Create test source folder
I created a new source folder called test where all my test classes will go I also added it as a src folder by right clicking on the test folder -> Build Path -> Source -> Use as Source Folder.

2. Create test class
I created a package called com.mydomain.shoppingcart.service.test under the new test folder. And within this package I created the ShoppingServiceTest class.

ShoppingServiceTest.java


package com.mydomain.shoppingcart.service.test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import java.util.ArrayList;
import java.util.List;

import org.junit.Before;
import org.junit.Test;

import com.mydomain.shoppingcart.bo.Basket;
import com.mydomain.shoppingcart.bo.Item;
import com.mydomain.shoppingcart.service.ShoppingService;
import com.mydomain.shoppingcart.service.impl.ShoppingManager;

/**
* @author Ross
*/
public class ShoppingServiceTest {
private Basket basket;
private ShoppingService shoppingManager;
private Item testItem;
private int itemsCount;

/**
* Tests adding an item to the basket.
*/
@Test
public void addItem() {
int itemCount = basket.getItemCount();
basket.addItem(testItem);
double expectedBalance = 0;
for (Item item : basket.getItems()) {
expectedBalance = expectedBalance + item.getPrice();
}
assertEquals(expectedBalance, basket.getBalance(), 0.0);
assertEquals(itemCount + 1, basket.getItemCount());
}

/**
* Tests emptying the basket.
*/
@Test
public void empty() {
basket.empty();
assertEquals(0, basket.getItemCount());
}

/**
* Tests finding items.
*/
@Test
public void findItems() {
try {
List<Item> allItems = new ArrayList<Item>(shoppingManager.findItems());
assertEquals(itemsCount, allItems.size());
} catch (Exception e) {
e.printStackTrace();
fail("Error in Shopping Manager");
}
}

/**
* Tests removing an item from the cart.
*/
@Test
public void removeItem() {
int itemCount = basket.getItemCount();
for (Item item : basket.getItems()) {
basket.removeItem(item);
break;
}
assertEquals(itemCount - 1, basket.getItemCount());
}

/**
* Sets up the test fixture.
*
* Called before every test case method.
*/
@Before
public void setUp() {
shoppingManager = new ShoppingManager();
itemsCount = shoppingManager.findItems().size();
testItem = new Item(1l, "Candy Cotton", "Candy coated milky tarts", 8.50d);
basket = new Basket();
basket.addItem(new Item(2l, "Jelly Beans", "Jelly icecream waffle cream", 18.99d));
basket.addItem(new Item(3l, "Jam Doughnut", "Strawberry jam and Christmas pudding", 23.00d));
}
}

Annotations
JUnit4 uses annotations to define which methods should be tested. The @Test line in the code is an example of an annotation. It is used to identify which methods should be treated as test methods. A test method will be executed when your JUnit tests are run.

Many APIs require a fair amount of boilerplate code (any code that is or can be reused in new contexts or applications without being changed much from the original). For example, in order to write a JAX-RPC web service, you must provide a paired interface and implementation. This boilerplate could be generated automatically by a tool if the program were “decorated” with annotations indicating which methods were remotely accessible.

Annotations are like meta-tags that you can add to your code and apply them to package declarations, type declarations, constructors, methods, fields, parameters, and variables. As a result, you will have helpful ways to indicate whether your methods are dependent on other methods, whether they are incomplete, whether your classes have references to other classes, and so on.

Annotation-based development relieves Java developers from the pain of cumbersome configuration. Annotation-based development lets us avoid writing boilerplate code under many circumstances by enabling tools to generate it from annotations in the source code. This leads to a declarative programming style where the programmer says what should be done and tools emit the code to do it.

Looking at our ShoppingServiceTest class we have a number of methods. The first is the setUp method. This method has a JUnit4 annotation defined above it called @Before. This method gets called before any test methods. It is used to initialize any global variables used within the test methods.

The following test methods are defined in our class:
  • empty() - Empty a basket and check whether or not the basket has any items
  • addItem() - Add an Item to the Basket then check whether or not the Item was added
  • removeItem() - Remove an item from the basket then check whether or not the Item was removed
  • findItems() - Lookup a list of all the items and compare the number of items retrieved with the actual number of items


Running the test
We will run our tests within Eclipse to do this right click on our test class ShoppingServiceTest.java -> Run as -> JUnit test.

JUnit should run and you should be able to see the results of your test in the JUnit View tab.
That is all on JUnit testing for now. I would strongly encourage you to write other tests and run them to really get comfortable with this framework. Until the next tutorial, happy testing!

Wednesday, May 6, 2009

Shopping Cart Web Application - Design - Part 2

Introduction
In this article we define the classes the shopping cart application is going to use. We also build a sequence diagram for one of our use cases.

Before we get started
I created the diagrams using ArgoUML. It is a UML modeling tool that you can download for free. If you download and install ArgoUML you should also be able to open the ShoppingCart modeling project I created.

What we will cover
  • Class diagrams
  • Sequence diagrams

Level
  • Introductory

Class Diagrams
A class diagram is used to describe the structure of a system by showing the system's classes, their attributes, and the relationships between the classes.
Figure 1 – shopping cart class diagram

The Shopping Cart Class Diagram defines the following classes:

1. Business Objects (Domain Model)
A domain model can be thought of as a conceptual model of a system which describes the various entities involved in that system and their relationships. The model identifies the relationships with other entities within the system as well as their methods and attributes.  The following two classes make up our domain model:
  • Basket
  • Item

2. Business Delegate
For simplicity the shopping cart application classes that handle the business logic reside within the web application. Although this is not always the case, more often than not the business logic resides outside of the web application. The Business Delegate pattern can be used to hide the underlying implementation details of the business service, such as lookup and access details. Our application doesn’t apply the business delegate pattern but I do feel it us important to mention it. The classes that handle the business logic are:
  • ShoppingService
  • ShoppingManager

3. View classes
The view classes represent the user interface views of our application. There is also a helper class that manages all the calls made to the Shopping Manager service class. These classes are modeled after the View Helper design pattern: 
  • Items
  • Checkout
  • ShoppingViewHelper
The above mentioned class diagrams are very high level and intended for beginners. I would encourage you to search the web for more in depth tutorials. Here are a few more examples:

Sequence Diagrams
A sequence diagram shows how processes operate with each other and in what order. 
  • The vertical lines in sequence diagrams represent different processes or objects that make up a system.
  • The horizontal arrows are messages exchanged between the different processes and objects in the order in which they occur.
Sequence diagrams are used to look at the behavior of several objects within a single use case. They are useful to identify any architectural or logical problems at an early stage.
I wouldn’t recommend doing a sequence diagram for every use case, only the real important ones.
Figure 2 – find items sequence diagram
Once again I highly recommend you take the time to search the web for further reading as well as for you to apply what you have learnt in your own projects. Here is another introduction to sequence diagrams:

Friday, May 1, 2009

Shopping Cart Web Application - Analysis - Part 1

Introduction
Welcome to the first tutorial I have written in this series of learning how to develop Java web applications. I will be using the same application throughout this series so I thought what better way to kick start this series than to start at the beginning. Before any code is written it is a good idea to understand what is required from us. In this tutorial we are going to define what those requirements are and then we will package those requirements in an industry recognized format and standard known as UML use cases.

What we will cover
  • Define business requirements
  • Specify the use cases for our application based on the requirements
  • Write use case specification for one of our use cases

Level
  • Introductory

Overview
The shopping cart application will be an online shopping store. I have decided that our store will be called “Scooby Doo's Little Shop of Horrors”. A visitor to the website will be able to browse a number of different ingredients and add them their virtual shopping basket so that ultimately they can create their very own custom made Scooby Dooby Monster Sandwich. Yeah I bet that just wet your appetite.

Requirements
  1. User must be able to browse items that the store is selling.
  2. Each item should have at least a price associated to it as well as a name and a description. Would be nice if it had an image. 
  3. The user should be able to enter in the quantity of how many items he / she wants to purchase (for now this can be optional). 
  4. There should be a link / button next to the item so that the user can add this item to their shopping cart. 
  5. There should be a checkout link / button that the user can click on at any time. This link will take the user to the checkout page. 
  6. When the user clicks on the checkout link he / she must be redirected to another page where the items the user has added to the shopping cart are displayed, along with their name, description and price. A total price of how much all items cost must also be displayed. 
  7. On the checkout page the user must be able to confirm payment. On clicking this link the user is taken to a confirmation page that says: “Thank you. You order has been processed.” This page should also have a link that takes the user back to the home page where they can start a new order if they so choose. 

Use Case Diagram
Our next step will be to identify the use cases that make up our application. A use case is a description of a system’s behaviour as it responds to a request that originates from outside of that system. A use case diagram is used to graphically represent the overview of the use cases. A use case diagram models the behavior of a system and helps to capture the requirements. It identifies the interactions between the system and its actors, and defines the scope of the system. 

There are two main components used within use case diagrams:
  • Actor - Represents a role of a user that interacts with the system. The user can be a human user, an organization, a machine, or another external system.
  • Use case - Describes a function that a system performs to achieve the user's goal. A use case must yield an observable result that is of value to the user of the system.
 
The use cases and actors shown in a use case diagram describe what the system does and how the actors use it, but not how the system operates internally. To relate an actor and a use case, you can create an association relationship to indicate the connection between the two model elements.

For our shopping cart application I have identified the following use cases based on the business requirements:
  • Show items – Display a list of items for sale
  • Add item to shopping cart – Add an item to the shopping cart
  • Checkout – Display the list of items added to the shopping cart along with the total cost
  • Process payment – Empty the shopping cart and display a meaningful message thanking the user for their payment 



Figure 1 – shopping cart use case diagram

For further reading I would encourage you to search on the internet for more use case diagram tutorials, two examples would be: 


The above diagram was created using ArgoUML. You can download it and use it for free. There is also an Eclipse plugin but I haven’t been too impressed with it and find the standalone IDE much better to use. Having said that I wouldn’t say it is a great tool either. I have tried a few free tools available but haven't been completely satisified in finding a tool that can be used to build most diagrams. 

ArgoUML have a manual with some pretty good advice in terms of UML design and project development principles. I highly recommend you take the time to read it: 

 
Use Case Specification
Once the use cases have been identified it is time to flesh out the detail for each one. This is done in a use case specification document. Some software development processes do not require anything more than a simple use case to define requirements. However, some other development processes require detailed use cases to define requirements. 

There is no standard template for documenting use cases. I would encourage you to use templates that work for you and your company. A typical specification would have the following sections:
  • Use case name
  • Version
  • Goal
  • Summary
  • Actors
  • Preconditions
  • Triggers
  • Basic course of events
  • Alternative paths
  • Post conditions
  • Business rules
  • Notes
  • Author and date

I created a very basic Shopping Cart - Add Item Use Case Specification document, you can download it from here.